feat(learn): Learn's agent, an MCP server suggesting in shared studysets
Some checks failed
CI / check (push) Failing after 1m56s

Halkyon's ADR 0044, step 6c (D7, D49 to D52). apps/learn/halkyon_learn_agent
is one executable, `halkyon-agent --instance URL sign-in | sync | mcp`:

- sign-in keeps the token read from stdin, signs in with it, makes the
  agent's key pair on its first sign-in, keeps it before setting the
  public halves on the register (agents.setKeys), and syncs;
- it opens its data as the app's _openPersonData does, on
  halkyon_learn_core and halkyon_content: its own SQLite database, the
  sync's space router, its keys and those of the spaces shared with it,
  and the repositories of studysets, cards, notes, paths, files and
  feedback;
- mcp serves ten tools over stdio (dart_mcp): list, read and search the
  studysets shared with it, suggest a change or a new card or note,
  report, list a studyset's suggestions and reply. Each syncs first and
  a suggestion again at once; a refusal is the tool's error;
- its files live in $XDG_CONFIG_HOME/halkyon-agent/<host>, 0700 and
  0600, refused when others may read them (D50);
- tool/install.sh builds it with `dart build cli` (libsodium and SQLite
  bundled) and copies it to its user on the host, the build before kept
  (D52).

The synced gateways of learning paths and files, and the fakes of the
core's gateways, move into halkyon_learn_core (its testing.dart), which
the app's tests and the agent's share.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Tizian 「ティツィアーン」 <raisondetredev@pm.me>
This commit is contained in:
Tizian 「ティツィアーン」 2026-11-11 22:06:29 +01:00
commit 54e212a51c
Signed by: raisondetredev
GPG key ID: 07F6FCF405488B64
121 changed files with 2925 additions and 314 deletions

View file

