From 92a15d3e1a1bbc172e189ce59c72c7b73b865e89 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 22 Oct 2026 15:44:03 -0400 Subject: [PATCH 1/5] rename(547): the header draws the clasped grimoire, and the README takes the standard shape AppLogo still drew the old open book with a spark, so the new mark showed only in the browser tab. It now draws the same clasped grimoire as favicon.svg, in the mark's own fixed colours. That covers the header and the sign-in, register and password pages. The README follows the house order: the logo, name and tagline, a short summary, quick start including the plugin install, the settings a reader must set, setup pitfalls, updating and backups, features grouped by what you do, troubleshooting by the error text, development, and licence. Co-Authored-By: Claude Opus 5.5 --- README.md | 121 ++++++++++++++++++++++------ frontend/src/components/AppLogo.vue | 58 +++++-------- 2 files changed, 113 insertions(+), 66 deletions(-) diff --git a/README.md b/README.md index ae5c924e..38d45cfe 100644 --- a/README.md +++ b/README.md @@ -1,42 +1,111 @@ -# Fabled Grimoire +

+ +

-A self-hosted work system-of-record for software projects, built to be driven by Claude Code. Notes, tasks, issues, projects, milestones, rules, and stored processes — reachable from Claude via a built-in MCP endpoint and a bundled Claude Code plugin, with a clean web UI for humans. No in-app LLM; Claude is the sole assistant. +

Fabled Grimoire

-## Features +

A self-hosted system of record for the work you do with Claude Code.