@ -4,7 +4,7 @@ What holds for every app and package of this repository (how work is done here,
A spaced-repetition learning app: studysets of flashcards, reviewed on an FSRS schedule. Content is rich text (`appflowy_editor` documents) everywhere. Targets: Linux, Windows, macOS, Android, iOS. There is no web build.
- **Packages** (`apps/learn/`): `halkyon_learn_server` (endpoints, models, migrations), `halkyon_learn_client` (generated, never edited), `halkyon_learn_flutter` (the app, ID `app.halkyon.learn`), `halkyon_learn_core` (Learn's content in pure Dart, shared with its agent, Halkyon's ADR 0044, D49: privacy, sync, payloads, and the models, gateways and repositories of studysets, cards, notes, tags and feedback; the app imports them from `package:halkyon_learn_core/…`, and what only it shows stays in it), `halkyon_learn_curator` (the dictionaries' converter, below), and `tool/` with the scripts that write the app's assets (maps, Anki fixtures; run them from `apps/learn`; its icon, Lucide's graduation cap since ADR 0031, is the root's `tool/app_icons.py`'s, `assets/icon/halkyon_learn_icon.png`, also atop the rail, on the launch screen and on halkyon_app's screens (`learnIcon`) since 2 Nov 2026, as Todo's and Train's show theirs, ADR 0031, D6). What every Halkyon server has comes from the Serverpod module `halkyon_base` (ADR 0014, decided 2026-10-19; `packages/halkyon_base_server` and `packages/halkyon_base_client`, which Learn's packages take by path): signing in, the account's ways in and its deletion, the pruning, and the instance's basics. The server sets it up for Learn before it starts (`HalkyonBase.configure(pod, learnBase(accounts: learnAccounts()))` in `server.dart`; `lib/src/auth/learn_base.dart`: Learn holds the instance's register of accounts (ADR 0016), `learnAccounts` reading the members from `INSTANCE_MEMBERS` and refusing to start with `ACCOUNT_REGISTER_URL`; the app it serves, `learn`, which its instances name in their basics and the app checks (never change it), the app's name in sign-in mails, this project's source, `minimumAppBuild`, Learn's own deletion as a hook), its endpoints are `client.modules.base` in the app, its tables (`email_identity`, `email_code_request`) are the module's, and tests that delete people or ask `instance.info()` set it up as the server does (`useLearnBase(sessionBuilder)`). What every Halkyon app's shell has comes from `halkyon_app` on the module's client (ADR 0014, `packages/halkyon_app`; with `halkyon_core`'s `SerialQueue` and `CoalescingRunner`): the instances and the first start, signing in and switching person, the gates (`InstanceGate`, `SessionGate`, `PersonScope`, `AppScope`), the sync service and where it stands, with texts of its own (`HalkyonAppLocalizations`, in `appLocalizationsDelegates`) that name the app from `learnFrame`. Change what they hold there, not here.
- **Packages** (`apps/learn/`): `halkyon_learn_server` (endpoints, models, migrations), `halkyon_learn_client` (generated, never edited), `halkyon_learn_flutter` (the app, ID `app.halkyon.learn`), `halkyon_learn_core` (Learn's content in pure Dart, shared with its agent, Halkyon's ADR 0044, D49: privacy, sync, payloads, and the models, gateways and repositories of studysets, cards, notes, tags and feedback; the app imports them from `package:halkyon_learn_core/…`, and what only it shows stays in it; the fakes of its gateways in its `testing.dart`), `halkyon_learn_agent` (Learn's agent, D50 to D52: `halkyon-agent sign-in | sync | mcp`, an MCP server over stdio reading the studysets shared with it and suggesting, on the core, its README saying how to install and run it), `halkyon_learn_curator` (the dictionaries' converter, below), and `tool/` with the scripts that write the app's assets (maps, Anki fixtures; run them from `apps/learn`; its icon, Lucide's graduation cap since ADR 0031, is the root's `tool/app_icons.py`'s, `assets/icon/halkyon_learn_icon.png`, also atop the rail, on the launch screen and on halkyon_app's screens (`learnIcon`) since 2 Nov 2026, as Todo's and Train's show theirs, ADR 0031, D6). What every Halkyon server has comes from the Serverpod module `halkyon_base` (ADR 0014, decided 2026-10-19; `packages/halkyon_base_server` and `packages/halkyon_base_client`, which Learn's packages take by path): signing in, the account's ways in and its deletion, the pruning, and the instance's basics. The server sets it up for Learn before it starts (`HalkyonBase.configure(pod, learnBase(accounts: learnAccounts()))` in `server.dart`; `lib/src/auth/learn_base.dart`: Learn holds the instance's register of accounts (ADR 0016), `learnAccounts` reading the members from `INSTANCE_MEMBERS` and refusing to start with `ACCOUNT_REGISTER_URL`; the app it serves, `learn`, which its instances name in their basics and the app checks (never change it), the app's name in sign-in mails, this project's source, `minimumAppBuild`, Learn's own deletion as a hook), its endpoints are `client.modules.base` in the app, its tables (`email_identity`, `email_code_request`) are the module's, and tests that delete people or ask `instance.info()` set it up as the server does (`useLearnBase(sessionBuilder)`). What every Halkyon app's shell has comes from `halkyon_app` on the module's client (ADR 0014, `packages/halkyon_app`; with `halkyon_core`'s `SerialQueue` and `CoalescingRunner`): the instances and the first start, signing in and switching person, the gates (`InstanceGate`, `SessionGate`, `PersonScope`, `AppScope`), the sync service and where it stands, with texts of its own (`HalkyonAppLocalizations`, in `appLocalizationsDelegates`) that name the app from `learnFrame`. Change what they hold there, not here.
- **Instances**: anyone may run one. The app takes the server URL from `--dart-define=SERVER_URL=…`, so never hard-code a host.
## Working on Learn
@ -51,7 +51,7 @@ A spaced-repetition learning app: studysets of flashcards, reviewed on an FSRS s
- **By layer**: models with plain unit tests; repositories against fake gateways; blocs by asserting the emitted state sequence; widgets pumped in isolation, presentation widgets fed with ready-made data.
- **Server endpoints are tested for real** against the embedded Postgres (`withServerpod`, `dart test` in the server package), including the denial tests.
- **Test dependencies come from a test factory**, `testDependencies(...)` in `test/support/test_dependencies.dart`, filling in fakes by default (a factory in `lib/` couldn't reach the fakes in `test/`), so a new dependency changes one place. Don't make dependencies nullable to spare tests: that moves null checks into production code.
- Shared fakes live in `test/support/`, those of halkyon_app's boundaries in its `package:halkyon_app/testing.dart` (`FakeAuthGateway`, `FakeInstanceChecker`, `MemorySignInAddresses`, `MemoryInstanceStore`, `MemoryPendingChangesStore`), which `testDependencies` fills in; fakes pre-stub their streams so an incidental subscription doesn't fail the test.
- Shared fakes live in `test/support/`, those of the core's gateways in `package:halkyon_learn_core/testing.dart`, those of halkyon_app's boundaries in its `package:halkyon_app/testing.dart` (`FakeAuthGateway`, `FakeInstanceChecker`, `MemorySignInAddresses`, `MemoryInstanceStore`, `MemoryPendingChangesStore`), which `testDependencies` fills in; fakes pre-stub their streams so an incidental subscription doesn't fail the test.
- **Editor in widget tests**: host `AppFlowyEditor` in a scrollable body with a fixed-height slot (an over-constrained `Expanded` hangs the test), and `pump(const Duration(seconds: 1))` after editor changes to flush its timers. Test the document ↔ JSON round-trip as plain unit tests.
- **No `Stream.first` on a repository's stream in code that widget tests run**: `first` waits for the subscription's cancel future, which for a broadcast stream is a completed future of the root zone, so under the widget test's fake clock it never completes. Read once with the repository's `all()` instead. For the same reason a repository never keeps a completed future to chain later work on (a `Future.value()` made in `setUp` runs what waits for it in the real zone): a queue of writes starts empty and empties again when idle (`SerialQueue`, halkyon_core), and a cache keeps values, not futures (`GeoMapRepository`). Assets are read for real, which the fake clock doesn't advance: a widget test showing a map gets the maps read beforehand (`loadedMaps(tester)` into `testDependencies(maps: ...)`), and one showing how a character is written its strokes (`loadedStrokes(tester, characters)` into `testDependencies(strokes: ...)`). Nor is a subscription that has finished cancelled with `await` there (`await subscription.cancel()` on a stream done): its cancel future never completes under the fake clock either, which hung everything after it (found 2026-10-26 with the flashcards an assistant proposes); cancel it unawaited (`CardProposalsCubit`), or forget it in `onDone` and `onError`, so only one still running is awaited (`ConversationCubit`).
- **Text inside the editor's views** (`LearnContentView`, `LearnContentEditor`) is rich text: find it with `findRichText: true`.

View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View file

@ -0,0 +1,62 @@
# halkyon_learn_agent
Halkyon Learn's agent (Halkyon's ADR 0044, D6, D7, D10, D49 to D52): an account of its own on an
instance, made in a person's Profile (Agents) and invited as a Viewer to the studysets they share
with it. It reads their cards and notes and **suggests**: changes, new cards and notes, reports of
what should go, replies. It never writes into a studyset; its Owner and Editors accept or decline
in the app (a studyset's Suggestions). Claude Code, or another MCP client, reaches it over stdio.
## Using it
On the machine it runs on, as a user of its own (D7; halkyon.li's host at home):
1. Build and copy it there from a laptop with Dart, `tool/install.sh <ssh target>` (D52). It builds
for the laptop's architecture (`dart build cli`, libsodium and SQLite bundled; the host needs
no Dart) into `~/.local/lib/halkyon-agent/<commit>`, `~/.local/bin/halkyon-agent` pointing to
it, the build before kept.
2. Sign in once with the token its owner copied from their Profile, on stdin, never as an
argument others on the machine could see:
```
$ halkyon-agent --instance https://halkyon.li sign-in < token.txt
```
It keeps the token, makes its key pair and sets the public halves on the register, syncs and
says how many studysets are shared with it.
3. Let Claude Code start it:
```
$ claude mcp add halkyon -- ~/.local/bin/halkyon-agent --instance https://halkyon.li mcp
```
`halkyon-agent --instance … sync` syncs once, e.g. to see that it still can.
## Its tools
`list_studysets`, `read_studyset` (title, description, topics, cards and notes as plain text),
`search_cards`, `suggest_card_change`, `suggest_new_card` (front and back, or a vocabulary
card's word, reading and meanings), `suggest_note_change`, `suggest_new_note`, `report`,
`list_suggestions` (with replies and what was decided) and `reply`. Only studysets shared with it
count. Each call syncs first and a suggestion syncs again at once; a sync that fails leaves what
it holds to read, and the result says so. A refusal (a studyset not shared with it, a card it
can't find) is the tool's error, which the model reads.
## What it keeps
`$XDG_CONFIG_HOME/halkyon-agent/<host>[_<port>]/` (else `~/.config/…`), the folder 0700 and its
files 0600, refused when others may read or change them (D50): `token`, `keys.json` (its key
pair, unsealed: its user's boundary protects it), `keys_set`, `sync.sqlite` (the shared
studysets, opened as the app opens them), `key_pins.json` (the members' public keys as first
seen), `privacy.json` and `files/`. An instance is reached over HTTPS, or plain HTTP on the same
machine alone. Its session is kept in memory, a sign-in with the token at every start.
## Code
- `lib/src/open_agent.dart` signs in and opens its data as the app's `_openPersonData` does, on
`halkyon_learn_core` (its gateways and repositories) and `halkyon_content` (keys, shared
spaces, files).
- `lib/src/agent_library.dart` reads and suggests, `lib/src/agent_server.dart` makes tools of it
(`dart_mcp`), `lib/src/agent_sync.dart` syncs on demand, `lib/src/agent_home.dart` keeps its
files; `bin/halkyon_agent.dart` is the CLI. Tests run on the core's fakes, without a server.
Licensed under the AGPL-3.0.

View file

@ -0,0 +1,9 @@
# The workspace's lint rules (see ../../analysis_options.yaml).
include: ../../../analysis_options.yaml
analyzer:
exclude:
- build/**
formatter:
trailing_commas: preserve

View file

@ -0,0 +1,134 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:args/command_runner.dart';
import 'package:dart_mcp/stdio.dart';
import 'package:halkyon_learn_agent/src/agent_home.dart';
import 'package:halkyon_learn_agent/src/agent_server.dart';
import 'package:halkyon_learn_agent/src/open_agent.dart';
/// Halkyon Learn's agent (Halkyon's ADR 0044, D50, D51): `sign-in` keeps
/// the token its owner made, `sync` syncs once, and `mcp` serves its tools
/// over stdio to Claude Code or another MCP client. Everything it says
/// goes to stderr, as stdout is the protocol's.
Future<void> main(List<String> arguments) async {
final runner =
CommandRunner<void>(
'halkyon-agent',
"Halkyon Learn's agent: reads the studysets shared with it and "
'suggests changes to them.',
)
..argParser.addOption(
'instance',
help: 'The instance it is an agent on, e.g. https://halkyon.li.',
mandatory: true,
)
..addCommand(_SignIn())
..addCommand(_Sync())
..addCommand(_Mcp());
try {
await runZoned(
() => runner.run(arguments),
zoneSpecification: ZoneSpecification(
print: (self, parent, zone, line) => stderr.writeln(line),
),
);
} on UsageException catch (usage) {
stderr.writeln(usage);
exitCode = 64;
} on AgentHomeRefused catch (refused) {
stderr.writeln(refused.message);
exitCode = 1;
} on Exception catch (failure) {
// The instance out of reach, the token refused, a sync failing: said
// in one line, the exit code telling a script.
stderr.writeln('halkyon-agent: $failure');
exitCode = 1;
}
}
/// The instance the command runs on, and its home.
Future<(Uri, AgentHome)> _homeOf(Command<void> command) async {
final instance = Uri.parse(command.globalResults!.option('instance')!);
return (instance, await AgentHome.open(AgentHome.defaultRoot(), instance));
}
/// Keeps the token read from stdin, then signs in with it, making and
/// setting the agent's keys and syncing once.
final class _SignIn() extends Command<void> {
@override
String get name => 'sign-in';
@override
String get description =>
'Keeps the token read from stdin (never an argument, which others on '
'this machine may see), signs in and syncs.';
@override
Future<void> run() async {
final (instance, home) = await _homeOf(this);
final token = (await stdin.transform(utf8.decoder).join()).trim();
if (token.isEmpty) {
throw UsageException('No token on stdin.', usage);
}
await home.keepToken(token);
final agent = await openAgent(home, instance);
try {
await agent.sync.syncNow();
final shared = await agent.library.sharedStudysets();
stderr.writeln(
'Signed in on ${instance.host}; ${shared.length} studysets shared.',
);
} finally {
await agent.close();
}
}
}
/// Syncs once.
final class _Sync() extends Command<void> {
@override
String get name => 'sync';
@override
String get description => 'Syncs the studysets shared with it, once.';
@override
Future<void> run() async {
final (instance, home) = await _homeOf(this);
final agent = await openAgent(home, instance);
try {
await agent.sync.syncNow();
} finally {
await agent.close();
}
}
}
/// Serves its tools over stdio until the client goes.
final class _Mcp() extends Command<void> {
@override
String get name => 'mcp';
@override
String get description =>
'Serves its tools to an MCP client over stdio, e.g. '
'`claude mcp add halkyon -- halkyon-agent --instance URL mcp`.';
@override
Future<void> run() async {
final (instance, home) = await _homeOf(this);
final agent = await openAgent(home, instance);
final server = AgentServer(
stdioChannel(input: stdin, output: stdout),
agent.library,
sync: agent.sync.syncNow,
);
try {
await server.done;
} finally {
await agent.close();
}
}
}

View file

@ -0,0 +1,151 @@
import 'dart:convert';
import 'dart:io';
import 'package:halkyon_content/halkyon_content.dart';
import 'package:path/path.dart' as p;
/// Why the agent's home wasn't opened or read: a folder or file others may
/// read or change, or an instance it wouldn't reach safely.
final class const AgentHomeRefused(
/// What to tell the person running it.
final String message,
) implements Exception {
@override
String toString() => message;
}
/// Where the agent keeps its token, keys and data for one instance
/// (Halkyon's ADR 0044, D50): `<root>/<host>[_<port>]`, mode 0700, its
/// files 0600, as ssh keeps keys: what others may read or change is
/// refused rather than read. The agent runs as a user of its own (D7),
/// whose boundary protects them.
final class AgentHome._(
/// The instance's folder.
final Directory folder,
) {
/// The folder for [instance] in [root], made if it isn't there. Refused
/// for an instance over plain HTTP other than this machine, and for a
/// folder others may enter.
static Future<AgentHome> open(Directory root, Uri instance) async {
final local = const {'localhost', '127.0.0.1', '::1'}.contains(
instance.host,
);
if (instance.scheme != 'https' && !(instance.scheme == 'http' && local)) {
throw AgentHomeRefused(
'The instance $instance is reached over HTTPS only, or plain HTTP '
'on this machine: the token would travel in the clear.',
);
}
final name = instance.hasPort
? '${instance.host}_${instance.port}'
: instance.host;
final folder = Directory(p.join(root.path, name));
if (!folder.existsSync()) {
await _private(root, mode: '700');
await folder.create(recursive: true);
await _chmod(folder.path, '700');
}
_refuseShared(folder.path, 'The folder');
return AgentHome._(folder);
}
/// The default root: `$XDG_CONFIG_HOME/halkyon-agent`, else
/// `~/.config/halkyon-agent`.
static Directory defaultRoot() {
final env = Platform.environment;
final config = switch (env['XDG_CONFIG_HOME']) {
final String home when home.isNotEmpty => home,
_ => p.join(env['HOME'] ?? '.', '.config'),
};
return Directory(p.join(config, 'halkyon-agent'));
}
File get _tokenFile => File(p.join(folder.path, 'token'));
File get _keysFile => File(p.join(folder.path, 'keys.json'));
File get _keysSetFile => File(p.join(folder.path, 'keys_set'));
/// The local synced database.
String get database => p.join(folder.path, 'sync.sqlite');
/// The public keys pinned for the members of its spaces.
File get pins => File(p.join(folder.path, 'key_pins.json'));
/// What it saw of privacy, which the instance can't take back.
File get privacy => File(p.join(folder.path, 'privacy.json'));
/// People's files, as the app keeps them.
Directory get files => Directory(p.join(folder.path, 'files'));
/// The token its owner made, kept by `sign-in`; null before.
Future<String?> token() async => (await _read(_tokenFile))?.trim();
/// Keeps [token], for its user alone.
Future<void> keepToken(String token) =>
_write(_tokenFile, '${token.trim()}\n');
/// Its key pair, made on its first sign-in; null before.
Future<UnlockedAccountKeys?> keys() async => switch (await _read(_keysFile)) {
final String json => UnlockedAccountKeys.fromJson(
jsonDecode(json) as Map<String, Object?>,
),
null => null,
};
/// Keeps [keys], for its user alone.
Future<void> keepKeys(UnlockedAccountKeys keys) =>
_write(_keysFile, jsonEncode(keys.toJson()));
/// Whether the register holds its keys' public halves, as noted.
Future<bool> keysSet() async => await _read(_keysSetFile) != null;
/// Notes that the register holds its keys' public halves.
Future<void> noteKeysSet() => _write(_keysSetFile, '');
/// [file]'s text; null where it isn't there; refused where others may
/// read or change it.
Future<String?> _read(File file) async {
if (!file.existsSync()) {
return null;
}
_refuseShared(file.path, 'The file');
return await file.readAsString();
}
/// Writes [text] into [file] made readable to its user alone first, so
/// it is never readable to others, not even for a moment.
static Future<void> _write(File file, String text) async {
final temp = File('${file.path}.new');
await temp.writeAsString('');
await _chmod(temp.path, '600');
await temp.writeAsString(text, flush: true);
await temp.rename(file.path);
}
/// [directory] made, for its user alone where it is new.
static Future<void> _private(
Directory directory, {
required String mode,
}) async {
if (!directory.existsSync()) {
await directory.create(recursive: true);
await _chmod(directory.path, mode);
}
}
static Future<void> _chmod(String path, String mode) async {
final result = await Process.run('chmod', [mode, path]);
if (result.exitCode != 0) {
throw AgentHomeRefused("Couldn't make $path its user's alone.");
}
}
/// Refuses [path] where its group or others may read, write or enter it.
static void _refuseShared(String path, String what) {
if (FileStat.statSync(path).mode & 0x3f != 0) {
throw AgentHomeRefused(
"$what $path is open to others; make it its user's alone "
'(chmod go-rwx) and its token new.',
);
}
}
}

View file

@ -0,0 +1,372 @@
import 'package:halkyon_content/rich_text.dart';
import 'package:halkyon_learn_core/feature/card/data/card_repository.dart';
import 'package:halkyon_learn_core/feature/card/model/card.dart';
import 'package:halkyon_learn_core/feature/card/model/card_content.dart';
import 'package:halkyon_learn_core/feature/feedback/data/feedback_repository.dart';
import 'package:halkyon_learn_core/feature/feedback/model/feedback.dart';
import 'package:halkyon_learn_core/feature/note/data/note_repository.dart';
import 'package:halkyon_learn_core/feature/note/model/note.dart';
import 'package:halkyon_learn_core/feature/note/model/note_content.dart';
import 'package:halkyon_learn_core/feature/studyset/data/studyset_repository.dart';
import 'package:halkyon_learn_core/feature/studyset/model/studyset.dart';
/// Why the agent did nothing: a studyset not shared with it, an item it
/// can't find there, or what it was asked for isn't something it does.
/// Said to the model as the tool's error.
final class const AgentRefused(
/// What to tell the model.
final String message,
) implements Exception {
@override
String toString() => message;
}
/// What the agent reads and suggests (Halkyon's ADR 0044, D7, D10, D51),
/// on Learn's repositories as the app has them: only the studysets shared
/// with it, as text; every change a suggestion in the studyset's space,
/// never a write to the studyset itself, as the agent is a Viewer (D10).
/// What it hands back is JSON, for the model to read.
class AgentLibrary({
required final StudysetRepository studysets,
required final CardRepository cards,
required final NoteRepository notes,
required final FeedbackRepository feedback,
}) {
/// The card types it writes: those whose parts are text alone.
static const writableTypes = {CardType.frontBack, CardType.vocabulary};
/// The studysets shared with it, not deleted, each with its parent, its
/// role and how many cards and notes it holds.
Future<List<Map<String, Object?>>> sharedStudysets() async {
final shared = await _shared();
final listed = <Map<String, Object?>>[];
for (final studyset in shared.values) {
listed.add({
'id': studyset.id,
'title': studyset.content.title,
'parent': shared.containsKey(studyset.parentId)
? studyset.parentId
: null,
'role': studyset.viewOnly ? 'viewer' : 'editor',
if (studyset.isLocked) 'locked': true,
'cards': (await cards.cardsOf(studyset.id)).length,
'notes': (await notes.notesOf(studyset.id)).length,
});
}
return listed;
}
/// The studyset [id] whole: its title, description, topics, cards and
/// notes as text. Refused for one not shared with it.
Future<Map<String, Object?>> studyset(String id) async {
final shared = await _shared();
final studyset = _sharedOne(shared, id);
return {
'id': studyset.id,
'title': studyset.content.title,
if (!studyset.content.description.isBlank)
'description': studyset.content.description.plainText,
'role': studyset.viewOnly ? 'viewer' : 'editor',
if (studyset.isLocked) 'locked': true,
'topics': [
for (final topic in shared.values)
if (topic.parentId == id) topic.id,
],
'cards': [for (final card in await cards.cardsOf(id)) _cardJson(card)],
'notes': [for (final note in await notes.notesOf(id)) _noteJson(note)],
};
}
/// The shared cards whose text holds [query], whatever its case, within
/// [studysetId] and its topics where given.
Future<List<Map<String, Object?>>> search(
String query, {
String? studysetId,
}) async {
final shared = await _shared();
final within = studysetId == null
? shared.keys.toList()
: [
_sharedOne(shared, studysetId).id,
..._topicsOf(studysetId, shared),
];
final needle = query.toLowerCase();
return [
for (final id in within)
for (final card in await cards.cardsOf(id))
if (_textOf(card.content).toLowerCase().contains(needle))
{..._cardJson(card), 'studyset': id},
];
}
/// Suggests a change to the card [cardId]: each part given replaces the
/// card's, the rest kept.
Future<void> suggestCardChange(
String cardId, {
required String message,
String? front,
String? back,
String? reading,
List<String>? meanings,
List<String>? hints,
String? explanation,
}) async {
final (studysetId, card) = await _cardOf(cardId);
if (!writableTypes.contains(card.content.type)) {
throw AgentRefused(
'A ${card.content.type.name} card is changed in the app, not here.',
);
}
await feedback.suggestCardInSpace(
_withParts(
card.content,
front: front,
back: back,
reading: reading,
meanings: meanings,
hints: hints,
explanation: explanation,
),
studysetId: studysetId,
cardId: cardId,
body: message,
);
}
/// Suggests a new card for the studyset [studysetId], of [type]
/// (`frontBack` or `vocabulary`).
Future<void> suggestNewCard(
String studysetId, {
required String front,
required String message,
String type = 'frontBack',
String back = '',
String reading = '',
List<String> meanings = const [],
List<String> hints = const [],
String? explanation,
}) async {
_sharedOne(await _shared(), studysetId);
final cardType = CardType.values.where((t) => t.name == type).firstOrNull;
if (cardType == null || !writableTypes.contains(cardType)) {
throw AgentRefused(
'Cards of type "$type" are written in the app; here frontBack or '
'vocabulary.',
);
}
await feedback.suggestCardInSpace(
_withParts(
CardContent(
type: cardType,
front: RichContent.empty(),
back: RichContent.empty(),
),
front: front,
back: back,
reading: reading,
meanings: meanings,
hints: hints,
explanation: explanation,
),
studysetId: studysetId,
body: message,
);
}
/// Suggests a change to the note [noteId]: its title or text, or both.
Future<void> suggestNoteChange(
String noteId, {
required String message,
String? title,
String? body,
}) async {
final (studysetId, note) = await _noteOf(noteId);
await feedback.suggestNoteInSpace(
NoteContent(
title: title ?? note.content.title,
body: body == null ? note.content.body : RichContent.plain(body),
),
studysetId: studysetId,
noteId: noteId,
body: message,
);
}
/// Suggests a new note for the studyset [studysetId].
Future<void> suggestNewNote(
String studysetId, {
required String title,
required String body,
required String message,
}) async {
_sharedOne(await _shared(), studysetId);
await feedback.suggestNoteInSpace(
NoteContent(title: title, body: RichContent.plain(body)),
studysetId: studysetId,
body: message,
);
}
/// Asks for the card or note ([kind]) [itemId] to go, saying why in
/// [message], which it must.
Future<void> report(
String kind,
String itemId, {
required String message,
}) async {
if (message.trim().isEmpty) {
throw const AgentRefused('Say why it should go.');
}
final (targetKind, studysetId) = switch (kind) {
'card' => (FeedbackTargetKind.card, (await _cardOf(itemId)).$1),
'note' => (FeedbackTargetKind.note, (await _noteOf(itemId)).$1),
_ => throw AgentRefused(
'Only a card or a note is reported, not "$kind".',
),
};
await feedback.reportInSpace(
studysetId: studysetId,
kind: targetKind,
item: itemId,
category: ReportCategory.other,
body: message,
);
}
/// The suggestions and reports within the studyset [studysetId], each
/// with its replies and how it was decided.
Future<List<Map<String, Object?>>> suggestions(String studysetId) async {
_sharedOne(await _shared(), studysetId);
return [
for (final thread in await feedback.threadsInSpaceOf(studysetId))
{
'id': thread.threadId,
'kind': thread.kind.name,
'target': {
'kind': thread.target.kind.name,
'item': thread.target.item,
},
'by': '@${thread.writer.handle}',
'status': thread.status.name,
'message': thread.body,
'replies': [
for (final reply in thread.messages)
{'by': '@${reply.by.handle}', 'message': reply.body},
],
},
];
}
/// Replies [message] to the suggestion or report [threadId] within the
/// studyset [studysetId].
Future<void> reply(
String studysetId,
String threadId, {
required String message,
}) async {
_sharedOne(await _shared(), studysetId);
final thread =
(await feedback.threadsInSpaceOf(studysetId))
.where((thread) => thread.threadId == threadId)
.firstOrNull ??
(throw AgentRefused('No suggestion $threadId in $studysetId.'));
await feedback.reply(thread, message);
}
/// The studysets shared with it, not deleted, by id.
Future<Map<String, Studyset>> _shared() async => {
for (final studyset in await studysets.all())
if (studyset.isShared) studyset.id: studyset,
};
/// The shared studyset [id]; refused for any other.
Studyset _sharedOne(Map<String, Studyset> shared, String id) =>
shared[id] ?? (throw AgentRefused('No studyset $id is shared with you.'));
/// Every topic below [id], at any depth.
List<String> _topicsOf(String id, Map<String, Studyset> shared) => [
for (final topic in shared.values)
if (topic.parentId == id) ...[topic.id, ..._topicsOf(topic.id, shared)],
];
/// The shared studyset holding the card [cardId], and the card.
Future<(String, Card)> _cardOf(String cardId) async {
for (final id in (await _shared()).keys) {
for (final card in await cards.cardsOf(id)) {
if (card.id == cardId) {
return (id, card);
}
}
}
throw AgentRefused('No card $cardId in a studyset shared with you.');
}
/// The shared studyset holding the note [noteId], and the note.
Future<(String, Note)> _noteOf(String noteId) async {
for (final id in (await _shared()).keys) {
for (final note in await notes.notesOf(id)) {
if (note.id == noteId) {
return (id, note);
}
}
}
throw AgentRefused('No note $noteId in a studyset shared with you.');
}
static CardContent _withParts(
CardContent content, {
String? front,
String? back,
String? reading,
List<String>? meanings,
List<String>? hints,
String? explanation,
}) {
final changed = content.copyWith(
front: front == null ? null : RichContent.plain(front),
back: back == null ? null : RichContent.plain(back),
reading: reading,
meanings: meanings,
hints: hints == null
? null
: [for (final h in hints) RichContent.plain(h)],
);
return explanation == null
? changed
: changed.withField(
CardField.explanation,
RichContent.plain(explanation),
);
}
static String _textOf(CardContent content) => [
content.front.plainText,
content.back.plainText,
content.reading,
...content.meanings,
for (final hint in content.hints) hint.plainText,
content.explanation?.plainText ?? '',
].join('\n');
static Map<String, Object?> _cardJson(Card card) {
final content = card.content;
return {
'id': card.id,
'type': content.type.name,
'front': content.front.plainText,
if (!content.back.isBlank) 'back': content.back.plainText,
if (content.reading.isNotEmpty) 'reading': content.reading,
if (content.meanings.isNotEmpty) 'meanings': content.meanings,
if (content.hints.isNotEmpty)
'hints': [for (final hint in content.hints) hint.plainText],
if (content.explanation case final explanation? when !explanation.isBlank)
'explanation': explanation.plainText,
};
}
static Map<String, Object?> _noteJson(Note note) => {
'id': note.id,
'title': note.content.title,
'body': note.content.body.plainText,
};
}

View file

@ -0,0 +1,324 @@
import 'dart:async';
import 'dart:convert';
import 'package:dart_mcp/server.dart';
import 'package:halkyon_learn_agent/src/agent_library.dart';
/// What the model is told of the agent as it connects.
const _instructions =
'Halkyon Learn studysets shared with you, an agent: you read their '
'flashcards and notes and suggest changes, new cards and new notes, which '
"the studyset's owner and editors accept or decline. You change nothing "
"yourself. Suggest in the studyset's language and say why in each "
"message; list a studyset's suggestions to see what was decided.";
/// The agent as an MCP client meets it (Halkyon's ADR 0044, D7, D51): its
/// tools read the studysets shared with it and suggest, through
/// [AgentLibrary]; each call syncs first ([sync]), and a suggestion is
/// synced at once, so it reaches the studyset's deciders. A refusal is the
/// tool's error, which the model reads; a sync that fails leaves what is
/// held to read, and says so.
base class AgentServer(
super.channel,
final AgentLibrary _library, {
/// Syncs the agent's spaces.
required final Future<void> Function() sync,
}) extends MCPServer with ToolsSupport {
this
: super.fromStreamChannel(
implementation: Implementation(
name: 'halkyon-learn-agent',
version: '0.1.0',
),
instructions: _instructions,
) {
_register(
'list_studysets',
'The studysets shared with you: id, title, parent, your role, how '
'many cards and notes.',
{},
read: true,
(args) async => {'studysets': await _library.sharedStudysets()},
);
_register(
'read_studyset',
"A studyset's title, description, topics, flashcards and notes, as "
'text.',
{'studyset_id': Schema.string()},
read: true,
required: ['studyset_id'],
(args) => _library.studyset(_string(args, 'studyset_id')),
);
_register(
'search_cards',
'Flashcards whose text holds the query, whatever its case, in every '
'studyset shared with you or in one and its topics.',
{
'query': Schema.string(),
'studyset_id': Schema.string(description: 'Only in this one.'),
},
read: true,
required: ['query'],
(args) async => {
'cards': await _library.search(
_string(args, 'query'),
studysetId: _optional(args, 'studyset_id'),
),
},
);
_register(
'suggest_card_change',
'Suggests a change to a flashcard (frontBack or vocabulary): each part '
'given replaces its own, the rest kept. Plain text; a new line '
'starts a paragraph.',
{
'card_id': Schema.string(),
'message': Schema.string(description: 'Why.'),
..._cardParts,
},
required: ['card_id', 'message'],
(args) async {
await _library.suggestCardChange(
_string(args, 'card_id'),
message: _string(args, 'message'),
front: _optional(args, 'front'),
back: _optional(args, 'back'),
reading: _optional(args, 'reading'),
meanings: _strings(args, 'meanings'),
hints: _strings(args, 'hints'),
explanation: _optional(args, 'explanation'),
);
return {'suggested': true};
},
);
_register(
'suggest_new_card',
'Suggests a new flashcard for a studyset: frontBack (front and back) '
'or vocabulary (front the word, its reading and meanings).',
{
'studyset_id': Schema.string(),
'message': Schema.string(description: 'Why.'),
'type': Schema.string(
description: 'frontBack (the default) or vocabulary.',
),
..._cardParts,
},
required: ['studyset_id', 'message'],
(args) async {
await _library.suggestNewCard(
_string(args, 'studyset_id'),
type: _optional(args, 'type') ?? 'frontBack',
front:
_optional(args, 'front') ??
(throw const AgentRefused('A new card needs its front.')),
back: _optional(args, 'back') ?? '',
reading: _optional(args, 'reading') ?? '',
meanings: _strings(args, 'meanings') ?? const [],
hints: _strings(args, 'hints') ?? const [],
explanation: _optional(args, 'explanation'),
message: _string(args, 'message'),
);
return {'suggested': true};
},
);
_register(
'suggest_note_change',
"Suggests a change to a note's title or text, or both.",
{
'note_id': Schema.string(),
'message': Schema.string(description: 'Why.'),
'title': Schema.string(),
'body': Schema.string(description: 'The whole text, as it should be.'),
},
required: ['note_id', 'message'],
(args) async {
await _library.suggestNoteChange(
_string(args, 'note_id'),
title: _optional(args, 'title'),
body: _optional(args, 'body'),
message: _string(args, 'message'),
);
return {'suggested': true};
},
);
_register(
'suggest_new_note',
'Suggests a new note for a studyset.',
{
'studyset_id': Schema.string(),
'title': Schema.string(),
'body': Schema.string(),
'message': Schema.string(description: 'Why.'),
},
required: ['studyset_id', 'title', 'body', 'message'],
(args) async {
await _library.suggestNewNote(
_string(args, 'studyset_id'),
title: _string(args, 'title'),
body: _string(args, 'body'),
message: _string(args, 'message'),
);
return {'suggested': true};
},
);
_register(
'report',
'Asks for a flashcard or note to be deleted, saying why: a duplicate, '
'wrong beyond a change, off the topic.',
{
'kind': Schema.string(description: 'card or note.'),
'item_id': Schema.string(),
'message': Schema.string(description: 'Why.'),
},
required: ['kind', 'item_id', 'message'],
(args) async {
await _library.report(
_string(args, 'kind'),
_string(args, 'item_id'),
message: _string(args, 'message'),
);
return {'reported': true};
},
);
_register(
'list_suggestions',
"A studyset's suggestions and reports, yours and others', with "
'their replies and status (open, accepted, declined, closed).',
{'studyset_id': Schema.string()},
read: true,
required: ['studyset_id'],
(args) async => {
'suggestions': await _library.suggestions(
_string(args, 'studyset_id'),
),
},
);
_register(
'reply',
'Replies to a suggestion or report within a studyset.',
{
'studyset_id': Schema.string(),
'thread_id': Schema.string(),
'message': Schema.string(),
},
required: ['studyset_id', 'thread_id', 'message'],
(args) async {
await _library.reply(
_string(args, 'studyset_id'),
_string(args, 'thread_id'),
message: _string(args, 'message'),
);
return {'replied': true};
},
);
}
/// A flashcard's parts, each optional.
static final _cardParts = <String, Schema>{
'front': Schema.string(),
'back': Schema.string(),
'reading': Schema.string(description: "A vocabulary card's reading."),
'meanings': Schema.list(
description: "A vocabulary card's meanings.",
items: Schema.string(),
),
'hints': Schema.list(description: 'Up to six.', items: Schema.string()),
'explanation': Schema.string(),
};
/// Each tool's required arguments, by its name.
final _requiredOf = <String, List<String>>{};
void _register(
String name,
String description,
Map<String, Schema> properties,
Future<Map<String, Object?>> Function(Map<String, Object?> args) run, {
bool read = false,
List<String> required = const [],
}) {
_requiredOf[name] = required;
registerTool(
Tool(
name: name,
description: description,
inputSchema: Schema.object(
properties: properties,
required: required,
),
annotations: ToolAnnotations(
readOnlyHint: read,
destructiveHint: false,
openWorldHint: false,
),
),
(request) => _call(request, run, write: !read),
);
}
Future<CallToolResult> _call(
CallToolRequest request,
Future<Map<String, Object?>> Function(Map<String, Object?> args) run, {
required bool write,
}) async {
final args = request.arguments ?? const {};
String? warning;
Future<void> synced() async {
try {
await sync();
} on Object catch (error) {
warning =
'Not synced ($error): what you read may be behind, and '
'what you suggested goes with the next sync.';
}
}
try {
for (final name in _requiredOf[request.name] ?? const <String>[]) {
if (args[name] == null) {
throw AgentRefused('"$name" is required.');
}
}
await synced();
final result = await run(args);
if (write) {
await synced();
}
return CallToolResult(
content: [
TextContent(
text: jsonEncode({...result, 'warning': ?warning}),
),
],
);
} on AgentRefused catch (refused) {
return CallToolResult(
isError: true,
content: [TextContent(text: refused.message)],
);
}
}
static String _string(Map<String, Object?> args, String name) =>
switch (args[name]) {
final String value => value,
_ => throw AgentRefused('"$name" is required, as text.'),
};
static String? _optional(Map<String, Object?> args, String name) =>
switch (args[name]) {
null => null,
final String value => value,
_ => throw AgentRefused('"$name" is text.'),
};
static List<String>? _strings(Map<String, Object?> args, String name) =>
switch (args[name]) {
null => null,
final List<Object?> values when values.every((v) => v is String) => [
for (final value in values) value! as String,
],
_ => throw AgentRefused('"$name" is a list of text.'),
};
}

View file

@ -0,0 +1,75 @@
import 'dart:async';
import 'package:halkyon_core/halkyon_core.dart';
/// A sync of the agent's that failed, and why.
final class const AgentSyncFailed(
/// What the sync threw.
final Object cause,
) implements Exception {
@override
String toString() => '$cause';
}
/// One sync of the agent's database, telling [onMerge] when it merged
/// changes from elsewhere.
typedef AgentSyncOnce = Future<void> Function({
required void Function() onMerge,
});
/// The agent's sync (Halkyon's ADR 0044, D7): the `SyncRequests` its
/// gateways ask, as halkyon_app's `SyncService` is the app's, without
/// Flutter or a timer of its own: a write's request syncs after a pause
/// ([debounce]), a tool syncs at once ([syncNow]), one sync at a time.
class AgentSync(
final AgentSyncOnce _syncOnce, {
final Duration debounce = const Duration(seconds: 2),
}) implements SyncRequests {
final _merges = StreamController<void>.broadcast();
final _synced = StreamController<void>.broadcast();
Timer? _pause;
/// Why the last sync failed; null once one went through.
Object? _failure;
late final _runner = CoalescingRunner(
_once,
onError: (error, _) => _failure = error,
);
Future<void> _once() async {
_failure = null;
await _syncOnce(onMerge: () => _merges.add(null));
_synced.add(null);
}
@override
Stream<void> get merges => _merges.stream;
/// An event each time a sync went through.
Stream<void> get synced => _synced.stream;
@override
void requestSync() {
_pause?.cancel();
_pause = Timer(debounce, () => unawaited(_runner.run()));
}
/// Syncs now, any request waiting included; throws [AgentSyncFailed]
/// where the last sync failed.
Future<void> syncNow() async {
_pause?.cancel();
await _runner.run();
if (_failure case final failure?) {
throw AgentSyncFailed(failure);
}
}
/// Ends it, once the sync under way, if any, is done.
Future<void> dispose() async {
_pause?.cancel();
await _runner.idle;
await _merges.close();
await _synced.close();
}
}

View file

@ -0,0 +1,199 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:halkyon_base_client/halkyon_base_client.dart' as base;
import 'package:halkyon_content/halkyon_content.dart';
import 'package:halkyon_learn_agent/src/agent_home.dart';
import 'package:halkyon_learn_agent/src/agent_library.dart';
import 'package:halkyon_learn_agent/src/agent_sync.dart';
import 'package:halkyon_learn_client/halkyon_learn_client.dart' as protocol;
import 'package:halkyon_learn_core/core/asset/data/asset_repository.dart';
import 'package:halkyon_learn_core/core/asset/data/sync_asset_gateway.dart';
import 'package:halkyon_learn_core/core/privacy/data/content_keys.dart';
import 'package:halkyon_learn_core/core/privacy/data/privacy.dart';
import 'package:halkyon_learn_core/core/privacy/data/privacy_ledger.dart';
import 'package:halkyon_learn_core/core/privacy/data/shared_space_keys.dart';
import 'package:halkyon_learn_core/core/privacy/data/sync_content_key_gateway.dart';
import 'package:halkyon_learn_core/core/sync/space_router.dart';
import 'package:halkyon_learn_core/core/sync/sync_space_lookup.dart';
import 'package:halkyon_learn_core/feature/card/data/card_repository.dart';
import 'package:halkyon_learn_core/feature/card/data/sync_card_gateway.dart';
import 'package:halkyon_learn_core/feature/feedback/data/feedback_envelopes.dart';
import 'package:halkyon_learn_core/feature/feedback/data/feedback_repository.dart';
import 'package:halkyon_learn_core/feature/feedback/data/serverpod_feedback_gateway.dart';
import 'package:halkyon_learn_core/feature/feedback/data/sync_feedback_gateway.dart';
import 'package:halkyon_learn_core/feature/learning_path/data/learning_path_repository.dart';
import 'package:halkyon_learn_core/feature/learning_path/data/sync_learning_path_gateway.dart';
import 'package:halkyon_learn_core/feature/note/data/note_repository.dart';
import 'package:halkyon_learn_core/feature/note/data/sync_note_gateway.dart';
import 'package:halkyon_learn_core/feature/studyset/data/studyset_repository.dart';
import 'package:halkyon_learn_core/feature/studyset/data/sync_studyset_gateway.dart';
import 'package:serverpod_auth_core_client/serverpod_auth_core_client.dart';
import 'package:serverpod_offline_sync_client/offline_sync.dart';
/// The agent signed in on its instance with its data open (Halkyon's ADR
/// 0044, D7, D43, D49): its library, its sync, and what closes them.
final class const OpenAgent({
/// What its tools read and suggest through.
required final AgentLibrary library,
/// Its sync.
required final AgentSync sync,
/// Closes its data and its connection.
required final Future<void> Function() close,
});
/// Signs the agent in on [instance] with the token kept in [home], makes
/// and sets its keys on its first sign-in, and opens its data as Learn's
/// app opens a person's (`_openPersonData`): its local database, its
/// sync, its keys and those of the spaces shared with it, and the
/// repositories its library reads and suggests through.
Future<OpenAgent> openAgent(AgentHome home, Uri instance) async {
final token =
await home.token() ??
(throw const AgentHomeRefused(
'No token yet: run `halkyon-agent sign-in` with the one your owner '
'made in their Profile.',
));
final sessions = ClientAuthSessionManager(storage: _MemoryAuthStorage());
final client = protocol.Client('$instance')..authSessionManager = sessions;
final success = await client.modules.base.agentSignIn.signIn(token: token);
await sessions.updateSignedInUser(success);
final me = success.authUserId.uuid;
final keys = await _keysOf(home, client.modules.base);
final db = await client.createSyncSession(
home.database,
persistentUserId: success.authUserId,
);
final spaceLookup = SyncSpaceLookup(db, me);
final spaces = SpaceRouter(spaceLookup);
db.db.newRowSpace = (row) async => switch (await spaces.spaceOf(row)) {
final space? => protocol.UuidValue.withValidation(space),
null => null,
};
final sync = AgentSync(
({required onMerge}) => client.offlineSync.syncOnce(
db,
onInboundMerge: (space) {
spaces.forget();
onMerge();
},
),
);
final ledger = PrivacyLedger(FilePrivacyLedgerStore(home.privacy));
await ledger.open();
final contentKeys = ContentKeys(
SyncContentKeyGateway(db, sync),
SodiumContentCipher(),
() async => keys,
seen: ledger,
// An agent always has keys (D6).
registerHasKeys: () async => true,
);
final spaceKeys = SharedSpaceKeys(
SharedKeys(
ServerpodSharedKeysGateway(client.modules.base),
KeyPins(FileKeyPinStore(home.pins)),
contentKeys.cipher,
me: me,
),
contentKeys.cipher,
() async => (await spaceLookup.sharedStudysets()).keys.toSet(),
);
final privacy = Privacy(db, contentKeys)
..requestSync = sync.requestSync
..spaces = spaces
..spaceKeys = spaceKeys;
await contentKeys.refresh();
spaceKeys.keepUpOn(sync.synced);
final studysets = StudysetRepository(SyncStudysetGateway(db, sync, privacy));
final cards = CardRepository(SyncCardGateway(db, sync, me, privacy));
final notes = NoteRepository(SyncNoteGateway(db, sync, me, privacy));
final paths = LearningPathRepository(
SyncLearningPathGateway(db, sync, me, privacy),
);
final assets = AssetRepository(
SyncAssetGateway(db, sync, privacy),
ServerpodFileServerGateway(client.modules.base),
DirectoryFileCache(home.files),
privacy,
uploadTriggers: sync.synced,
);
privacy
..files = assets
..maintainOn(sync.merges);
final envelopes = PrivacyFeedbackEnvelopes(privacy, spaces, studysets);
final library = AgentLibrary(
studysets: studysets,
cards: cards,
notes: notes,
feedback: FeedbackRepository(
SyncFeedbackGateway(db, sync, spaces),
ServerpodFeedbackGateway(client, envelopes),
cards,
notes,
paths,
assets,
envelopes,
),
);
return OpenAgent(
library: library,
sync: sync,
close: () async {
await sync.dispose();
await assets.dispose();
await studysets.dispose();
await cards.dispose();
await notes.dispose();
await paths.dispose();
await db.close();
client.close();
},
);
}
/// The agent's keys: those kept in [home], else new ones, kept before
/// their public halves are set on the register, once (D6). Keys kept whose
/// public halves the register already has stay as they are.
Future<UnlockedAccountKeys> _keysOf(
AgentHome home,
base.Caller agents,
) async {
final kept = await home.keys();
final keys = kept ?? await newAccountKeys();
if (kept == null) {
await home.keepKeys(keys);
}
if (!await home.keysSet()) {
try {
await agents.agents.setKeys(
encryption: ByteData.sublistView(keys.encryptionPublicKey),
signing: ByteData.sublistView(keys.signingPublicKey),
);
} on base.AgentRefusedException catch (refused) {
// Set by an earlier run that stopped before it noted so; keys made
// anew now aren't those, and the agent can't take part.
if (refused.reason != base.AgentRefusal.keysSet || kept == null) {
rethrow;
}
}
await home.noteKeysSet();
}
return keys;
}
/// Keeps the agent's session in memory: it signs in with its token at
/// every start, for a day's session (D43).
final class _MemoryAuthStorage() implements ClientAuthSuccessStorage {
AuthSuccess? _session;
@override
Future<AuthSuccess?> get() async => _session;
@override
Future<void> set(AuthSuccess? data) async => _session = data;
}

View file

@ -0,0 +1,39 @@
name: halkyon_learn_agent
description: >-
Halkyon Learn's agent (Halkyon's ADR 0044, D6, D7, D49 to D52): signs in to
an instance with its token, syncs the shared studysets it is a member of,
opens them with its own keys and suggests changes to them, for Claude Code
or another MCP client, over stdio.
version: 0.1.0
publish_to: none
resolution: workspace
environment:
sdk: ^3.13.0
executables:
halkyon-agent: halkyon_agent
dependencies:
args: ^2.7.0
# The Model Context Protocol, the Dart team's own (D51).
dart_mcp: ^0.5.2
halkyon_base_client:
path: ../../../packages/halkyon_base_client
halkyon_content:
path: ../../../packages/halkyon_content
halkyon_core:
path: ../../../packages/halkyon_core
halkyon_learn_client:
path: ../halkyon_learn_client
# Learn's content, as the app reads and writes it (D41, D49).
halkyon_learn_core:
path: ../halkyon_learn_core
path: ^1.9.1
serverpod_auth_core_client: 4.0.4
serverpod_offline_sync_client: 0.0.10
dev_dependencies:
# The tests' channel to the MCP server, in memory.
stream_channel: ^2.1.4
test: ^1.31.1

View file

@ -0,0 +1,107 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:halkyon_content/halkyon_content.dart';
import 'package:halkyon_learn_agent/src/agent_home.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';
/// Where the agent keeps its token, keys and data (Halkyon's ADR 0044,
/// D50): a folder per instance only its user may enter, files only it may
/// read, and nothing read that others could have read or changed.
void main() {
late Directory root;
setUp(() async {
root = await Directory.systemTemp.createTemp('agent_home');
addTearDown(() => root.delete(recursive: true));
});
int modeOf(String path) => FileStat.statSync(path).mode & 0x1ff;
test(
'each instance has a folder of its own, its user alone entering it',
() async {
final learn = await AgentHome.open(
root,
Uri.parse('https://learn.halkyon.eu/'),
);
final local = await AgentHome.open(
root,
Uri.parse('http://localhost:8080'),
);
expect(p.basename(learn.folder.path), 'learn.halkyon.eu');
expect(p.basename(local.folder.path), 'localhost_8080');
expect(modeOf(learn.folder.path), 0x1c0); // 0700
},
);
test('the token is kept for its user alone, and read back', () async {
final home = await AgentHome.open(root, Uri.parse('https://halkyon.li'));
expect(await home.token(), isNull);
await home.keepToken('hlk_agent_secret\n');
expect(await home.token(), 'hlk_agent_secret');
expect(modeOf(p.join(home.folder.path, 'token')), 0x180); // 0600
});
test(
"a token, keys or folder others may read or change isn't read",
() async {
final home = await AgentHome.open(root, Uri.parse('https://halkyon.li'));
await home.keepToken('secret');
await Process.run('chmod', ['644', p.join(home.folder.path, 'token')]);
await expectLater(home.token(), throwsA(isA<AgentHomeRefused>()));
await Process.run('chmod', ['600', p.join(home.folder.path, 'token')]);
await Process.run('chmod', ['755', home.folder.path]);
await expectLater(
AgentHome.open(root, Uri.parse('https://halkyon.li')),
throwsA(isA<AgentHomeRefused>()),
);
},
);
test(
'the keys are kept for its user alone, and read back as they were',
() async {
final home = await AgentHome.open(root, Uri.parse('https://halkyon.li'));
expect(await home.keys(), isNull);
final keys = UnlockedAccountKeys(
encryptionPublicKey: Uint8List.fromList(List.filled(32, 1)),
encryptionSecretKey: Uint8List.fromList(List.filled(32, 2)),
signingPublicKey: Uint8List.fromList(List.filled(32, 3)),
signingSecretKey: Uint8List.fromList(List.filled(64, 4)),
);
await home.keepKeys(keys);
expect(await home.keys(), keys);
expect(modeOf(p.join(home.folder.path, 'keys.json')), 0x180);
},
);
test('notes once the register holds its public keys', () async {
final home = await AgentHome.open(root, Uri.parse('https://halkyon.li'));
expect(await home.keysSet(), isFalse);
await home.noteKeysSet();
expect(await home.keysSet(), isTrue);
});
test('an instance is reached over HTTPS, or plain HTTP on this machine '
'alone', () async {
await expectLater(
AgentHome.open(root, Uri.parse('http://halkyon.li')),
throwsA(isA<AgentHomeRefused>()),
);
await expectLater(
AgentHome.open(root, Uri.parse('ftp://halkyon.li')),
throwsA(isA<AgentHomeRefused>()),
);
});
}

View file

@ -0,0 +1,328 @@
import 'package:halkyon_content/rich_text.dart';
import 'package:halkyon_content/testing.dart';
import 'package:halkyon_learn_agent/src/agent_library.dart';
import 'package:halkyon_learn_core/core/asset/data/asset_repository.dart';
import 'package:halkyon_learn_core/core/profile/public_person.dart';
import 'package:halkyon_learn_core/feature/card/data/card_repository.dart';
import 'package:halkyon_learn_core/feature/card/model/card_content.dart';
import 'package:halkyon_learn_core/feature/feedback/data/feedback_repository.dart';
import 'package:halkyon_learn_core/feature/feedback/model/feedback.dart';
import 'package:halkyon_learn_core/feature/learning_path/data/learning_path_repository.dart';
import 'package:halkyon_learn_core/feature/note/data/note_repository.dart';
import 'package:halkyon_learn_core/feature/note/model/note_content.dart';
import 'package:halkyon_learn_core/feature/studyset/data/studyset_payload.dart';
import 'package:halkyon_learn_core/feature/studyset/data/studyset_repository.dart';
import 'package:halkyon_learn_core/feature/studyset/model/studyset_content.dart';
import 'package:halkyon_learn_core/testing.dart';
import 'package:test/test.dart';
/// What the agent reads and suggests (Halkyon's ADR 0044, D7, D10, D51):
/// the studysets shared with it alone, their cards and notes as text, and
/// every change as a suggestion in the studyset's space, never a write.
void main() {
late FakeStudysetGateway studysetGateway;
late FakeCardGateway cardGateway;
late FakeNoteGateway noteGateway;
late FakeFeedbackWriteGateway written;
late FakeFeedbackServerGateway server;
late CardRepository cards;
late NoteRepository notes;
late AgentLibrary library;
late String cardId;
late String noteId;
setUp(() async {
studysetGateway = FakeStudysetGateway()
..receiveRemoteChange(
'japanese',
encodeStudysetPayload(StudysetContent.titled('Japanese')),
)
..receiveRemoteChange(
'kanji',
encodeStudysetPayload(StudysetContent.titled('Kanji')),
parentId: 'japanese',
)
..receiveRemoteChange(
'diary',
encodeStudysetPayload(StudysetContent.titled('Diary')),
)
..shared['japanese'] = (space: 'space-1', viewOnly: true)
..shared['kanji'] = (space: 'space-1', viewOnly: true);
cardGateway = FakeCardGateway();
noteGateway = FakeNoteGateway();
written = FakeFeedbackWriteGateway();
server = FakeFeedbackServerGateway();
final studysets = StudysetRepository(studysetGateway);
cards = CardRepository(cardGateway);
notes = NoteRepository(noteGateway);
final assets = AssetRepository(
FakeAssetGateway(),
FakeFileServerGateway(),
MemoryFileCache(),
FakeAssetSealing(),
);
addTearDown(() async {
await studysets.dispose();
await cards.dispose();
await notes.dispose();
await assets.dispose();
});
cardId = await cards.create(
'japanese',
CardContent(
front: RichContent.plain('猫'),
back: RichContent.plain('dog'),
),
);
await cards.create(
'diary',
CardContent(
front: RichContent.plain('Secret'),
back: RichContent.plain('Mine'),
),
);
noteId = (await notes.create(
'kanji',
NoteContent(title: 'Radicals', body: RichContent.plain('氵 is water.')),
)).noteId;
library = AgentLibrary(
studysets: studysets,
cards: cards,
notes: notes,
feedback: FeedbackRepository(
written,
server,
cards,
notes,
LearningPathRepository(FakeLearningPathGateway()),
assets,
FakeFeedbackEnvelopes(
spaces: {'japanese': 'space-1', 'kanji': 'space-1'},
),
),
);
});
test('lists the studysets shared with it, never one of its own '
'space', () async {
final listed = await library.sharedStudysets();
expect([for (final s in listed) s['id']], ['japanese', 'kanji']);
expect(listed.first, {
'id': 'japanese',
'title': 'Japanese',
'parent': null,
'role': 'viewer',
'cards': 1,
'notes': 0,
});
expect(listed.last['parent'], 'japanese');
});
test("reads a studyset's cards and notes as text; one not shared with it "
"isn't there", () async {
final japanese = await library.studyset('japanese');
expect(japanese['cards'], [
{'id': cardId, 'type': 'frontBack', 'front': '猫', 'back': 'dog'},
]);
expect(japanese['topics'], ['kanji']);
final kanji = await library.studyset('kanji');
expect(kanji['notes'], [
{'id': noteId, 'title': 'Radicals', 'body': '氵 is water.'},
]);
await expectLater(
library.studyset('diary'),
throwsA(isA<AgentRefused>()),
);
await expectLater(
library.studyset('nothing'),
throwsA(isA<AgentRefused>()),
);
});
test('searches the shared cards alone', () async {
expect(
[for (final card in await library.search('猫')) card['id']],
[cardId],
);
expect(await library.search('secret'), isEmpty);
});
test("a change to a card is suggested in its studyset's space, the card "
'unchanged', () async {
await library.suggestCardChange(
cardId,
back: 'cat',
message: '猫 is a cat.',
);
final thread = written.threads.single;
expect(thread.space, 'space-1');
expect(thread.json['target'], {
'kind': 'card',
'item': cardId,
'version': 0,
});
expect(thread.json['body'], '猫 is a cat.');
final proposed = thread.json['proposed']! as Map<String, Object?>;
expect(
RichContent.fromJson(proposed['back']! as Map<String, Object?>).plainText,
'cat',
);
expect((await cards.byId(cardId))!.content.back.plainText, 'dog');
});
test('new cards and notes are suggested for a shared studyset, nothing '
'added', () async {
await library.suggestNewCard(
'kanji',
front: '水',
back: 'water',
message: '',
);
await library.suggestNewNote(
'japanese',
title: 'Particles',
body: 'は marks the topic.\nが the subject.',
message: 'A start.',
);
await library.suggestNoteChange(
noteId,
title: 'Radicals (部首)',
message: '',
);
expect(
[for (final t in written.threads) t.json['target']],
[
{'kind': 'newCard', 'item': 'kanji', 'version': 0},
{'kind': 'newNote', 'item': 'japanese', 'version': 0},
{'kind': 'note', 'item': noteId, 'version': 0},
],
);
expect(await cards.cardsOf('kanji'), isEmpty);
expect(await notes.notesOf('japanese'), isEmpty);
});
test(
'a vocabulary card is suggested with its reading and meanings',
() async {
await library.suggestNewCard(
'japanese',
type: 'vocabulary',
front: '犬',
reading: 'いぬ',
meanings: ['dog'],
message: '',
);
final proposed =
written.threads.single.json['proposed']! as Map<String, Object?>;
expect(proposed['type'], 'vocabulary');
expect(proposed['reading'], 'いぬ');
expect(proposed['meanings'], ['dog']);
},
);
test('nothing is suggested in a studyset not shared with it, on an item '
"it can't find, or of a kind it can't write", () async {
await expectLater(
library.suggestNewCard('diary', front: 'x', back: 'y', message: ''),
throwsA(isA<AgentRefused>()),
);
await expectLater(
library.suggestCardChange('nothing', back: 'y', message: ''),
throwsA(isA<AgentRefused>()),
);
final mine = (await cards.cardsOf('diary')).single.id;
await expectLater(
library.suggestCardChange(mine, back: 'y', message: ''),
throwsA(isA<AgentRefused>()),
);
await expectLater(
library.suggestNewCard(
'japanese',
type: 'matching',
front: 'x',
message: '',
),
throwsA(isA<AgentRefused>()),
);
await expectLater(
library.report('card', mine, message: 'Delete it.'),
throwsA(isA<AgentRefused>()),
);
expect(written.threads, isEmpty);
});
test('a report asks for something shared to go, saying why', () async {
await library.report('note', noteId, message: 'A duplicate.');
await expectLater(
library.report('card', cardId, message: ' '),
throwsA(isA<AgentRefused>()),
);
final thread = written.threads.single;
expect(thread.kind, FeedbackKind.report);
expect(thread.json['target'], {
'kind': 'note',
'item': noteId,
'version': 0,
});
expect(thread.json['body'], 'A duplicate.');
});
test("a studyset's suggestions are listed with their replies, and "
'replied to', () async {
server.gathered = [
FeedbackThread(
threadId: 'thread-1',
publicId: 'space-1',
studysetTitle: '',
location: '',
kind: FeedbackKind.suggestion,
writer: const PublicPerson(handle: 'claude'),
target: FeedbackTarget(
kind: FeedbackTargetKind.card,
item: cardId,
version: 0,
),
createdAt: DateTime.utc(2026, 11, 11),
body: '猫 is a cat.',
status: FeedbackStatus.declined,
messages: [
FeedbackMessage(
id: 'm-1',
by: const PublicPerson(handle: 'alice'),
fromAuthor: true,
body: 'It is a pun.',
createdAt: DateTime.utc(2026, 11, 11, 1),
),
],
space: 'space-1',
studysetId: 'japanese',
),
];
final listed = await library.suggestions('japanese');
expect(listed.single, {
'id': 'thread-1',
'kind': 'suggestion',
'target': {'kind': 'card', 'item': cardId},
'by': '@claude',
'status': 'declined',
'message': '猫 is a cat.',
'replies': [
{'by': '@alice', 'message': 'It is a pun.'},
],
});
await library.reply('japanese', 'thread-1', message: 'Thanks!');
expect(written.messages.single.json['body'], 'Thanks!');
await expectLater(
library.reply('japanese', 'thread-9', message: 'Hm?'),
throwsA(isA<AgentRefused>()),
);
});
}

View file

@ -0,0 +1,184 @@
import 'dart:async';
import 'dart:convert';
import 'package:dart_mcp/client.dart';
import 'package:halkyon_content/rich_text.dart';
import 'package:halkyon_content/testing.dart';
import 'package:halkyon_learn_agent/src/agent_library.dart';
import 'package:halkyon_learn_agent/src/agent_server.dart';
import 'package:halkyon_learn_core/core/asset/data/asset_repository.dart';
import 'package:halkyon_learn_core/feature/card/data/card_repository.dart';
import 'package:halkyon_learn_core/feature/card/model/card_content.dart';
import 'package:halkyon_learn_core/feature/feedback/data/feedback_repository.dart';
import 'package:halkyon_learn_core/feature/learning_path/data/learning_path_repository.dart';
import 'package:halkyon_learn_core/feature/note/data/note_repository.dart';
import 'package:halkyon_learn_core/feature/studyset/data/studyset_payload.dart';
import 'package:halkyon_learn_core/feature/studyset/data/studyset_repository.dart';
import 'package:halkyon_learn_core/feature/studyset/model/studyset_content.dart';
import 'package:halkyon_learn_core/testing.dart';
import 'package:stream_channel/stream_channel.dart';
import 'package:test/test.dart';
/// The agent as Claude Code meets it (Halkyon's ADR 0044, D51): an MCP
/// server whose tools read the studysets shared with it and suggest, each
/// read after a sync and each suggestion synced at once, a refusal told to
/// the model as the tool's error.
void main() {
late FakeFeedbackWriteGateway written;
late ServerConnection server;
late List<String> syncs;
Exception? syncFails;
late String cardId;
setUp(() async {
final studysetGateway = FakeStudysetGateway()
..receiveRemoteChange(
'japanese',
encodeStudysetPayload(StudysetContent.titled('Japanese')),
)
..shared['japanese'] = (space: 'space-1', viewOnly: true);
written = FakeFeedbackWriteGateway();
final studysets = StudysetRepository(studysetGateway);
final cards = CardRepository(FakeCardGateway());
final notes = NoteRepository(FakeNoteGateway());
final assets = AssetRepository(
FakeAssetGateway(),
FakeFileServerGateway(),
MemoryFileCache(),
FakeAssetSealing(),
);
cardId = await cards.create(
'japanese',
CardContent(
front: RichContent.plain('猫'),
back: RichContent.plain('dog'),
),
);
syncs = [];
syncFails = null;
final library = AgentLibrary(
studysets: studysets,
cards: cards,
notes: notes,
feedback: FeedbackRepository(
written,
FakeFeedbackServerGateway(),
cards,
notes,
LearningPathRepository(FakeLearningPathGateway()),
assets,
FakeFeedbackEnvelopes(spaces: {'japanese': 'space-1'}),
),
);
final toServer = StreamController<String>();
final toClient = StreamController<String>();
final agent = AgentServer(
StreamChannel<String>.withCloseGuarantee(
toServer.stream,
toClient.sink,
),
library,
sync: () async {
syncs.add('sync');
if (syncFails case final error?) {
throw error;
}
},
);
final client = MCPClient(Implementation(name: 'test', version: '0'));
server = client.connectServer(
StreamChannel<String>.withCloseGuarantee(toClient.stream, toServer.sink),
);
final initialized = await server.initialize(
InitializeRequest(
protocolVersion: ProtocolVersion.latestSupported,
capabilities: client.capabilities,
clientInfo: client.implementation,
),
);
expect(initialized.instructions, contains('suggest'));
server.notifyInitialized(InitializedNotification());
await agent.initialized;
addTearDown(() async {
await client.shutdown();
await agent.shutdown();
await studysets.dispose();
await cards.dispose();
await notes.dispose();
await assets.dispose();
});
});
Future<CallToolResult> call(String tool, Map<String, Object?> arguments) =>
server.callTool(CallToolRequest(name: tool, arguments: arguments));
Object? jsonOf(CallToolResult result) =>
jsonDecode((result.content.single as TextContent).text);
test('offers its tools, every one reading or suggesting', () async {
expect(
[for (final tool in (await server.listTools()).tools) tool.name],
unorderedEquals([
'list_studysets',
'read_studyset',
'search_cards',
'suggest_card_change',
'suggest_new_card',
'suggest_note_change',
'suggest_new_note',
'report',
'list_suggestions',
'reply',
]),
);
});
test('reads after a sync, as JSON', () async {
final result = await call('read_studyset', {'studyset_id': 'japanese'});
expect(result.isError, isNot(isTrue));
expect(syncs, ['sync']);
expect((jsonOf(result)! as Map)['cards'], [
{'id': cardId, 'type': 'frontBack', 'front': '猫', 'back': 'dog'},
]);
});
test('a suggestion goes and is synced at once', () async {
final result = await call('suggest_card_change', {
'card_id': cardId,
'back': 'cat',
'message': '猫 is a cat.',
});
expect(result.isError, isNot(isTrue));
expect(written.threads.single.json['body'], '猫 is a cat.');
// Before, to find the card; after, to send it.
expect(syncs, ['sync', 'sync']);
});
test('a refusal, or an argument missing, is an error the model reads, '
'and nothing is written', () async {
final refused = await call('read_studyset', {'studyset_id': 'diary'});
expect(refused.isError, isTrue);
expect(
(refused.content.single as TextContent).text,
contains('No studyset diary'),
);
final missing = await call('suggest_new_note', {'studyset_id': 'japanese'});
expect(missing.isError, isTrue);
expect(written.threads, isEmpty);
});
test('a sync that fails leaves what is held to read, and says so', () async {
syncFails = Exception('offline');
final result = await call('list_studysets', {});
expect(result.isError, isNot(isTrue));
final json = jsonOf(result)! as Map;
expect(json['studysets'], hasLength(1));
expect(json['warning'], contains('Not synced'));
});
}

View file

@ -0,0 +1,60 @@
import 'dart:async';
import 'package:halkyon_learn_agent/src/agent_sync.dart';
import 'package:test/test.dart';
/// The agent's sync (Halkyon's ADR 0044, D7), the `SyncRequests` its
/// gateways ask: a burst of requests syncs once after a pause, a tool's
/// sync runs at once and says whether it went, and what a sync merged is
/// heard.
void main() {
late List<String> runs;
late Exception? fails;
late AgentSync sync;
setUp(() {
runs = [];
fails = null;
sync = AgentSync(({required onMerge}) async {
runs.add('sync');
if (fails case final error?) {
throw error;
}
onMerge();
}, debounce: const Duration(milliseconds: 50));
addTearDown(sync.dispose);
});
test('requests in a burst sync once, after the pause', () async {
sync
..requestSync()
..requestSync()
..requestSync();
expect(runs, isEmpty);
await Future<void>.delayed(const Duration(milliseconds: 150));
expect(runs, ['sync']);
});
test('a sync now runs at once, and what it merged is heard', () async {
final merged = sync.merges.first;
final synced = sync.synced.first;
await sync.syncNow();
expect(runs, ['sync']);
await merged;
await synced;
});
test('a sync now that fails says so; the next that goes through '
"doesn't", () async {
fails = Exception('offline');
await expectLater(sync.syncNow(), throwsA(isA<Exception>()));
fails = null;
await sync.syncNow();
expect(runs, ['sync', 'sync']);
});
}

View file

@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Builds Halkyon Learn's agent on this machine and copies it to its user on
# the host it runs on (Halkyon's ADR 0044, D52), which has no Dart SDK:
#
# apps/learn/halkyon_learn_agent/tool/install.sh <ssh target>
#
# e.g. `claude@halkyon-li-host`. Each build goes into a folder of its own,
# ~/.local/lib/halkyon-agent/<commit>, `current` pointing to it and
# ~/.local/bin/halkyon-agent to its executable, so an agent still running
# keeps its files; the build before stays, the older ones go.
set -euo pipefail
target=${1:?"usage: $0 <ssh target>"}
package=$(cd "$(dirname "$0")/.." && pwd)
# `dart build cli` builds for this machine alone.
remote_arch=$(ssh "$target" uname -m)
if [[ $remote_arch != "$(uname -m)" ]]; then
echo "The host is $remote_arch, this machine $(uname -m): build on one like it." >&2
exit 1
fi
version=$(git -C "$package" rev-parse --short=12 HEAD)
if [[ -n $(git -C "$package" status --porcelain -- . ../halkyon_learn_core ../../../packages) ]]; then
version="$version-dirty-$(date +%Y%m%d%H%M%S)"
fi
build=$(mktemp -d)
trap 'rm -rf "$build"' EXIT
(cd "$package" && dart build cli -o "$build")
# tar rather than rsync, which the host may lack; for its user alone.
tar -C "$build/bundle" -cz . | ssh "$target" "
set -eu
umask 077
lib=\$HOME/.local/lib/halkyon-agent
mkdir -p \"\$lib/$version\" \"\$HOME/.local/bin\"
tar -C \"\$lib/$version\" -xz
previous=\$(readlink \"\$lib/current\" || true)
ln -sfn '$version' \"\$lib/current\"
ln -sfn \"\$lib/current/bin/halkyon_agent\" \"\$HOME/.local/bin/halkyon-agent\"
for old in \"\$lib\"/*/; do
old=\$(basename \"\$old\")
# current/ is a link to a build, never one itself.
if [ ! -L \"\$lib/\$old\" ] && [ \"\$old\" != '$version' ] && [ \"\$old\" != \"\$previous\" ]; then
rm -rf \"\$lib/\$old\"
fi
done
\"\$HOME/.local/bin/halkyon-agent\" --help > /dev/null
"
echo "Installed $version on $target: ~/.local/bin/halkyon-agent." >&2

View file

@ -8,13 +8,14 @@ both read and write, so the privacy rules and the payloads live in one place.
`SyncSpaceLookup`, positions), people's files (`asset/`), `LatestValue` and `watchReads`
(`async/`), citations and public people.
- `feature/`: the models, payload codecs, gateways (the synced ones included) and repositories
of studysets, cards, notes, tags and feedback, and what they take of learning paths and study
of studysets, cards, notes, tags, feedback and learning paths, and what they take of study
options.
- `testing.dart`: the fakes of its gateways, for the app's tests and the agent's.
The synced gateways take halkyon_core's `SyncRequests`, which halkyon_app's `SyncService` and
the agent's own sync implement. What only the app shows (progress, exam coverage, deletions'
waits, the card browser, a subject's icon and name) stays in the app, `halkyon_learn_flutter`.
Paths' sync, PDFs, reviews and settings move here when the agent needs them.
PDFs, reviews and settings move here when the agent needs them.
Its tests are still the app's (`halkyon_learn_flutter/test/`), on the fakes there. Licensed under
Its tests are still the app's (`halkyon_learn_flutter/test/`), on the fakes of `testing.dart`. Licensed under
the AGPL-3.0.

View file

@ -0,0 +1,133 @@
import 'dart:typed_data';
import 'package:halkyon_content/halkyon_content.dart';
import 'package:halkyon_core/halkyon_core.dart';
import 'package:halkyon_learn_client/halkyon_learn_client.dart' as protocol;
import 'package:halkyon_learn_core/core/asset/data/asset_gateway.dart';
import 'package:halkyon_learn_core/core/content/payload.dart';
import 'package:halkyon_learn_core/core/privacy/data/privacy.dart';
import 'package:serverpod_offline_sync_client/offline_sync.dart';
/// [AssetGateway] on the person's local database, which the sync engine keeps
/// in step with their other devices. A file of a private studyset has its
/// row's payload sealed with its tree's key ([Privacy], ADR 0019).
class SyncAssetGateway(
final OfflineSyncDatabaseSession _db,
final SyncRequests _sync,
final Privacy _privacy,
) implements AssetGateway {
@override
Future<AssetRow?> byId(String id) async {
final protocol.UuidValue uuid;
try {
uuid = protocol.UuidValue.withValidation(id);
} on FormatException {
// Content can name anything; a name that is no id names no row.
return null;
}
await _privacy.keys.refresh();
return _row(await protocol.Asset.db.findById(_db, uuid));
}
@override
Future<AssetRow?> bySha256(String sha256) async {
await _privacy.keys.refresh();
return _row(
await protocol.Asset.db.findFirstRow(
_db,
where: (t) => t.sha256.equals(sha256),
),
);
}
@override
Future<List<AssetRow>> all() async {
await _privacy.keys.refresh();
return [
for (final asset in await protocol.Asset.db.find(_db)) ?_row(asset),
];
}
@override
String newId() => Privacy.newId().uuid;
@override
Future<String> insert({
required String id,
required String sha256,
required String mimeType,
required int byteSize,
required ByteData payload,
String? keyId,
}) async {
final sealed = _privacy.seal(
payload,
keyId: keyId,
table: 'asset',
bound: '',
id: id,
item: 'asset:$id',
);
final asset = await protocol.Asset.db.insertRow(
_db,
protocol.Asset(
id: protocol.UuidValue.withValidation(id),
sha256: sha256,
mimeType: mimeType,
byteSize: byteSize,
keyId: sealed.keyId,
nonce: sealed.nonce,
payload: sealed.payload,
),
);
_sync.requestSync();
return asset.id!.uuid;
}
@override
Future<void> delete(String id) async {
final uuid = protocol.UuidValue.withValidation(id);
if (await protocol.Asset.db.findById(_db, uuid) case final asset?) {
// The name it came with is content (ADR 0002, rule 2).
await protocol.Asset.db.updateRow(
_db,
asset.copyWith(payload: redactedPayload),
columns: (t) => [t.payload],
);
await protocol.Asset.db.deleteWhere(
_db,
where: (t) => t.id.equals(uuid),
);
_sync.requestSync();
}
}
AssetRow? _row(protocol.Asset? asset) {
if (asset == null) {
return null;
}
// A file this device saw sealed never counts as readable again (the
// reading of 22 Oct): a readable row in its place nobody signed is
// locked.
final opened = _privacy.openItem(
(keyId: asset.keyId, nonce: asset.nonce, payload: asset.payload),
table: 'asset',
bound: '',
id: asset.id!.uuid,
item: 'asset:${asset.id!.uuid}',
treeKey: null,
);
return (
id: asset.id!.uuid,
sha256: asset.sha256,
mimeType: asset.mimeType,
byteSize: asset.byteSize,
payload: switch (opened) {
Readable(:final payload) => payload,
Locked() => redactedPayload,
},
keyId: asset.keyId,
locked: opened is Locked,
);
}
}

View file

@ -0,0 +1,387 @@
import 'dart:typed_data';
import 'package:halkyon_content/halkyon_content.dart';
import 'package:halkyon_core/halkyon_core.dart';
import 'package:halkyon_learn_client/halkyon_learn_client.dart' as protocol;
import 'package:halkyon_learn_core/core/content/payload.dart';
import 'package:halkyon_learn_core/core/privacy/data/privacy.dart';
import 'package:halkyon_learn_core/feature/learning_path/data/learning_path_gateway.dart';
import 'package:serverpod_offline_sync_client/offline_sync.dart';
/// [LearningPathGateway] on the person's local database, which the sync
/// engine keeps in step with their other devices. Step revisions record
/// [_authorId] as their author. In a private studyset, paths and step
/// revisions are sealed with their tree's key ([Privacy], ADR 0019); one
/// that doesn't open here reads as blank.
class SyncLearningPathGateway(
final OfflineSyncDatabaseSession _db,
final SyncRequests _sync,
final String _authorId,
final Privacy _privacy,
) implements LearningPathGateway {
@override
Future<List<PathRow>> paths({String? studysetId}) async {
await _privacy.keys.refresh();
final treeKey = await _privacy.treeKeys();
return [
for (final path in await protocol.LearningPath.db.find(
_db,
where: studysetId == null
? null
: (t) => t.studysetId.equals(_uuid(studysetId)),
))
(
id: path.id!.uuid,
studysetId: path.studysetId.uuid,
position: path.position,
payload: _opened(
'learning_path',
path.id!.uuid,
(keyId: path.keyId, nonce: path.nonce, payload: path.payload),
bound: 'studyset:${path.studysetId.uuid}',
item: 'path:${path.id!.uuid}',
treeKey: treeKey(path.studysetId.uuid),
),
),
];
}
/// [envelope]'s payload opened as [item]'s, [bound] to the row it
/// belongs to, in a tree with [treeKey]; blank where it doesn't open here,
/// or isn't trusted there.
ByteData _opened(
String table,
String id,
Envelope envelope, {
required String bound,
required String item,
required String? treeKey,
}) => switch (_privacy.openItem(
envelope,
table: table,
id: id,
bound: bound,
item: item,
treeKey: treeKey,
)) {
Readable(:final payload) => payload,
Locked() => redactedPayload,
};
@override
Future<String> insertPath({
required String studysetId,
required String position,
required ByteData payload,
}) async {
final id = Privacy.newId();
final sealed = _privacy.seal(
payload,
keyId: await _privacy.keyToWriteIn(studysetId),
table: 'learning_path',
id: id.uuid,
bound: 'studyset:$studysetId',
item: 'path:${id.uuid}',
);
final path = await protocol.LearningPath.db.insertRow(
_db,
protocol.LearningPath(
id: id,
studysetId: _uuid(studysetId),
position: position,
keyId: sealed.keyId,
nonce: sealed.nonce,
payload: sealed.payload,
),
);
_sync.requestSync();
return path.id!.uuid;
}
@override
Future<void> updatePathPayload(String id, ByteData payload) async {
if (await protocol.LearningPath.db.findById(_db, _uuid(id))
case final path?) {
final sealed = _privacy.seal(
payload,
keyId: await _privacy.keyOfPath(id),
table: 'learning_path',
id: id,
bound: 'studyset:${path.studysetId.uuid}',
item: 'path:$id',
);
// Only the named columns change (ADR 0001, rule 1).
await protocol.LearningPath.db.updateRow(
_db,
path.copyWith(
keyId: sealed.keyId,
nonce: sealed.nonce,
payload: sealed.payload,
),
columns: (t) => [t.keyId, t.nonce, t.payload],
);
_sync.requestSync();
}
}
@override
Future<void> updatePathPosition(String id, String position) async {
if (await protocol.LearningPath.db.findById(_db, _uuid(id))
case final path?) {
await protocol.LearningPath.db.updateRow(
_db,
path.copyWith(position: position),
columns: (t) => [t.position],
);
_sync.requestSync();
}
}
@override
Future<void> deletePath(String id) async {
await protocol.LearningPathTag.db.deleteWhere(
_db,
where: (t) => t.pathId.equals(_uuid(id)),
);
await protocol.LearningPath.db.deleteWhere(
_db,
where: (t) => t.id.equals(_uuid(id)),
);
_sync.requestSync();
}
@override
Future<List<StepRow>> steps(Set<String> pathIds) async {
if (pathIds.isEmpty) {
return const [];
}
return [
for (final step in await protocol.LearningPathStep.db.find(
_db,
where: (t) => t.pathId.inSet({for (final id in pathIds) _uuid(id)}),
))
(
id: step.id!.uuid,
pathId: step.pathId.uuid,
position: step.position,
kind: step.kind,
),
];
}
@override
Future<List<StepRevisionRow>> revisions(Set<String> stepIds) async {
if (stepIds.isEmpty) {
return const [];
}
await _privacy.keys.refresh();
final ids = {for (final id in stepIds) _uuid(id)};
final treeKey = await _privacy.treeKeys();
final pathOf = {
for (final step in await protocol.LearningPathStep.db.find(
_db,
where: (t) => t.id.inSet(ids),
))
step.id!.uuid: step.pathId,
};
final studysetOf = pathOf.isEmpty
? const <String, String>{}
: {
for (final path in await protocol.LearningPath.db.find(
_db,
where: (t) => t.id.inSet(<protocol.UuidValue>{...pathOf.values}),
))
path.id!.uuid: path.studysetId.uuid,
};
String? treeKeyOf(String stepId) =>
switch (studysetOf[pathOf[stepId]?.uuid]) {
final studyset? => treeKey(studyset),
null => null,
};
return [
for (final revision in await protocol.LearningPathStepRevision.db.find(
_db,
where: (t) => t.stepId.inSet(ids),
))
(
id: revision.id!.uuid,
stepId: revision.stepId.uuid,
parents: {for (final parent in revision.parents) parent.uuid},
payload: _opened(
'learning_path_step_revision',
revision.id!.uuid,
(
keyId: revision.keyId,
nonce: revision.nonce,
payload: revision.payload,
),
bound: 'step:${revision.stepId.uuid}',
item: 'step:${revision.stepId.uuid}',
treeKey: treeKeyOf(revision.stepId.uuid),
),
),
];
}
@override
Future<({String stepId, String revisionId})> insertStep({
required String pathId,
required String position,
required String kind,
required ByteData payload,
}) async {
// Refused before anything is written where this device may write
// nothing (the final reading of 22 Oct).
await _privacy.keyOfPath(pathId);
final step = await protocol.LearningPathStep.db.insertRow(
_db,
protocol.LearningPathStep(
pathId: _uuid(pathId),
position: position,
kind: kind,
),
);
final revisionId = await insertRevision(
stepId: step.id!.uuid,
parents: const {},
payload: payload,
);
return (stepId: step.id!.uuid, revisionId: revisionId);
}
@override
Future<List<String>> insertSteps(
String pathId,
List<NewStepRow> steps,
) async {
if (steps.isEmpty) {
return const [];
}
final keyId = await _privacy.keyOfPath(pathId);
final rows = await protocol.LearningPathStep.db.insert(_db, [
for (final step in steps)
protocol.LearningPathStep(
pathId: _uuid(pathId),
position: step.position,
kind: step.kind,
),
]);
// The batch's positions are distinct, so they tell the stored rows apart
// whatever order they come back in.
final idOf = {for (final row in rows) row.position: row.id!};
await protocol.LearningPathStepRevision.db.insert(_db, [
for (final step in steps)
_newRevision(idOf[step.position]!, const [], step.payload, keyId),
]);
_sync.requestSync();
return [for (final step in steps) idOf[step.position]!.uuid];
}
@override
Future<String> insertRevision({
required String stepId,
required Set<String> parents,
required ByteData payload,
}) async {
final revision = await protocol.LearningPathStepRevision.db.insertRow(
_db,
_newRevision(
_uuid(stepId),
parents,
payload,
await _privacy.keyOfStep(stepId),
),
);
_sync.requestSync();
return revision.id!.uuid;
}
/// A new revision of [stepId] with [payload], sealed with [keyId].
protocol.LearningPathStepRevision _newRevision(
protocol.UuidValue stepId,
Iterable<String> parents,
ByteData payload,
String? keyId,
) {
final id = Privacy.newId();
final sealed = _privacy.seal(
payload,
keyId: keyId,
table: 'learning_path_step_revision',
id: id.uuid,
bound: 'step:${stepId.uuid}',
item: 'step:${stepId.uuid}',
);
return protocol.LearningPathStepRevision(
id: id,
stepId: stepId,
parents: [for (final parent in parents) _uuid(parent)],
authorId: _uuid(_authorId),
keyId: sealed.keyId,
nonce: sealed.nonce,
payload: sealed.payload,
);
}
@override
Future<void> updateStepPosition(String id, String position) async {
if (await protocol.LearningPathStep.db.findById(_db, _uuid(id))
case final step?) {
await protocol.LearningPathStep.db.updateRow(
_db,
step.copyWith(position: position),
columns: (t) => [t.position],
);
_sync.requestSync();
}
}
@override
Future<void> blank({String? stepId, String? pathId}) async {
if (stepId != null) {
final revisions = await protocol.LearningPathStepRevision.db.find(
_db,
where: (t) => t.stepId.equals(_uuid(stepId)),
);
// Column-scoped updates, which sync like any other edit (ADR 0002,
// rule 2).
await protocol.LearningPathStepRevision.db.update(
_db,
[
for (final revision in revisions)
revision.copyWith(payload: redactedPayload),
],
columns: (t) => [t.payload],
);
}
if (pathId != null) {
await updatePathPayload(pathId, redactedPayload);
}
_sync.requestSync();
}
@override
Future<void> deleteStep(String id) async {
final step = _uuid(id);
// Its answers go too: no content, but personal study data that would
// otherwise stay on the server as hidden rows.
await protocol.LearningPathAnswer.db.deleteWhere(
_db,
where: (t) => t.stepId.equals(step),
);
await protocol.LearningPathStepRevision.db.deleteWhere(
_db,
where: (t) => t.stepId.equals(step),
);
await protocol.LearningPathStep.db.deleteWhere(
_db,
where: (t) => t.id.equals(step),
);
_sync.requestSync();
}
@override
Stream<void> get remoteChanges => _sync.merges;
protocol.UuidValue _uuid(String id) => protocol.UuidValue.withValidation(id);
}

View file

@ -0,0 +1,13 @@
/// Fakes of halkyon_learn_core's gateways, in memory, for the tests of
/// Learn's app and of its agent: nothing here reaches a server, a database
/// or the file system.
library;
export 'testing/fake_asset_gateway.dart';
export 'testing/fake_asset_sealing.dart';
export 'testing/fake_card_gateway.dart';
export 'testing/fake_feedback_gateways.dart';
export 'testing/fake_learning_path_gateway.dart';
export 'testing/fake_note_gateway.dart';
export 'testing/fake_studyset_gateway.dart';
export 'testing/fake_tag_gateway.dart';

Some files were not shown because too many files have changed in this diff Show more