-Notes, tasks and issues; projects with milestones as plans; rules that reach Claude when its work matches them or at a moment of work; lessons, snippets of prior art and a ledger of the code they account for; design systems; ideas shared across projects on the same platform; and stored processes. Semantic search feeds both Claude's recall and the plugin's context injection. A knowledge graph, sharing with users and groups, and scheduled backups round it out. See [Features](docs/features.md). +Claude records what it learned, decided and built in Grimoire, and that record reaches the next session, so a solution is recalled instead of reinvented. Notes, tasks, plans, rules, lessons and reusable code live in one place. Claude reaches them through a built-in MCP endpoint and the bundled Claude Code plugin, and people read and edit the same records in the web UI. There is no language model inside Grimoire: Claude is the only assistant. -## Quick Start +## Quick start -**Prerequisites:** Docker and Docker Compose. No GPU or local model needed — Claude is the sole assistant, reached over MCP. - -Download [`docker-compose.quickstart.yml`](docker-compose.quickstart.yml) from this repo, then: +You need Docker with Compose. Download [`docker-compose.quickstart.yml`](docker-compose.quickstart.yml), then: ```bash -# Optional but recommended — set a secret key -export SECRET_KEY=your-random-secret-here +SECRET_KEY=$(python3 -c 'import secrets; print(secrets.token_hex(32))') \ + docker compose -f docker-compose.quickstart.yml up -d +``` +Open `http://localhost:5000`. The first account you register becomes the admin. + +To connect Claude, create an API key under **Settings → MCP Access**, then in Claude Code: + +``` +/plugin marketplace add https://git.fabledsword.com/bvandeusen/FabledGrimoire.git +/plugin install grimoire@grimoire-plugin +``` + +The plugin asks for your Grimoire URL and the API key. Settings → MCP Access shows the exact commands for your instance. + +## Configuration + +Set these in the environment or a `.env` file beside the compose file: + +| Variable | Needed | What it does | +|----------|--------|--------------| +| `SECRET_KEY` | Yes | Signs sessions and seals stored credentials. Set it once and keep it | +| `BASE_URL` | Behind a proxy | The public URL, used in email links and SSO redirects | +| `SECURE_COOKIES` | Over HTTPS | `true` when Grimoire is served over HTTPS | +| `TRUST_PROXY_HEADERS` | Behind a proxy | `true` to read the client address from the proxy's headers | +| `POSTGRES_PASSWORD` | Recommended | The database password (defaults to `grimoire`) | + +Everything else (registration, email, SSO, git forge connections, retrieval tuning, backups) is in **Settings**, or listed in [Configuration](docs/configuration.md). + +## Setup pitfalls + +- **Keep your `SECRET_KEY`.** Forge tokens and the backup bucket's secret are sealed under it. If it changes, Settings asks you to enter those credentials again. +- **The embedding model downloads on first use**, into the `/data` volume. Without internet access, semantic search falls back to keyword search until the model is in place. +- **Behind a reverse proxy, turn off response buffering** for `/mcp`, because MCP responses stream. [Configuration](docs/configuration.md#behind-a-reverse-proxy) has an Nginx example. + +## Updating and backups + +```bash +docker compose -f docker-compose.quickstart.yml pull docker compose -f docker-compose.quickstart.yml up -d ``` -Open `http://localhost:5000`. The first user to register becomes admin. To connect Claude, create an API key under **Settings → MCP Access** and install the Claude Code plugin — see [API Keys & MCP](docs/api-keys-and-mcp.md). +Database migrations run when the app starts. Claude Code updates the plugin from its marketplace; run `/reload-plugins` after an update. -> **Development:** To build from source, see [Development](docs/development.md). +Everything Grimoire stores is in the database. **Settings → Data → Scheduled backups** writes a daily backup to a folder or an S3-compatible bucket, and `python -m grimoire.restore` brings a fresh instance back from one. See [Backups](docs/backups.md). -## Documentation +## Features -| Doc | Contents | -|-----|----------| -| [Architecture](docs/architecture.md) | Stack, design decisions, data models, key services | -| [Configuration](docs/configuration.md) | Environment variables, Docker Compose, production setup, security | -| [Features](docs/features.md) | Detailed feature breakdown and keyboard shortcuts | -| [Development](docs/development.md) | Dev workflow, CI/CD, migrations, release process | -| [API Keys & MCP](docs/api-keys-and-mcp.md) | API keys and installing the Claude Code plugin | -| [SSO / OAuth](docs/sso-oauth.md) | OIDC setup for Authentik, Keycloak, and other providers | -| [Backups](docs/backups.md) | Scheduled backups to a folder or S3, and restoring from one | -| [Design system](docs/design-system.md) | The FabledSword house style and how Grimoire applies it | -| [API Reference](docs/api-reference.md) | All REST API endpoints | +**Working with Claude** +- Claude enters a project and gets a short primer: its goal, current plans, open tasks and areas. +- Your rules reach Claude when its work matches them, or at a moment of work such as finishing a task or pushing code. +- Before Claude writes a file or runs a command, the plugin shows it the rules, lessons and reusable code that may apply. +- Stored procedures, such as a drift audit, become Claude Code skills. -## License +**Recording the work** +- Notes in a Markdown editor, with wikilinks, tags and version history. +- Tasks, issues and time-boxed investigations, with work logs that the next session reads first. +- Plans as milestones: a design plus ordered steps. +- Lessons learned the hard way, linked to the rules they illustrate. +- Duplicate checks, so a new record that matches an existing one updates it instead. -This project is privately maintained. +**Reusing code** +- Snippets of reusable code, each with when to reach for it and where it lives in the repo. +- With a git forge connected, Grimoire tracks every function and style in your repos and shows which ones are still unaccounted for. +- Ideas shared across projects on the same platform, with each project's answer recorded. +- Design systems with tokens, inheritance and a generated stylesheet. + +**For people** +- A web UI to browse, search and edit everything, plus a graph of how notes connect. +- Sharing with users and groups, as viewer, editor or admin. +- Email and password sign-in, optional SSO through OIDC, and invite links. +- Personal export to Markdown or JSON, and admin backup and restore. + +The full list is in [Features](docs/features.md). + +## Troubleshooting + +| What you see | Why | Fix | +|--------------|-----|-----| +| `SECRET_KEY is set to the insecure default` at startup | `SECURE_COOKIES=true` while `SECRET_KEY` is still the built-in default | Set `SECRET_KEY` | +| `Can't locate revision identified by '…'` at startup | An older image is running against a database a newer one has already migrated | Run the newer image; migrations only move forward | +| The plugin's tools are missing in Claude Code | The plugin isn't installed, or Claude Code hasn't reloaded it | `/plugin` to install or update it, then `/reload-plugins` | +| Search finds only exact words | The embedding model hasn't downloaded yet | Give the app internet access once, or wait for the first download to finish | + +## Development + +```bash +cp .env.example .env # then set SECRET_KEY +docker compose up --build +``` + +[Development](docs/development.md) covers checks, migrations, the plugin and CI. [Architecture](docs/architecture.md) describes how it is built, and the [API reference](docs/api-reference.md) lists every REST endpoint. + +## Licence + +Fabled Grimoire is privately maintained. All rights reserved. diff --git a/frontend/src/components/AppLogo.vue b/frontend/src/components/AppLogo.vue index 30bff082..0a64d744 100644 --- a/frontend/src/components/AppLogo.vue +++ b/frontend/src/components/AppLogo.vue @@ -3,6 +3,8 @@ defineProps<{ size?: number }>(); - - -- 2.54.0 From 81fe851509c8aa367459972108d313814f3934dc Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 22 Oct 2026 15:45:11 -0400 Subject: [PATCH 2/5] licence: Fabled Grimoire is AGPL-3.0-only LICENSE carries the GNU Affero General Public License v3.0 text, the same file the other Fabled projects ship. pyproject.toml, the frontend's package.json and lockfile, and the plugin manifest declare it as the SPDX expression AGPL-3.0-only, and the README says what it asks of anyone who runs a modified version over a network. Reading `license` as an SPDX expression needs setuptools 77, so the build floor rises to it. The project description now matches the README's tagline. Co-Authored-By: Claude Opus 5.5 --- LICENSE | 661 ++++++++++++++++++++++++++++++ README.md | 2 +- frontend/package-lock.json | 1 + frontend/package.json | 1 + plugin/.claude-plugin/plugin.json | 3 +- pyproject.toml | 6 +- 6 files changed, 670 insertions(+), 4 deletions(-) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..be3f7b28 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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 +. diff --git a/README.md b/README.md index 38d45cfe..8f2ad796 100644 --- a/README.md +++ b/README.md @@ -108,4 +108,4 @@ docker compose up --build ## Licence -Fabled Grimoire is privately maintained. All rights reserved. +Fabled Grimoire is free software under the [GNU Affero General Public License v3.0 only](LICENSE) (`AGPL-3.0-only`). If you run a modified version for other people over a network, the licence requires you to offer them its source. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 6e270dc0..785a0973 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -7,6 +7,7 @@ "": { "name": "grimoire-frontend", "version": "0.1.0", + "license": "AGPL-3.0-only", "dependencies": { "@fullcalendar/core": "^6.1.20", "@fullcalendar/daygrid": "^6.1.20", diff --git a/frontend/package.json b/frontend/package.json index 74027f36..2954ea20 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,7 @@ { "name": "grimoire-frontend", "private": true, + "license": "AGPL-3.0-only", "version": "0.1.0", "type": "module", "scripts": { diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 31e6b243..030f3036 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,10 +1,11 @@ { "name": "grimoire", "description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", - "version": "2026.10.22.1907", + "version": "2026.10.22.1945", "author": { "name": "Bryan Van Deusen" }, + "license": "AGPL-3.0-only", "mcpServers": { "grimoire": { "type": "http", diff --git a/pyproject.toml b/pyproject.toml index e5409765..bede1e36 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,11 +1,13 @@ [build-system] -requires = ["setuptools>=68.0", "setuptools-scm>=8.0"] +# 77 is the first setuptools that reads `license` as an SPDX expression. +requires = ["setuptools>=77.0", "setuptools-scm>=8.0"] build-backend = "setuptools.build_meta" [project] name = "grimoire" version = "0.1.0" -description = "Self-hosted note-taking, project-management, and calendar app exposed to Claude via MCP" +description = "A self-hosted system of record for the work you do with Claude Code" +license = "AGPL-3.0-only" requires-python = ">=3.14" dependencies = [ "quart>=0.19", -- 2.54.0 From 787685ac631ccc667c416e607391d770bd5d2def Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 22 Oct 2026 16:13:43 -0400 Subject: [PATCH 3/5] fix(6244): the instance keeps its own SECRET_KEY in /data, and docker-compose.yml is the compose users deploy from With no SECRET_KEY set, Grimoire fell back to a fixed placeholder. The quickstart compose substituted change-me-in-production, so the README's own update step (pull, up -d) recreated the container on that placeholder, and every credential sealed under the key the user started with stopped opening. - config: with neither SECRET_KEY nor SECRET_KEY_FILE, the first start writes a random key to DATA_DIR/secret_key (mode 0600, published with a hard link so concurrent starts agree), and later starts read it back. An explicit key wins and leaves the file alone. A missing SECRET_KEY_FILE or an empty key file stops the start instead of switching keys. With no data directory (a run outside the container) the process gets a temporary key and says so. - app: warns on a public placeholder key, on a temporary key, and when /data is not a mounted volume. - Dockerfile creates /data. - docker-compose.yml is now the deploy compose (published image, both volumes, nothing to set). The build-from-source compose is docker-compose.dev.yml, and docker-compose.quickstart.yml is gone. The Swarm stack file gains the /data volume and keeps its explicit key, because a Swarm can move the app away from a node-local volume. - README: a Deploy section with the compose inline, SECRET_KEY optional, "keep both volumes", and updates that keep the key. A test holds the README's copy equal to the file. - Installs that ran on the change-me-in-production placeholder get a key of their own on the new compose; Settings then asks once for saved forge tokens and the backup secret. Co-Authored-By: Claude Opus 5.5 --- .env.example | 4 +- Dockerfile | 4 + Makefile | 10 +-- README.md | 78 ++++++++++++----- ...e.quickstart.yml => docker-compose.dev.yml | 27 +++--- docker-compose.prod.yml | 6 ++ docker-compose.yml | 31 ++++--- docs/architecture.md | 2 +- docs/backups.md | 3 +- docs/configuration.md | 23 ++--- docs/development.md | 8 +- src/grimoire/app.py | 22 ++++- src/grimoire/config.py | 79 +++++++++++++++++- tests/test_config_secret_key.py | 83 +++++++++++++++++++ tests/test_readme_compose.py | 24 ++++++ 15 files changed, 329 insertions(+), 75 deletions(-) rename docker-compose.quickstart.yml => docker-compose.dev.yml (59%) create mode 100644 tests/test_config_secret_key.py create mode 100644 tests/test_readme_compose.py diff --git a/.env.example b/.env.example index 897c1f55..aa019006 100644 --- a/.env.example +++ b/.env.example @@ -4,4 +4,6 @@ POSTGRES_USER=fabled POSTGRES_PASSWORD=fabled POSTGRES_DB=grimoire # PGDATA_VOLUME=grimoire_pgdata -SECRET_KEY=dev-secret-change-me +# Grimoire keeps its own SECRET_KEY in the /data volume. Set one here only to +# use a key you manage yourself; it then wins over the kept one. +# SECRET_KEY= diff --git a/Dockerfile b/Dockerfile index d53ffedd..25777099 100644 --- a/Dockerfile +++ b/Dockerfile @@ -56,5 +56,9 @@ ENV APP_BUILD_KEY=$BUILD_KEY ENV APP_CHANNEL=$BUILD_CHANNEL ENV APP_COMMIT=$BUILD_COMMIT +# The instance's own SECRET_KEY, the model cache and diagnostics live here. +# Mount a volume on it so they outlive the container. +RUN mkdir -p /data + EXPOSE 5000 CMD ["sh", "-c", "alembic upgrade head && hypercorn 'grimoire.app:create_app()' --bind 0.0.0.0:5000 --keep-alive 600"] diff --git a/Makefile b/Makefile index cb7476ef..cdc7f970 100644 --- a/Makefile +++ b/Makefile @@ -3,22 +3,22 @@ # --- Docker --- build: - docker compose build + docker compose -f docker-compose.dev.yml build up: - docker compose up -d + docker compose -f docker-compose.dev.yml up -d down: - docker compose down + docker compose -f docker-compose.dev.yml down logs: - docker compose logs -f + docker compose -f docker-compose.dev.yml logs -f health: curl -s http://localhost:5000/api/health migrate: - docker compose exec app alembic upgrade head + docker compose -f docker-compose.dev.yml exec app alembic upgrade head # --- Local dev (requires: uv sync --extra dev and cd frontend && npm ci) --- diff --git a/README.md b/README.md index 8f2ad796..388d47d8 100644 --- a/README.md +++ b/README.md @@ -8,17 +8,57 @@ Claude records what it learned, decided and built in Grimoire, and that record reaches the next session, so a solution is recalled instead of reinvented. Notes, tasks, plans, rules, lessons and reusable code live in one place. Claude reaches them through a built-in MCP endpoint and the bundled Claude Code plugin, and people read and edit the same records in the web UI. There is no language model inside Grimoire: Claude is the only assistant. -## Quick start +## Deploy -You need Docker with Compose. Download [`docker-compose.quickstart.yml`](docker-compose.quickstart.yml), then: +You need Docker with Compose. Save this as `docker-compose.yml` (it is the [`docker-compose.yml`](docker-compose.yml) in this repository), then run `docker compose up -d` beside it: -```bash -SECRET_KEY=$(python3 -c 'import secrets; print(secrets.token_hex(32))') \ - docker compose -f docker-compose.quickstart.yml up -d +```yaml +# Fabled Grimoire: the app and its database. +# docker compose up -d +# Then open http://localhost:5000. The first account registered becomes admin. +# +# Keep both volumes. app_data holds the instance's own SECRET_KEY, which seals +# saved credentials; pgdata holds everything else. + +services: + app: + image: git.fabledsword.com/bvandeusen/fabledgrimoire:latest + ports: + - "5000:5000" + environment: + DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${POSTGRES_PASSWORD:-grimoire}@db:5432/${POSTGRES_DB:-grimoire}" + LOG_LEVEL: "${LOG_LEVEL:-INFO}" + # Behind an HTTPS reverse proxy: + # BASE_URL: "https://grimoire.example.com" + # SECURE_COOKIES: "true" + # TRUST_PROXY_HEADERS: "true" + volumes: + - app_data:/data + depends_on: + - db + restart: unless-stopped + + db: + # Postgres 17 with the vector extension Grimoire needs. + image: pgvector/pgvector:pg17 + stop_grace_period: 120s + volumes: + - pgdata:/var/lib/postgresql/data + environment: + POSTGRES_USER: ${POSTGRES_USER:-grimoire} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-grimoire} + POSTGRES_DB: ${POSTGRES_DB:-grimoire} + restart: unless-stopped + +volumes: + app_data: + pgdata: ``` Open `http://localhost:5000`. The first account you register becomes the admin. +Nothing has to be set first. On its first start Grimoire makes its own `SECRET_KEY` and keeps it in the `app_data` volume, so restarts, reboots and updates all use the same key. + To connect Claude, create an API key under **Settings → MCP Access**, then in Claude Code: ``` @@ -30,34 +70,34 @@ The plugin asks for your Grimoire URL and the API key. Settings → MCP Access s ## Configuration -Set these in the environment or a `.env` file beside the compose file: +Everything is optional. Set these in the environment or in a `.env` file beside the compose file: -| Variable | Needed | What it does | -|----------|--------|--------------| -| `SECRET_KEY` | Yes | Signs sessions and seals stored credentials. Set it once and keep it | +| Variable | When | What it does | +|----------|------|--------------| | `BASE_URL` | Behind a proxy | The public URL, used in email links and SSO redirects | | `SECURE_COOKIES` | Over HTTPS | `true` when Grimoire is served over HTTPS | | `TRUST_PROXY_HEADERS` | Behind a proxy | `true` to read the client address from the proxy's headers | -| `POSTGRES_PASSWORD` | Recommended | The database password (defaults to `grimoire`) | +| `POSTGRES_PASSWORD` | Before the first start | The database password (defaults to `grimoire`; the database is reachable only inside the compose network). Postgres takes it once, when the volume is created | +| `SECRET_KEY` | Rarely | A key you manage yourself, instead of the one Grimoire keeps. It wins over the kept key; remove it to go back | Everything else (registration, email, SSO, git forge connections, retrieval tuning, backups) is in **Settings**, or listed in [Configuration](docs/configuration.md). ## Setup pitfalls -- **Keep your `SECRET_KEY`.** Forge tokens and the backup bucket's secret are sealed under it. If it changes, Settings asks you to enter those credentials again. -- **The embedding model downloads on first use**, into the `/data` volume. Without internet access, semantic search falls back to keyword search until the model is in place. +- **Keep both volumes.** `pgdata` holds everything Grimoire stores. `app_data` holds the instance's key, and forge tokens and the backup bucket's secret are sealed under it. If the key is lost, Settings asks you to enter those credentials again; nothing else is lost. +- **The embedding model downloads on first use**, into the `app_data` volume. Without internet access, semantic search falls back to keyword search until the model is in place. - **Behind a reverse proxy, turn off response buffering** for `/mcp`, because MCP responses stream. [Configuration](docs/configuration.md#behind-a-reverse-proxy) has an Nginx example. ## Updating and backups ```bash -docker compose -f docker-compose.quickstart.yml pull -docker compose -f docker-compose.quickstart.yml up -d +docker compose pull +docker compose up -d ``` -Database migrations run when the app starts. Claude Code updates the plugin from its marketplace; run `/reload-plugins` after an update. +Database migrations run when the app starts, and the key stays in its volume. Claude Code updates the plugin from its marketplace; run `/reload-plugins` after an update. -Everything Grimoire stores is in the database. **Settings → Data → Scheduled backups** writes a daily backup to a folder or an S3-compatible bucket, and `python -m grimoire.restore` brings a fresh instance back from one. See [Backups](docs/backups.md). +**Settings → Data → Scheduled backups** writes a daily backup of the database to a folder or an S3-compatible bucket, and `python -m grimoire.restore` brings a fresh instance back from one. See [Backups](docs/backups.md). ## Features @@ -92,7 +132,8 @@ The full list is in [Features](docs/features.md). | What you see | Why | Fix | |--------------|-----|-----| -| `SECRET_KEY is set to the insecure default` at startup | `SECURE_COOKIES=true` while `SECRET_KEY` is still the built-in default | Set `SECRET_KEY` | +| `SECRET_KEY is set to the public placeholder` at startup | `SECURE_COOKIES=true` while `SECRET_KEY` is `dev-secret-change-me` | Remove `SECRET_KEY`, or set a real one | +| Settings asks for forge tokens or the backup secret again | The instance's key changed: the `app_data` volume was replaced, or `SECRET_KEY` was set or removed | Enter them again, or restore the previous key | | `Can't locate revision identified by '…'` at startup | An older image is running against a database a newer one has already migrated | Run the newer image; migrations only move forward | | The plugin's tools are missing in Claude Code | The plugin isn't installed, or Claude Code hasn't reloaded it | `/plugin` to install or update it, then `/reload-plugins` | | Search finds only exact words | The embedding model hasn't downloaded yet | Give the app internet access once, or wait for the first download to finish | @@ -100,8 +141,7 @@ The full list is in [Features](docs/features.md). ## Development ```bash -cp .env.example .env # then set SECRET_KEY -docker compose up --build +docker compose -f docker-compose.dev.yml up --build ``` [Development](docs/development.md) covers checks, migrations, the plugin and CI. [Architecture](docs/architecture.md) describes how it is built, and the [API reference](docs/api-reference.md) lists every REST endpoint. diff --git a/docker-compose.quickstart.yml b/docker-compose.dev.yml similarity index 59% rename from docker-compose.quickstart.yml rename to docker-compose.dev.yml index 90af1f63..e7fc02e4 100644 --- a/docker-compose.quickstart.yml +++ b/docker-compose.dev.yml @@ -1,36 +1,35 @@ -# Fabled Grimoire from the pre-built image: -# docker compose -f docker-compose.quickstart.yml up -d -# Then open http://localhost:5000 (the first account registered becomes admin) -# and connect Claude from Settings → MCP Access. +# Grimoire built from this checkout, for development: +# docker compose -f docker-compose.dev.yml up --build services: app: - image: git.fabledsword.com/bvandeusen/fabledgrimoire:latest + build: . ports: - "5000:5000" - environment: - DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${POSTGRES_PASSWORD:-grimoire}@db:5432/${POSTGRES_DB:-grimoire}" - # Set SECRET_KEY in the environment or a .env file beside this one. - SECRET_KEY: "${SECRET_KEY:-change-me-in-production}" - LOG_LEVEL: "${LOG_LEVEL:-INFO}" - volumes: - - app_data:/data depends_on: - db restart: unless-stopped + volumes: + - app_data:/data + # Or a bind mount, for direct host access to the app's data: + # - ./data:/data + environment: + DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${POSTGRES_PASSWORD:-grimoire}@db:5432/${POSTGRES_DB:-grimoire}" + # Optional: a SearXNG instance to list as the web-search backend in Integrations. + # SEARXNG_URL: "http://searxng:8080" db: # Postgres 17 with the vector extension Grimoire needs. image: pgvector/pgvector:pg17 stop_grace_period: 120s + restart: unless-stopped volumes: - pgdata:/var/lib/postgresql/data environment: POSTGRES_USER: ${POSTGRES_USER:-grimoire} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-grimoire} POSTGRES_DB: ${POSTGRES_DB:-grimoire} - restart: unless-stopped volumes: - app_data: pgdata: + app_data: diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 1d19d84c..a575577b 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -3,10 +3,15 @@ services: image: git.fabledsword.com/bvandeusen/fabledgrimoire:latest environment: DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${DB_PASSWORD}@db:5432/${POSTGRES_DB:-grimoire}" + # A Swarm can start the app on another node, away from the key kept in + # a node-local /data volume, so a stack sets its key itself (or mounts + # a Docker secret and sets SECRET_KEY_FILE to its path). SECRET_KEY: "${SECRET_KEY}" LOG_LEVEL: "${LOG_LEVEL:-INFO}" TRUST_PROXY_HEADERS: "true" SECURE_COOKIES: "true" + volumes: + - app_data:/data networks: - backend @@ -26,6 +31,7 @@ services: volumes: pgdata: name: ${PGDATA_VOLUME:-grimoire_pgdata} + app_data: networks: backend: diff --git a/docker-compose.yml b/docker-compose.yml index 2a420706..0a231d78 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,33 +1,40 @@ +# Fabled Grimoire: the app and its database. +# docker compose up -d +# Then open http://localhost:5000. The first account registered becomes admin. +# +# Keep both volumes. app_data holds the instance's own SECRET_KEY, which seals +# saved credentials; pgdata holds everything else. + services: app: - build: . + image: git.fabledsword.com/bvandeusen/fabledgrimoire:latest ports: - "5000:5000" + environment: + DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${POSTGRES_PASSWORD:-grimoire}@db:5432/${POSTGRES_DB:-grimoire}" + LOG_LEVEL: "${LOG_LEVEL:-INFO}" + # Behind an HTTPS reverse proxy: + # BASE_URL: "https://grimoire.example.com" + # SECURE_COOKIES: "true" + # TRUST_PROXY_HEADERS: "true" + volumes: + - app_data:/data depends_on: - db restart: unless-stopped - volumes: - - app_data:/data - # Or a bind mount, for direct host access to the app's data: - # - ./data:/data - environment: - DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${POSTGRES_PASSWORD:-grimoire}@db:5432/${POSTGRES_DB:-grimoire}" - SECRET_KEY: "${SECRET_KEY:-dev-secret-change-me}" - # Optional: a SearXNG instance to list as the web-search backend in Integrations. - # SEARXNG_URL: "http://searxng:8080" db: # Postgres 17 with the vector extension Grimoire needs. image: pgvector/pgvector:pg17 stop_grace_period: 120s - restart: unless-stopped volumes: - pgdata:/var/lib/postgresql/data environment: POSTGRES_USER: ${POSTGRES_USER:-grimoire} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-grimoire} POSTGRES_DB: ${POSTGRES_DB:-grimoire} + restart: unless-stopped volumes: - pgdata: app_data: + pgdata: diff --git a/docs/architecture.md b/docs/architecture.md index 735821cb..2ecc9e19 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -74,7 +74,7 @@ Every database wait on startup has a deadline. Migrations wait for the database - **OIDC** single sign-on with PKCE, optionally replacing local logins ([SSO / OAuth](sso-oauth.md)). - **Rate limits** on register, login and forgot-password, per client IP (`TRUST_PROXY_HEADERS` reads the IP from the proxy's headers). -Credentials Grimoire stores for outside services (forge tokens, the backup destination's S3 secret) are sealed under a key derived from `SECRET_KEY`. +Credentials Grimoire stores for outside services (forge tokens, the backup destination's S3 secret) are sealed under a key derived from `SECRET_KEY`, which the instance makes on first start and keeps in `/data/secret_key` unless one is set. ## Repository layout diff --git a/docs/backups.md b/docs/backups.md index df93be32..e0c630cb 100644 --- a/docs/backups.md +++ b/docs/backups.md @@ -31,7 +31,8 @@ differently. It does **not** hold: - **Credentials:** API keys and forge connections. After a restore, issue new API keys and add forge connections again. (Forge tokens are also sealed under `SECRET_KEY` in the database itself, so a copy of the database doesn't carry - them in readable form either.) + them in readable form either. The key lives in `/data/secret_key`, outside + the database.) - **Logs and notifications.** - **The backup destination's own S3 secret.** diff --git a/docs/configuration.md b/docs/configuration.md index ac7e37ad..5c437bae 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -11,7 +11,8 @@ Any variable marked *secret* can also be read from a file: set `_FILE` to | Variable | Default | Description | |----------|---------|-------------| | `DATABASE_URL` *(secret)* | `postgresql+asyncpg://grimoire:grimoire@localhost:5432/grimoire` | PostgreSQL connection string, using the `asyncpg` driver | -| `SECRET_KEY` *(secret)* | `dev-secret-change-me` | Signs sessions and seals stored credentials. Set it before first use and keep it (see below) | +| `SECRET_KEY` *(secret)* | kept in `DATA_DIR` | Signs sessions and seals stored credentials. Unset, the instance makes its own on first start and keeps it in `DATA_DIR/secret_key`. Set it only to manage the key yourself; it wins over the kept one (see below) | +| `DATA_DIR` | `/data` | Where the instance keeps its own `SECRET_KEY`. Mount a volume here | | `BASE_URL` | `http://localhost:5000` | Public URL, used in email links and OIDC redirects | | `SECURE_COOKIES` | `false` | `true` when Grimoire is served over HTTPS | | `TRUST_PROXY_HEADERS` | `false` | `true` behind a reverse proxy, to read the client IP from `X-Forwarded-For` / `X-Real-IP` | @@ -56,27 +57,27 @@ Admins can set SMTP in **Settings**; these are the defaults until they do. ## Running it -### Quick start +### Docker Compose -[`docker-compose.quickstart.yml`](../docker-compose.quickstart.yml) runs the published image with its own database: +[`docker-compose.yml`](../docker-compose.yml) runs the published image with its own database, and needs nothing set: ```bash -SECRET_KEY=$(python3 -c 'import secrets; print(secrets.token_hex(32))') \ - docker compose -f docker-compose.quickstart.yml up -d +docker compose up -d ``` Open `http://localhost:5000`. The first account registered becomes the admin; after that, registration stays closed until an admin opens it in Settings or sends an invite. +Update with `docker compose pull && docker compose up -d`. The key and the data stay in their volumes. + ### From source ```bash -cp .env.example .env # then set SECRET_KEY -docker compose up --build +docker compose -f docker-compose.dev.yml up --build ``` ### Docker Swarm -[`docker-compose.prod.yml`](../docker-compose.prod.yml) is a stack file: the app and database on a private overlay network, with `SECURE_COOKIES` and `TRUST_PROXY_HEADERS` on. Provide `DB_PASSWORD` and `SECRET_KEY` in the environment: +[`docker-compose.prod.yml`](../docker-compose.prod.yml) is a stack file: the app and database on a private overlay network, with `SECURE_COOKIES` and `TRUST_PROXY_HEADERS` on. A Swarm can move the app to another node, away from a node-local `/data` volume, so the stack sets its own key: provide `DB_PASSWORD` and `SECRET_KEY` in the environment (or mount a Docker secret and set `SECRET_KEY_FILE`): ```bash DB_PASSWORD=... SECRET_KEY=... docker stack deploy -c docker-compose.prod.yml grimoire @@ -89,9 +90,9 @@ The shipped files leave out healthchecks and restart policies on purpose. The ap ### Volumes - **Database** (`pgdata`): everything Grimoire stores. -- **App data** (`/data`): the embedding model cache and diagnostics. Losing it costs a re-download, nothing else. +- **App data** (`/data`): the instance's own `SECRET_KEY`, the embedding model cache and diagnostics. Losing it costs the key: Settings then asks for saved forge tokens and the backup secret again, and the model downloads again. -Back up the database with **Settings → Data → Scheduled backups** ([Backups](backups.md)). +Back up the database with **Settings → Data → Scheduled backups** ([Backups](backups.md)). A database backup doesn't carry the key; to move sealed credentials to a new instance, copy `/data/secret_key` with it. ## Behind a reverse proxy @@ -115,7 +116,7 @@ With `TRUST_PROXY_HEADERS=true`, make sure the proxy replaces any `X-Forwarded-F ## Security checklist -- **Set a strong `SECRET_KEY`, and keep it.** Forge tokens and the backup destination's S3 secret are sealed under a key derived from it, so a copy of the database alone can't read them. If the key changes (say, a restore onto an instance with a different key), Settings marks those credentials and asks for them again; nothing else breaks. The app logs a warning at startup while the default key is in use, and refuses to start with it when `SECURE_COOKIES=true`. +- **Keep the key.** Forge tokens and the backup destination's S3 secret are sealed under a key derived from `SECRET_KEY`, so a copy of the database alone can't read them. Unset, the instance makes a random key and keeps it in `/data/secret_key`, readable by its owner only; keep that volume. If the key changes (say, a restore onto an instance with a different key), Settings marks those credentials and asks for them again; nothing else breaks. The app warns at startup when `SECRET_KEY` is a public placeholder or `/data` is not a mounted volume, and refuses to start with `dev-secret-change-me` when `SECURE_COOKIES=true`. - **`SECURE_COOKIES=true`** whenever Grimoire is served over HTTPS. - **Registration** is open only for the first account. Invite people, or open it briefly from Settings. - **Signing everyone else out**: changing a password ends that user's other sessions; Settings → Account has a button for it too. diff --git a/docs/development.md b/docs/development.md index 096e4ebf..d0ec56a1 100644 --- a/docs/development.md +++ b/docs/development.md @@ -3,9 +3,9 @@ ## Running it ```bash -docker compose up --build # app + PostgreSQL at http://localhost:5000 -docker compose up --build app # rebuild after a change -docker compose down -v # stop and wipe the database +docker compose -f docker-compose.dev.yml up --build # app + PostgreSQL at http://localhost:5000 +docker compose -f docker-compose.dev.yml up --build app # rebuild after a change +docker compose -f docker-compose.dev.yml down -v # stop and wipe the database ``` The image builds the frontend, so a frontend change needs a rebuild too. For quicker frontend work, run Vite against the running app; it proxies `/api` to port 5000: @@ -32,7 +32,7 @@ Unit tests run without a database. Tests marked `integration` need a real Postgr The container runs `alembic upgrade head` on every start, after waiting for the database to accept connections. ```bash -docker compose exec app alembic revision -m "short_description" +docker compose -f docker-compose.dev.yml exec app alembic revision -m "short_description" ``` - Number revisions sequentially (`0123_...`). Revision ids must fit in 32 characters, the width of `alembic_version.version_num`. diff --git a/src/grimoire/app.py b/src/grimoire/app.py index 21e36252..6d278ede 100644 --- a/src/grimoire/app.py +++ b/src/grimoire/app.py @@ -1,11 +1,12 @@ import logging +import os import time import traceback as tb_module from pathlib import Path from quart import Quart, g, jsonify, make_response, request, send_from_directory -from grimoire.config import Config +from grimoire.config import PLACEHOLDER_SECRET_KEYS, SECRET_KEY_FILENAME, Config from grimoire.routes.admin import admin_bp from grimoire.routes.api import api from grimoire.routes.auth import auth_bp @@ -62,10 +63,23 @@ def create_app() -> Quart: app.config["SESSION_COOKIE_SAMESITE"] = "Lax" app.config["SESSION_COOKIE_SECURE"] = Config.SECURE_COOKIES - if Config.SECRET_KEY == "dev-secret-change-me": + if Config.SECRET_KEY in PLACEHOLDER_SECRET_KEYS: logger.warning( - "SECRET_KEY is set to the default value — session cookies are insecure. " - "Set SECRET_KEY or SECRET_KEY_FILE for production use." + "SECRET_KEY is set to a public placeholder, so session cookies are insecure. " + "Remove it to let the instance keep its own key in %s, or set a real one.", + Config.DATA_DIR, + ) + if Config.SECRET_KEY_SOURCE == "ephemeral": + logger.warning( + "No SECRET_KEY is set and %s does not exist, so this process is using a " + "temporary key. Sessions and saved credentials will not survive a restart.", + Config.DATA_DIR, + ) + elif Config.SECRET_KEY_SOURCE == "data" and not os.path.ismount(Config.DATA_DIR): + logger.warning( + "%s is not a mounted volume. The instance's key (%s) and the model cache " + "are lost when the container is recreated; mount a volume there.", + Config.DATA_DIR, SECRET_KEY_FILENAME, ) if not Config.TRUST_PROXY_HEADERS: diff --git a/src/grimoire/config.py b/src/grimoire/config.py index 111351c4..d0a11a62 100644 --- a/src/grimoire/config.py +++ b/src/grimoire/config.py @@ -1,4 +1,13 @@ import os +import secrets +from pathlib import Path + +# The file in the data directory that holds the instance's own SECRET_KEY. +SECRET_KEY_FILENAME = "secret_key" + +# Placeholder keys that sample files and older compose files have shipped. A +# key anyone can read in this repository signs nothing safely. +PLACEHOLDER_SECRET_KEYS = frozenset({"dev-secret-change-me", "change-me-in-production"}) def _read_secret(env_var: str, secret_file_var: str, default: str) -> str: @@ -16,13 +25,76 @@ def _read_secret(env_var: str, secret_file_var: str, default: str) -> str: return default +def load_or_create_secret_key(data_dir: Path) -> str | None: + """The instance's own SECRET_KEY, kept in `data_dir` and made on first use. + + The first call writes a random key to `/secret_key`, readable by + its owner only; every later call, from this process or another, reads that + same key back. The file is published with a hard link, so two processes + starting together agree on one key and a crash never leaves an empty file. + Answers None when `data_dir` doesn't exist, which is a run outside the + container. An empty key file raises rather than being replaced, because a + new key would orphan everything sealed under the old one. + """ + if not data_dir.is_dir(): + return None + path = data_dir / SECRET_KEY_FILENAME + if not path.exists(): + tmp = data_dir / f".{SECRET_KEY_FILENAME}.{os.getpid()}" + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + try: + with os.fdopen(fd, "w") as f: + f.write(secrets.token_hex(32) + "\n") + f.flush() + os.fsync(f.fileno()) + try: + os.link(tmp, path) + except FileExistsError: + pass + finally: + tmp.unlink(missing_ok=True) + key = path.read_text().strip() + if not key: + raise RuntimeError( + f"{path} is empty. Restore it from a copy, or delete it to start " + "with a new key (saved forge tokens and the backup secret are then " + "entered again)." + ) + return key + + +def _secret_key() -> tuple[str, str]: + """SECRET_KEY and where it came from: "env", "data" or "ephemeral". + + An explicit key (SECRET_KEY or SECRET_KEY_FILE) wins and leaves the data + directory's key file alone, so unsetting it returns to that key. With no + explicit key the instance keeps its own in DATA_DIR. With neither, the + process gets a random key of its own that dies with it. + """ + explicit = _read_secret("SECRET_KEY", "SECRET_KEY_FILE", "") + if explicit: + return explicit, "env" + if os.environ.get("SECRET_KEY_FILE"): + # Falling through to another key would orphan what the named one sealed. + raise RuntimeError( + f"SECRET_KEY_FILE={os.environ['SECRET_KEY_FILE']} is missing or empty." + ) + kept = load_or_create_secret_key(Path(os.environ.get("DATA_DIR", "/data"))) + if kept: + return kept, "data" + return secrets.token_hex(32), "ephemeral" + + class Config: DATABASE_URL: str = _read_secret( "DATABASE_URL", "DATABASE_URL_FILE", "postgresql+asyncpg://grimoire:grimoire@localhost:5432/grimoire", ) - SECRET_KEY: str = _read_secret("SECRET_KEY", "SECRET_KEY_FILE", "dev-secret-change-me") + # Where the instance keeps its own SECRET_KEY. /data is a volume in every + # shipped compose file, beside the model cache and diagnostics. + DATA_DIR: str = os.environ.get("DATA_DIR", "/data") + SECRET_KEY, SECRET_KEY_SOURCE = _secret_key() SECURE_COOKIES: bool = os.environ.get("SECURE_COOKIES", "").lower() in ("1", "true", "yes") LOG_LEVEL: str = os.environ.get("LOG_LEVEL", "INFO") LOG_RETENTION_DAYS: int = int(os.environ.get("LOG_RETENTION_DAYS", "90")) @@ -93,8 +165,9 @@ class Config: errors.append(f"BASE_URL='{cls.BASE_URL}' must start with http:// or https:// when OIDC is enabled") if cls.SECRET_KEY == "dev-secret-change-me" and cls.SECURE_COOKIES: errors.append( - "SECRET_KEY is set to the insecure default but SECURE_COOKIES=true indicates " - "a production deployment. Set SECRET_KEY or SECRET_KEY_FILE before starting." + "SECRET_KEY is set to the public placeholder 'dev-secret-change-me' but " + "SECURE_COOKIES=true indicates a production deployment. Remove SECRET_KEY " + "to let the instance keep its own key in DATA_DIR, or set a real one." ) if errors: raise ValueError("Configuration errors:\n" + "\n".join(f" - {e}" for e in errors)) diff --git a/tests/test_config_secret_key.py b/tests/test_config_secret_key.py new file mode 100644 index 00000000..f6c9eecf --- /dev/null +++ b/tests/test_config_secret_key.py @@ -0,0 +1,83 @@ +"""The instance keeps its own SECRET_KEY in the data directory. + +A deployment that never sets SECRET_KEY must get the same key on every start, +or everything sealed under the first one (forge tokens, the backup secret) +stops opening after the first container recreate. +""" +import stat +from unittest.mock import patch + +import pytest + +from grimoire import config +from grimoire.config import SECRET_KEY_FILENAME, load_or_create_secret_key +from grimoire.services import secrets + + +def test_the_first_start_writes_a_key_only_its_owner_can_read(tmp_path): + key = load_or_create_secret_key(tmp_path) + + path = tmp_path / SECRET_KEY_FILENAME + assert key and len(key) == 64 + assert path.read_text().strip() == key + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + assert [p.name for p in tmp_path.iterdir()] == [SECRET_KEY_FILENAME] + + +def test_every_later_start_reads_the_same_key_and_what_it_sealed_still_opens(tmp_path): + first = load_or_create_secret_key(tmp_path) + with patch.object(secrets.Config, "SECRET_KEY", first): + sealed = secrets.seal("forge-token") + + second = load_or_create_secret_key(tmp_path) + + assert second == first + with patch.object(secrets.Config, "SECRET_KEY", second): + assert secrets.unseal(sealed) == "forge-token" + + +def test_no_data_directory_means_no_kept_key(tmp_path): + assert load_or_create_secret_key(tmp_path / "absent") is None + + +def test_an_empty_key_file_is_refused_rather_than_replaced(tmp_path): + (tmp_path / SECRET_KEY_FILENAME).write_text("\n") + + with pytest.raises(RuntimeError, match="is empty"): + load_or_create_secret_key(tmp_path) + assert (tmp_path / SECRET_KEY_FILENAME).read_text() == "\n" + + +def test_an_explicit_key_wins_and_leaves_the_kept_one_alone(tmp_path, monkeypatch): + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + monkeypatch.delenv("SECRET_KEY_FILE", raising=False) + monkeypatch.delenv("SECRET_KEY", raising=False) + kept, source = config._secret_key() + assert source == "data" + + monkeypatch.setenv("SECRET_KEY", "an-operator-key") + assert config._secret_key() == ("an-operator-key", "env") + + monkeypatch.delenv("SECRET_KEY") + assert config._secret_key() == (kept, "data") + + +def test_a_secret_key_file_that_is_missing_stops_the_start(tmp_path, monkeypatch): + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + monkeypatch.delenv("SECRET_KEY", raising=False) + monkeypatch.setenv("SECRET_KEY_FILE", str(tmp_path / "no-such-secret")) + + with pytest.raises(RuntimeError, match="SECRET_KEY_FILE"): + config._secret_key() + assert not (tmp_path / SECRET_KEY_FILENAME).exists() + + +def test_with_nowhere_to_keep_a_key_the_process_gets_a_temporary_one(tmp_path, monkeypatch): + monkeypatch.setenv("DATA_DIR", str(tmp_path / "absent")) + monkeypatch.delenv("SECRET_KEY", raising=False) + monkeypatch.delenv("SECRET_KEY_FILE", raising=False) + + key, source = config._secret_key() + + assert source == "ephemeral" + assert key not in config.PLACEHOLDER_SECRET_KEYS and len(key) == 64 diff --git a/tests/test_readme_compose.py b/tests/test_readme_compose.py new file mode 100644 index 00000000..c2b7f3c7 --- /dev/null +++ b/tests/test_readme_compose.py @@ -0,0 +1,24 @@ +"""The compose file the README shows is the one users deploy from. + +The README carries docker-compose.yml inline, so a newcomer can copy it from +the page. Both copies have to say the same thing. +""" +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def test_the_readme_shows_the_shipped_compose_file_verbatim(): + compose = (ROOT / "docker-compose.yml").read_text() + readme = (ROOT / "README.md").read_text() + + assert f"```yaml\n{compose}```" in readme + + +def test_the_shipped_compose_needs_no_key_and_keeps_its_data(): + compose = (ROOT / "docker-compose.yml").read_text() + + settings = [line for line in compose.splitlines() if not line.lstrip().startswith("#")] + assert not [line for line in settings if "SECRET_KEY" in line] + assert "app_data:/data" in compose + assert "pgdata:/var/lib/postgresql/data" in compose -- 2.54.0 From e89e6a24de2400c9e1159f7fa20eba8f21ad9968 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 22 Oct 2026 16:18:03 -0400 Subject: [PATCH 4/5] =?UTF-8?q?fix(6245):=20bind=5Frepo(moved=5Ffrom=3D?= =?UTF-8?q?=E2=80=A6)=20moves=20the=20snippet=20locations=20recorded=20in?= =?UTF-8?q?=20the=20old=20repo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A repo renamed on its forge kept every snippet location naming the old repo: the binding and the shape ledger moved, the snippets did not. - snippets.move_location_repo rewrites, on every live snippet of the project, each location whose repo is the old remote in any form (URL, normalized key, "owner/Repo", bare "Repo", compared without case) to the new normalized key. A snippet the caller can only read is listed in read_only and left alone. - Its loop is shared with move_locations through _rewrite_locations, which saves each changed snippet through update_snippet. - bind_repo calls it after the binding moves and reports snippets_moved and snippets_read_only. Co-Authored-By: Claude Opus 5.5 --- src/grimoire/mcp/tools/repos.py | 21 +++++-- src/grimoire/services/snippets.py | 85 ++++++++++++++++++++++------- tests/test_integration_repo_move.py | 32 +++++++++++ 3 files changed, 112 insertions(+), 26 deletions(-) diff --git a/src/grimoire/mcp/tools/repos.py b/src/grimoire/mcp/tools/repos.py index ff6255f0..a63faf39 100644 --- a/src/grimoire/mcp/tools/repos.py +++ b/src/grimoire/mcp/tools/repos.py @@ -11,6 +11,7 @@ from __future__ import annotations from grimoire.mcp._context import current_user_id from grimoire.services import projects as projects_svc from grimoire.services import repo_bindings as repo_bindings_svc +from grimoire.services import snippets as snippets_svc async def bind_repo( @@ -30,9 +31,11 @@ async def bind_repo( pass ref="-" to clear it back to the default branch. A repo renamed on its forge has a new remote, and its ledger is stored - under the old one. Pass the old remote as `moved_from` and the binding and - every shape judgment move to the new name together. Binding the new name - without it starts an empty ledger beside the old one. + under the old one. Pass the old remote as `moved_from` and the binding, + every shape judgment, and every snippet location recorded in the old repo + move to the new name together. Binding the new name without it starts an + empty ledger beside the old one. A snippet shared with you read-only keeps + its location and is listed in `snippets_read_only`; its owner moves it. Args: repo_url: the repo's git remote (e.g. the output of @@ -49,11 +52,14 @@ async def bind_repo( if project is None: raise ValueError(f"project {project_id} not found") ref_arg = None if not ref else ("" if ref.strip() == "-" else ref) - moved = None + moved = snippets = None if moved_from: _, moved = await repo_bindings_svc.move_binding( uid, moved_from, repo_url, project_id, ) + snippets = await snippets_svc.move_location_repo( + uid, project_id, moved_from, repo_url, + ) binding = await repo_bindings_svc.set_binding(uid, repo_url, project_id, ref_arg) follows = binding.ref or "the default branch" out = { @@ -70,7 +76,12 @@ async def bind_repo( old_key = repo_bindings_svc.normalize_repo_key(moved_from) out["moved_from"] = old_key out["shapes_moved"] = moved - out["message"] += f" Moved from `{old_key}` with {moved} shape(s)." + out["snippets_moved"] = snippets["moved"] + out["snippets_read_only"] = snippets["read_only"] + out["message"] += ( + f" Moved from `{old_key}` with {moved} shape(s) and " + f"{len(snippets['moved'])} snippet(s)." + ) return out diff --git a/src/grimoire/services/snippets.py b/src/grimoire/services/snippets.py index 92a4997a..b34a9f59 100644 --- a/src/grimoire/services/snippets.py +++ b/src/grimoire/services/snippets.py @@ -1280,22 +1280,15 @@ def _path_touches(recorded: str, changed: str) -> bool: return changed == recorded or changed.startswith(recorded + "/") -async def move_locations( - user_id: int, project_id: int, from_path: str, to_path: str, -) -> dict: - """Re-path the recorded locations under ``from_path`` (a file or a - directory) to the same place under ``to_path``, on every live snippet of - the project the caller can edit. +async def _rewrite_locations(user_id: int, project_id: int, rewrite) -> dict: + """Apply ``rewrite`` to every recorded location of the project's live + snippets, and save each snippet a rewrite changed. - The twin of the shape ledger's move: a snippet recorded at a path that - moved reads `missing` at its next check, and its canonical stamp no longer - covers the shape that moved. Each snippet is rewritten through - update_snippet, so its body and indexed fields stay one record. A - snippet the caller can only read is left as it is and listed in - ``read_only``. + ``rewrite(location)`` answers the new location, or None to leave it as it + is. Each snippet is saved through update_snippet, so its body and indexed + fields stay one record. A snippet the caller can only read is left as it + is and listed in ``read_only``. """ - old = (from_path or "").strip().strip("/") - new = (to_path or "").strip().strip("/") async with async_session() as session: notes = ( await session.execute( @@ -1310,15 +1303,14 @@ async def move_locations( read_only: list[int] = [] for note in notes: locations = snippet_fields(note).get("locations") or [] - if not any(_path_touches(old, loc.get("path") or "") for loc in locations): + rewritten = [rewrite(loc) for loc in locations] + if all(new is None for new in rewritten): continue - repathed = [ - {**loc, "path": new + loc["path"].strip("/")[len(old):]} - if _path_touches(old, loc.get("path") or "") else loc - for loc in locations - ] try: - await update_snippet(user_id, int(note.id), locations=repathed) + await update_snippet( + user_id, int(note.id), + locations=[new or loc for new, loc in zip(rewritten, locations)], + ) except PermissionError: read_only.append(int(note.id)) continue @@ -1326,6 +1318,57 @@ async def move_locations( return {"moved": moved, "read_only": read_only} +async def move_locations( + user_id: int, project_id: int, from_path: str, to_path: str, +) -> dict: + """Re-path the recorded locations under ``from_path`` (a file or a + directory) to the same place under ``to_path``, on every live snippet of + the project the caller can edit. + + The twin of the shape ledger's move: a snippet recorded at a path that + moved reads `missing` at its next check, and its canonical stamp no longer + covers the shape that moved. Returns {"moved": [ids], "read_only": [ids]}. + """ + old = (from_path or "").strip().strip("/") + new = (to_path or "").strip().strip("/") + + def repath(loc: dict) -> dict | None: + if not _path_touches(old, loc.get("path") or ""): + return None + return {**loc, "path": new + loc["path"].strip("/")[len(old):]} + + return await _rewrite_locations(user_id, project_id, repath) + + +async def move_location_repo( + user_id: int, project_id: int, old_repo: str, new_repo: str, +) -> dict: + """Point the project's snippet locations recorded in ``old_repo`` at + ``new_repo``, for a repo renamed on its forge. + + The twin of the binding move: a location still naming the old repo + resolves to nothing on the forge. Repo names are recorded free-form, so a + location matches when it is the old remote in any form, or a trailing + part of it ("owner/Repo", "Repo"), compared without case. A match is + rewritten to the new normalized key. Returns {"moved": [ids], + "read_only": [ids]}. + """ + from grimoire.services.repo_bindings import normalize_repo_key + + old_key = normalize_repo_key(old_repo) + new_key = normalize_repo_key(new_repo) + + def rename(loc: dict) -> dict | None: + recorded = normalize_repo_key(loc.get("repo") or "") + if not recorded or recorded == new_key: + return None + if recorded != old_key and not old_key.endswith("/" + recorded): + return None + return {**loc, "repo": new_key} + + return await _rewrite_locations(user_id, project_id, rename) + + async def invalidate_for_push( repo_key: str, changed: list[str], diff --git a/tests/test_integration_repo_move.py b/tests/test_integration_repo_move.py index 0d9b1f88..700ddad8 100644 --- a/tests/test_integration_repo_move.py +++ b/tests/test_integration_repo_move.py @@ -100,3 +100,35 @@ async def test_the_same_repo_under_both_names_is_refused(bound): await svc.move_binding( bound["owner"], OLD, "git@git.example.com:alice/oldname", bound["pid"], ) + + +@pytest.mark.integration +async def test_the_snippets_recorded_in_the_old_repo_move_with_it(bound): + from grimoire.services import snippets as snippets_svc + + owner, pid = bound["owner"], bound["pid"] + + async def snippet(name, *repos): + note = await snippets_svc.create_snippet( + owner, name=name, code=f"def {name}():\n pass\n", language="python", + project_id=pid, + locations=[{"repo": r, "path": "src/app.py", "symbol": name} for r in repos], + ) + return int(note.id) + + moved_one = await snippet("moved_one", "OldName", "alice/oldname", OLD) + mixed = await snippet("mixed", "git.example.com/alice/oldname", "elsewhere/gadget") + untouched = await snippet("untouched", "Gadget", "git.example.com/alice/oldnamesake") + + result = await snippets_svc.move_location_repo(owner, pid, OLD, NEW) + + assert sorted(result["moved"]) == sorted([moved_one, mixed]) + assert result["read_only"] == [] + + async def repos(snippet_id): + note = await snippets_svc.get_snippet(owner, snippet_id) + return [loc["repo"] for loc in snippets_svc.snippet_fields(note)["locations"]] + + assert await repos(moved_one) == [NEW_KEY, NEW_KEY, NEW_KEY] + assert await repos(mixed) == [NEW_KEY, "elsewhere/gadget"] + assert await repos(untouched) == ["Gadget", "git.example.com/alice/oldnamesake"] -- 2.54.0 From f77d18cb63d960b9f27a40e5070d970788c15a87 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 22 Oct 2026 16:21:19 -0400 Subject: [PATCH 5/5] =?UTF-8?q?fix(6245):=20a=20re-run=20of=20bind=5Frepo(?= =?UTF-8?q?moved=5Ffrom=3D=E2=80=A6)=20finishes=20an=20earlier=20move?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Once the binding has moved, the old remote is no longer bound, and move_binding refused. An install that renamed its repo before snippet locations moved with it had no way to move them. When the old remote is unbound and the new one is bound to this project, bind_repo now skips the binding move and still moves the snippet locations that name the old repo. The snippet-move test gives each location its own path: rewritten to one repo, identical locations merge into one. Co-Authored-By: Claude Opus 5.5 --- src/grimoire/mcp/tools/repos.py | 17 +++++++++++---- tests/test_integration_repo_move.py | 33 ++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/grimoire/mcp/tools/repos.py b/src/grimoire/mcp/tools/repos.py index a63faf39..c1d86c75 100644 --- a/src/grimoire/mcp/tools/repos.py +++ b/src/grimoire/mcp/tools/repos.py @@ -34,8 +34,10 @@ async def bind_repo( under the old one. Pass the old remote as `moved_from` and the binding, every shape judgment, and every snippet location recorded in the old repo move to the new name together. Binding the new name without it starts an - empty ledger beside the old one. A snippet shared with you read-only keeps - its location and is listed in `snippets_read_only`; its owner moves it. + empty ledger beside the old one. Running it again once the binding has + moved moves only what still names the old repo. A snippet shared with you + read-only keeps its location and is listed in `snippets_read_only`; its + owner moves it. Args: repo_url: the repo's git remote (e.g. the output of @@ -54,9 +56,16 @@ async def bind_repo( ref_arg = None if not ref else ("" if ref.strip() == "-" else ref) moved = snippets = None if moved_from: - _, moved = await repo_bindings_svc.move_binding( - uid, moved_from, repo_url, project_id, + already = ( + await repo_bindings_svc.resolve_project(uid, moved_from) is None + and await repo_bindings_svc.resolve_project(uid, repo_url) == project_id ) + if already: + moved = 0 + else: + _, moved = await repo_bindings_svc.move_binding( + uid, moved_from, repo_url, project_id, + ) snippets = await snippets_svc.move_location_repo( uid, project_id, moved_from, repo_url, ) diff --git a/tests/test_integration_repo_move.py b/tests/test_integration_repo_move.py index 700ddad8..ee102a19 100644 --- a/tests/test_integration_repo_move.py +++ b/tests/test_integration_repo_move.py @@ -112,7 +112,12 @@ async def test_the_snippets_recorded_in_the_old_repo_move_with_it(bound): note = await snippets_svc.create_snippet( owner, name=name, code=f"def {name}():\n pass\n", language="python", project_id=pid, - locations=[{"repo": r, "path": "src/app.py", "symbol": name} for r in repos], + # A path per location: rewritten to one repo, identical locations + # would merge into one. + locations=[ + {"repo": r, "path": f"src/app{i}.py", "symbol": name} + for i, r in enumerate(repos) + ], ) return int(note.id) @@ -132,3 +137,29 @@ async def test_the_snippets_recorded_in_the_old_repo_move_with_it(bound): assert await repos(moved_one) == [NEW_KEY, NEW_KEY, NEW_KEY] assert await repos(mixed) == [NEW_KEY, "elsewhere/gadget"] assert await repos(untouched) == ["Gadget", "git.example.com/alice/oldnamesake"] + + +@pytest.mark.integration +async def test_running_the_move_again_finishes_what_an_earlier_one_left(bound): + from grimoire.mcp._context import _user_id_ctx + from grimoire.mcp.tools.repos import bind_repo + from grimoire.services import snippets as snippets_svc + + owner, pid = bound["owner"], bound["pid"] + await svc.move_binding(owner, OLD, NEW, pid) + note = await snippets_svc.create_snippet( + owner, name="left_behind", code="def left_behind():\n pass\n", + language="python", project_id=pid, + locations=[{"repo": "OldName", "path": "src/app.py", "symbol": "left_behind"}], + ) + + token = _user_id_ctx.set(owner) + try: + out = await bind_repo(NEW, pid, moved_from=OLD) + finally: + _user_id_ctx.reset(token) + + assert out["shapes_moved"] == 0 + assert out["snippets_moved"] == [int(note.id)] + moved = await snippets_svc.get_snippet(owner, int(note.id)) + assert snippets_svc.snippet_fields(moved)["locations"][0]["repo"] == NEW_KEY -- 2.54.0