Compare commits

...
158 Commits
Author SHA1 Message Date
Bendik Aagaard LynghaugandClaude Opus 5.5 db89ea6400 An upload that did not arrive says why
Test / test (pull_request) Successful in 1m21s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 21:08:28 +02:00
Bendik Aagaard Lynghaug 95bffc221b Release 0.6.7
Test / test (push) Successful in 1m19s
Publish release / publish (push) Successful in 2m8s
2026-09-30 20:50:44 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 f5266cb347 Changelog: 0.6.7
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 20:50:42 +02:00
bl 248561e805 Merge pull request 'leaves_after: finished records leave their lists' (#16) from leaves-after into main
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m16s
2026-09-30 18:50:41 +00:00
Bendik Aagaard LynghaugandClaude Opus 5.5 0dc25b4023 A record may leave its lists some time after reaching a state: leaves_after
Test / test (pull_request) Successful in 1m20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 20:50:28 +02:00
Bendik Aagaard Lynghaug 96c513d912 Release 0.6.6
Test / test (push) Successful in 1m16s
Publish release / publish (push) Successful in 2m7s
2026-09-30 20:39:12 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 0cb1dda202 Changelog: 0.6.6
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m16s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 20:39:10 +02:00
bl ec9bf10b72 Merge pull request 'A card of one's own; no double sends; refusals shown' (#15) from own-card into main
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m14s
2026-09-30 18:39:09 +00:00
Bendik Aagaard LynghaugandClaude Opus 5.5 809a6bdfe8 A card of one's own: one_per_person, prefilled, replaced on send; no double sends; refusals are shown
Test / test (pull_request) Successful in 1m12s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 20:39:01 +02:00
Bendik Aagaard Lynghaug cae116b50c Release 0.6.5
Test / test (push) Successful in 1m9s
Publish release / publish (push) Successful in 1m54s
2026-09-30 20:10:59 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 d8528ff1f9 Changelog: 0.6.5
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m10s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 20:10:56 +02:00
bl 6c2e0cc299 Merge pull request 'A need may be paused' (#14) from paused-needs into main
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m10s
2026-09-30 18:10:56 +00:00
Bendik Aagaard LynghaugandClaude Opus 5.5 9368086d81 A need may be paused: its card stays, with no form and a button that does not press
Test / test (pull_request) Successful in 1m12s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 20:09:14 +02:00
Bendik Aagaard Lynghaug e2497941c8 Release 0.6.4
Test / test (push) Successful in 1m9s
Publish release / publish (push) Successful in 1m55s
2026-09-30 19:52:12 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 55fc61c514 Changelog: 0.6.4
docs / deploy (push) Successful in 2s
Test / test (push) Successful in 1m9s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 19:52:10 +02:00
bl 3b17e6440e Merge pull request 'Rate limit: 100 at once, 10 a second; the page's own files uncounted' (#13) from rate-limit into main
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m9s
2026-09-30 17:52:09 +00:00
Bendik Aagaard LynghaugandClaude Opus 5.5 87d4dda0eb Rate limit: a hundred at once, ten a second, and the page's own files are not counted
Test / test (pull_request) Successful in 1m15s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 19:51:48 +02:00
Bendik Aagaard Lynghaug 3604683df3 Release 0.6.3
Test / test (push) Successful in 1m8s
Publish release / publish (push) Successful in 1m55s
2026-09-30 19:33:11 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 1193894b02 Changelog: 0.6.3
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m8s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 19:33:08 +02:00
bl 574d0bfe71 Merge pull request 'Pages move the way their addresses do; picture cards; who we are' (#12) from people-and-motion into main
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m9s
2026-09-30 17:33:07 +00:00
Bendik Aagaard LynghaugandClaude Opus 5.5 309e30f36d Pages move the way their addresses do; a record with a picture is a card; the trainer says who a business is
Test / test (pull_request) Successful in 1m13s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 19:32:49 +02:00
bl 748241709a Merge pull request 'Klingenberg Bygg's plan; a plan carries a slideshow' (#11) from klingenberg-plan into main
Test / test (push) Successful in 1m15s
2026-09-30 15:56:50 +00:00
Bendik Aagaard LynghaugandClaude Opus 5.5 a70690a736 Klingenberg Bygg's plan and words; a plan carries a slideshow; the words model is told what a follower's desk and an inside sent page are
Test / test (pull_request) Successful in 1m17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 17:56:24 +02:00
Bendik Aagaard Lynghaug 827a75be3d Release 0.6.2
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m14s
Publish release / publish (push) Successful in 2m3s
2026-09-30 17:39:57 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 4e0a56be13 Changelog: 0.6.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 17:39:55 +02:00
bl 04204bef23 Merge pull request 'The header knows who is here; my cases; controls that scale' (#10) from header into main
docs / deploy (push) Successful in 2s
Test / test (push) Successful in 1m14s
2026-09-30 15:39:54 +00:00
Bendik Aagaard LynghaugandClaude Opus 5.5 c766dedc0e A stored file on a record shows as its name and opens from the row
Test / test (pull_request) Successful in 1m16s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 17:38:32 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 a822f2175f Trainer: followed_by - a group whose members each see their own cases; file fields
Test / test (pull_request) Successful in 1m14s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 17:36:08 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 f2b131ebbb KANIDM_GROUP_PREFIX: plain group names in content on a shared Kanidm
Test / test (pull_request) Successful in 1m14s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 17:34:21 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 6b72ae568a The header knows who is here; my cases; controls that scale with the text
Test / test (pull_request) Successful in 1m12s
A session link top right on a site with sign-in, and on a page with
pictures the wordmark as its own bar over the strip. A list may be
narrowed to the signed-in person's own records ({user.email}, from the
session), and an attachment follows the list that shows its record.
Form controls are sized in em: the date picker's icon and the file
picker's button scale and take the field's colours.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 17:32:41 +02:00
Bendik Aagaard Lynghaug 9a96386444 Release 0.6.1
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m7s
Publish release / publish (push) Successful in 1m46s
2026-09-30 17:19:36 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 5c95b6d8b3 Changelog: 0.6.1; the bare binary sorts after the tarball
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 17:19:34 +02:00
bl d3a9e79351 Merge pull request 'A slideshow across a page' (#9) from slideshow into main
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m8s
2026-09-30 15:19:33 +00:00
Bendik Aagaard LynghaugandClaude Opus 5.5 c1a8433640 Slideshow: brace the closure
Test / test (pull_request) Successful in 1m8s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 17:17:55 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 cfb050d3ef A slideshow across a page: pictures the full width of the screen, captions over them
Test / test (pull_request) Failing after 1m5s
slideshow on a page: max_height in svh, slides with an image (a path
in the content repo or https), a caption laid over the picture's foot,
and optionally the picture's size so its place is held before it
loads. Swiper upgrades it; before that it is a row that scrolls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 17:16:50 +02:00
bl fc708c3546 Merge pull request 'Trainer: documents - a text word for word, one card per section' (#8) from documents-as-cards into main
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m7s
2026-09-30 15:06:28 +00:00
Bendik Aagaard LynghaugandClaude Opus 5.5 c7e0ee146f Trainer: documents - a text word for word, one card per section
Test / test (pull_request) Successful in 1m8s
Bylaws and terms are not the model's to write. documents in a plan
names a markdown file beside it; every heading with text under it is
one alternative on a page of its own, its paragraphs the card's words.
Tomter Vel's bylaws of 23.04.2018 are the first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 17:05:06 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 3bb517be0f Docs: vel.klingenbergbygg.no runs v0.6.0
docs / deploy (push) Successful in 2s
Test / test (push) Failing after 8s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 15:40:35 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 4eb1d03583 Changelog: 0.5.11 was tagged and never published
docs / deploy (push) Successful in 2s
Test / test (push) Failing after 35s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 15:38:53 +02:00
Bendik Aagaard Lynghaug 3cb0733955 Release 0.6.0
docs / deploy (push) Successful in 3s
Publish release / publish (push) Successful in 1m53s
Test / test (push) Successful in 1m5s
2026-09-30 15:33:17 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 969c22b432 Changelog: 0.6.0
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 15:33:15 +02:00
bl a17da3198c Merge pull request 'One binary: the lint and the trainer are commands of portal' (#7) from one-binary into main
docs / deploy (push) Successful in 2s
Test / test (push) Successful in 1m6s
2026-09-30 13:33:14 +00:00
Bendik Aagaard LynghaugandClaude Fable 5.1 48cba5cd8e Docs: the examples in English
Test / test (pull_request) Successful in 1m5s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 15:31:59 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 96b3746643 One binary: the lint and the trainer are commands of portal
Test / test (pull_request) Successful in 1m7s
portal serve runs a site; portal lint is what iris was; portal plan,
build, report and the rest are what portal-trainer was. One source at
one version, so the three never disagree about what content means.
Both histories are merged in (subtree). The release attaches the bare
binary for a content repo's CI. The trainer's plans, intakes, engines
and reference prompt come along; its runs stay in the old repo.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 15:29:30 +02:00
Bendik Aagaard Lynghaug d0d1cbf23d Bring the lint in (uhhm/iris main, history kept)
git-subtree-dir: vendor/lint
git-subtree-mainline: bedd306854
git-subtree-split: e3c68f9441
2026-09-30 15:23:16 +02:00
Bendik Aagaard Lynghaug bedd306854 Bring the trainer in (uhhm/portal-trainer main, history kept)
git-subtree-dir: vendor/trainer
git-subtree-mainline: c7c2956e15
git-subtree-split: a2a9f4edcf
2026-09-30 15:23:15 +02:00
Bendik Aagaard Lynghaug c7c2956e15 Release 0.5.11
docs / deploy (push) Successful in 2s
Test / test (push) Failing after 39s
Publish release / publish (push) Failing after 2m13s
2026-09-30 15:17:32 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 267f7f0787 Changelog: 0.5.11
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 15:17:30 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 e3c68f9441 needs.yaml may name the tones
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 15:17:20 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 a2a9f4edcf Tones and storylines: every word once per tone, kept through a lift, and a report of what each brought in
tones in the plan lists tones of voice, one storyline each. The words
pass writes each page once per tone and folds the tones into lists
where they differ; the render emits the lists portal reads as
storylines; the lift carries them back. needs.yaml names the tones.
portal-trainer report --site reads the site's counts per storyline
and scores each on what arrived and what ended well.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 15:16:29 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 f395ace556 Storylines: the same site told several ways, one per visitor, counted
docs / deploy (push) Successful in 3s
Test / test (push) Successful in 1m1s
Any text a person reads may be a list, one entry per storyline, every
list the same length. A visitor is given one storyline for the whole
site and reads it on every page and in every mail about their case.
Records and events carry the storyline; GET /report gives counts per
bucket, storyline and state, and nothing else.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 15:11:27 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 cc3107e502 Docs: vel.klingenbergbygg.no runs v0.5.10 with memberships
docs / deploy (push) Successful in 3s
Test / test (push) Failing after 25s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 14:22:11 +02:00
portal release 050fb34fb0 Match portal v0.5.10 2026-09-30 14:13:58 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 ca73ef7e9f plans: Tomter Vel keeps its people in portal (people: memberships)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 14:12:22 +02:00
portal release b86a12e5df Match portal v0.5.9 2026-09-30 14:09:37 +02:00
portal release 2f04c82c89 Match portal v0.5.8 2026-09-30 13:44:15 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 b0787f7c5a build: people: memberships - invite by phone number, list who is in
With portal keeping the groups itself (portal v0.5.7), a desk's invite
form asks for a phone number first, the list of invites is the list
of memberships, and a grant may know the person by number.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 13:37:02 +02:00
portal release 00449916a3 Match portal v0.5.7 2026-09-30 13:36:50 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 1025dd7718 build: escalate - a case left too long goes up to another desk with the same buttons
escalate: { <stage>: { days, to: <group> } } on a need adds a stage
<stage>_escalated the clock enters, with the same moves out of it; the
group's desk lists exactly those cases with those buttons, and the
desk that had it keeps it and may send it up itself. Not a mail: a
desk job. The vel's help requests go up to styret after a week.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 11:58:02 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 3dabcf7c58 build: one page holds every need that answers a record; runs: the kommune planned again by Opus
Two needs about the same record wrote the same page, and the last won.
The record's page now holds one form per answering need, under
words["forms"][need].

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 08:58:55 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 41db6093e5 The effort budget counts what a person fills in, not carrier fields
A type: record field carries the case an answer is about on the link,
and a hidden preset carries a value; neither is asked. An objection
form that carried the application's id counted one field over.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 08:57:03 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 9776dc1808 plan: the guidance names records that answer records, members-only needs and a group contact
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 08:38:44 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 28ef235906 build: a door may point to a members-only need; signed-in people are not asked who they are; a granted group does not self-invite
The vel: paid membership grants the medlemmer group, and a committee
seat is offered on the bidra door and taken on the members' page.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 08:38:25 +02:00
portal release 572dfc200c Match portal v0.5.6 2026-09-30 08:22:10 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 67250af445 build: the plan's contact may be a group, which then answers for every page
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 08:18:30 +02:00
portal release 955a33609a Match portal v0.5.5 2026-09-30 07:54:29 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 894f228b8f build: the answer page's guidance says what it is not
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 07:02:51 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 42b6ce7c70 build: a desk card is its list; runs: Tomter Vel's lending board answered from the board
The lift matched cards on a desk by action, which every card there
shares, so a card that left the desk left its words on the next one.
A card with a strong identity - a bucket, a group it invites into, a
page of its own - is matched on that alone, and a desk card's identity
is the bucket its feature lists.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 07:02:40 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 4e1bc2027d build: a need about another, answered from the board's own rows
`about: <need>` on a need puts its form on a page per record of the
other need (/status/<bucket>/[key]), links every row of the public
list to it, carries the record's id in a type: record field, takes a
signed-in person's address without asking, and lets `mails: { open:
owner }` reach whoever sent the record. The vel's plan uses it for
the lending board: notices stand from the moment they are sent, the
board hears, an answer goes straight to the poster, the queue is the
poster's inbox, and the redaktør or the clock takes down what stands.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-30 06:55:28 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 02235a7ef1 build: the way down the tree is the link at the foot
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-29 21:23:05 +02:00
portal release 9b96111916 Match portal v0.5.4 2026-09-29 21:14:02 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 5e53485de5 build: invites can be sent again, and suggested changes have a desk
Portal 0.5.4 moves an invite whose link ran out to expired and files
what responsible people suggest as cases in portal_edit_suggestions.
Every desk that lists invites gets the move back to open (a fresh link,
mailed), and the desk that invites into the most groups - where portal
seeds the first person - gets the list of suggestions with its moves.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-29 21:01:48 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 6a746543df runs: Tomter Vel without back alternatives, on portal v0.5.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-29 13:38:33 +02:00
portal release f2fc5097f7 Match portal v0.5.3 2026-09-29 13:33:07 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 c2658ae2c4 build: no 'back' alternatives; portal's way down the tree replaces them
The page after sending and every public list ended with a Back/Tilbake
alternative. Portal now puts a way down the tree on every page (an
arrow at the left edge and a link at the foot, uhhm/portal PR 1), to
the nearest page below that the visitor may open: the front door after
a public form, the group's desk after an internal one. Sites built from
here need a portal that carries it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GT37Z1Xtfd9pUuQtMTg6Yt
2026-09-29 07:05:48 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 cda3b0685a build: new generic lines fall back in the plan's language; Tomter Vel's front door deployed
List notes, empty lists and the invite form's guidance are lines no
model is asked about before a page ships; on a Norwegian site they
showed in English until reworded. They now fall back in Norwegian for
no/nb/nn plans, like the mail fallbacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 20:50:24 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 5e736668e4 runs: uhhm on portal 0.5.1 (scrapped after preview), its mail rounds, and Tomter Vel's front door
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 20:34:53 +02:00
Bendik Aagaard LynghaugandClaude Opus 5.5 d4d4c7cba3 Portal 0.5 in the plan, mails scored as read, and a front door that shows
Portal 0.5's content, from the plan: `grants` (an approval that is
membership; refused without a mail sender, since the sign-in link goes
by mail), `deadlines` (portal's `after:`, only along a move the
machine has), and `public_states` with an `empty` line on public lists,
whose words now say which stages they show.

Onboarding is a mail too: a plan that invites or grants gets
`mail.invite` in site.yaml in its own language, and a reword that loses
{link} gets it back. `rate --repo` rates every mail, the invite
included, read as it arrives: LIX, and what happened / what now / who
wrote, each against a gutted twin. The mail words are guided by what
that found on uhhm (name the case by a short required field, sign with
the business, invite a reply rather than promise a reason).

The front door shows public lists instead of pointing at them: each
public bucket is a feature with its newest three records inline and a
link to the whole list. Its card is named for what it shows. The plan
reference gains 'What a portal site can do': the schema's options and
when each pays off, as guidance rather than rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 20:34:53 +02:00
portal release f2ca00b309 Match portal v0.5.2 2026-09-28 18:11:49 +02:00
portal release ac4af4395a Match portal v0.5.1 2026-09-28 17:51:11 +02:00
portal release 1e7245b062 Match portal v0.5.0 2026-09-28 16:50:47 +02:00
Bendik Aagaard LynghaugandClaude Opus 5 040a95ee07 A submitter's own moves say where they may be made from
portal compiles one access rule per state a self_transition names, and
without them assumed the day the case arrived. The builder already
knew the answer - `moves_of(need, SUBMITTER)` carries the from-state
of every move - and now writes it down, so the applicant answering a
request for papers from `incomplete` gets a rule for it, and withdrawal
is offered from wherever the case has got to.

Measured on the building authority: the submitter had two rules, both
out of `open`. It now has ten, across applications and appeals.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-25 21:35:32 +02:00
Bendik Aagaard LynghaugandClaude Opus 5 3e1c299490 A door costs the person who was going to pick correctly
Three seeds over the building authority's front door, then three more
over a variant where the two bare needs became doors of their own.

The diagnosis held: six of the eight front-door misroutes went to the
appeal, a concrete sentence standing among abstract categories, which
collected everyone with any sort of grievance whatever it was about.
Behind a door of its own it collected none.

The site got no better for it - 77.3% against 80.0%, inside the spread.
Two offers went from findable to hidden: the firm whose insurance
certificate had lapsed found "to be on the list, and then to file
without asking again" as a sentence on the front door, and fails every
seed once it is behind a door called "Work as a firm".

So the leak was not costing what it looked like it was costing, and the
rewrite is rejected on measurement. The mixed front door stays.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-25 20:25:25 +02:00
Bendik Aagaard LynghaugandClaude Opus 5 d2aae383b2 A case can be sent back, and can end well partway along
A municipal building authority is the first sector that the line a
case walks could not describe. An application is returned for the
drawing it was missing and walks the same stretch again; an appeal
ends the moment the authority changes its own decision, without ever
reaching the board; an applicant may withdraw from anywhere, while a
refusal may only come once the papers are in.

`reached_from: { <stage>: [<stage>, ...] }` says where a stage is
entered from when the line does not. A stage named there is entered
from exactly those stages and nowhere else, so saying where a refusal
may come from also says where it may not - which `turned_down_from`
could not, being one list for every bad ending at once.

Found by replaying fifteen real building cases through portal's own
engine against a throwaway JetStream: it refused three legal paths and
accepted two illegal ones. Portal needed no change - hand-writing the
correct graph into aggregates.yaml, cycle and all, was accepted and
enforced exactly. The rebuilt site now produces that same graph from
the plan, and the access policy follows it.

Also: a public view is of a bucket, not of a need. A permit register
holds the owner's small application and the approved firm's large one
and is one page either way; the rule refused to publish a bucket the
moment any role filed into it. A bucket only a role ever writes to is
still refused.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-25 20:17:06 +02:00
portal release a847d0defa Match portal v0.4.0 2026-09-24 21:37:28 +02:00
Bendik Aagaard LynghaugandClaude Opus 5 443ddcca68 A plan may ask for a place
`type: location` on a field is portal 0.4.0's map pin, stored as
lat/lon/zoom. The reference tells the model it needs `optional: true`,
since a map needs a browser that can draw one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 21:35:45 +02:00
Bendik Aagaard LynghaugandClaude Opus 5 242a1e0ad6 The keys come out in the order they were written
A page is read by the people who own it, and serde_json sorts keys, so
every file put `name` at the bottom under `action` and `consequence`.
With preserve_order the file reads the way it was built: name, then
description, then what the card does.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 20:44:37 +02:00
Bendik Aagaard LynghaugandClaude Opus 5 1ed33b6160 build: a card states what the reader must already have
`requires:` on a need is one sentence naming what the person must
have or be for the alternative to work - a membership, a reference
number, the link from a mail. It renders as the card's first feature,
above the road, who-reads-it and the form, because a condition a
reader meets only after filling the form in has already cost them the
filling in. Whether the section exists is read from the plan, never
from its wording: under a lift every slot holds a token and a token is
never empty, which would conjure a section the live page lacks and
shift every feature after it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 20:42:41 +02:00
Bendik Aagaard LynghaugandClaude Opus 5 743f4a8563 build: every feature says something; a lift carries words, not absences
Five features were emitted empty, as layout: a door's strip, a desk's
list, an invited list, a public list, an invite form. Each now has a
title and a line that says what a row is and what the buttons under it
do, or what the list leaves out - true from the plan before a model
writes a word, and a slot the model can improve. Desk cards, their
links and the desk page itself get real fallbacks too. The lift no
longer copies an empty live string over a fallback, which would have
emptied every new slot on the next rebuild.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 20:40:03 +02:00
Bendik Aagaard LynghaugandClaude Opus 5 c6d0701639 build: the mail cleanup runs on the final words, not only a model's reply
A stray placeholder or a lost link was only fixed when a model wrote
the mail, so a words file that already carried one kept it through
every later build. The pass now runs once on the finished
aggregates.yaml words, covering --words, --words-from and the model
alike; the football club's three mails lose the `{chain}` they were
shipped with.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 20:28:27 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 0a02b4db1a build: a bare {chain} in a mail body goes, on its own line or inline
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 09:33:21 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 88e54ed17f runs: the club's short mails, as actually written
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 09:01:11 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 f516e26926 build: a mail is at most three short sentences and the link line
The mail prompt said "short"; it now says how short. The football
club's enrolment mails halved in length and read easier, and the
vel's evened out, with every link kept.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 09:00:15 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 6f2f7e271c runs: the football club with a sender, stage words and mails
The second Norwegian case: level with its earlier build on routing
inside the spread, desks 13 of 14 with outcomes in words, Norwegian
mails from Sonnet in one pass.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 08:28:26 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 1df710f32f runs: the friendliness judge passes a positive control
Live vel front door against a cold, bureaucratic twin: friendlier 9
of 10 to the live page, none to the twin, both orders. So the earlier
no-preference between the live doors and the rejected rewrite was a
verdict, not blindness; and judged clarity and measured routing are
different things.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 07:50:52 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 fd785288a4 runs: the rejected vel doors read clearer and route worse
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 07:15:58 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 4d22f4cb44 plan: a spectator role goes back to the model once; bare-word movers and unlabelled groups parse
Re-planning the contractor showed three wasted rounds: `moves_by: {
checking: submitter }` written as a bare word, a group without a
label, and the two featured owner roles left with nothing to play,
which the builder only warned about after the fact. The bare word and
the missing label now parse (a label defaults to the id), and a plan
that parses with spectator roles is sent back once with the finding;
on the contractor, round three fixed both.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 06:42:05 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 6e49694211 build: turned_down_from, and uhhm's stages in words
A need may say which unfinished stages a case can still be turned
down from; the machine no longer offers the bad end from every stage.
uhhm's collaborators are declined before they start and depart after,
as the live site has it. The uhhm plan gets stages_text and three
desk buttons reworded: every uhhm desk scores full marks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 06:01:56 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 aeff4c8cbe CI: lint with iris v0.3.47
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 05:23:48 +02:00
portal release 57b733e606 Match portal v0.3.47 2026-09-24 05:20:11 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 be14e33603 build: stages in the plan's own words
`stages_text` on a need gives each stage plain words in the plan's
language. The fallback mails, the road line and the desk buttons use
them, and needs.yaml carries them as `stage_words` so the desk score
describes an outcome the way the site would. The vel's plan has them;
its desks score 26 of 26 where the id-based outcome scored 24.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 05:17:18 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 3923d4d0dc needs: stage_words, each state in the site's own words, carried into the simulation model
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 05:17:11 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 8e6a93ebb7 rate: a desk row offers only the buttons that start from its state
The first desk score offered every button of the bucket, where portal
shows a row only the moves from its own state; that scored the live
vel 17 of 26 and sent a rewrite of the neighbour-help desk chasing an
instrument fault. With the row's buttons only: 24 of 26, and the
rewrite loses on the fair test too. Noted: an accent-stripped state id
(ikke_lost) reads as English even to a strong picker.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 04:39:13 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 9089503524 rate: the desks are scored on their buttons
The inside of the business reads button labels and nothing else. For
every desk and bucket with two or more buttons, a worker is told what
just happened to a case, in the state's own words, and picks the
button; scored right of total with what each miss was taken for. The
vel's neighbour-help desk scores 2 of 4 and the notice board 1 of 2:
the first numbers a desk has ever had.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 03:44:52 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 5e313b7d40 runs: the planned contractor rated
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 03:05:00 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 2622fdac88 plan: a budget that equals the form is reported as counted, not decided
Four of the planned contractor's five needs had max_fields equal to
their required fields: the model counted the form and called it the
person's tolerance. `plan` now says so when most needs do, and the
reference tells the model to decide the number before writing the
form.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 03:04:22 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 d132f1e4df runs: the contractor planned end to end, 7 of 8 across seeds
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 02:32:30 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 209e9d1258 plan: held-out personas are mapped to the plan's needs by a model, ids only
The one manual step left after `plan` was mapping the attached
personas' `need:` to whatever ids the model chose. A second call now
does it: the model sees the plan's needs and the persona texts and
returns ids only, after the plan is final, so no persona wording can
reach a page. An id the plan lacks is ignored and the reader is told.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 02:27:38 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 b1f0210691 build: personas naming undeclared needs is the reader's mapping, not a builder bug
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 01:55:39 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 20e5e16641 plan: the model that writes a plan learns this week's keys
`does`, `shows`, `mail`, `mails`, `invites_by`, `events`,
`attended_by`, and the measured guidance on doors: the plan reference
the model reads lagged the builder by a week, so a planned site had no
opener, no mails and no onboarding.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 01:54:02 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 42059da48f CI: the tests, and every plan built and linted
The trainer had no CI. Every push now runs the tests and builds every
plan under plans/ against the iris release the live sites run, and
lints the onboarding site.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 01:16:35 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 07da3b40f7 Docs: the skill file says what the trainer does now
iris instead of question_lint everywhere; the skill's procedure is
plan, build, score: the opener and the look-around, mails and the
sender, moves for the person, doors only when measured, the lift
through a rebuild, the language and link guards, the descriptions
score over the headings score, and the spread a change has to beat.
README documents --llm-for.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 00:45:16 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 deee27d280 runs: the vel doors reworded by a model, worse across three seeds, rejected
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 00:12:57 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 8c7fb870bf build: a reply in the wrong language keeps the words it had; the vel's mails
A model asked for Norwegian sometimes answers in English. The commonest
function words of each language are counted across a reply, and one
that reads as the other language is refused with a line saying so.
Tomter Vel's six mails, worded by Sonnet in Norwegian, are round 2 of
runs/tomtervel-opener-2026-09-23 and live.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 23:35:32 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 72a081ed59 build: a model may not lose the submitter's link; uhhm round 7, the mails
Sonnet wrote the ten uhhm mails and replaced the decide link with a
bare {chain}. keep_links puts the fallback's link line back into any
mail that lost it. The mails read easier than the fallbacks (LIX 9 to
33 against 18 to 28) and say something.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 23:02:48 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 b5f5c46ff2 build --llm-for <prefix>, and rate reads the mails
The words model can be pointed at a subset of pages (`aggregates.yaml`
for the mails alone) while everything else keeps the words it has.
`rate --repo` rates each mail's prose on its own, LIX and length,
since a person reads a mail with no card around it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 23:00:37 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 1191551f28 README: the noise floor, measured over four seeds
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 22:59:10 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 c240d3a646 spread.sh: the engine path is absolute
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 22:46:44 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 cc50249d7f answer --seed, and runs/spread.sh: a score comes with its spread
Every score so far was one run of a small visitor. `answer --seed n`
answers the same tasks with other shuffles and sampling, and
runs/spread.sh prints a run's score per seed, so a change can be told
from the visitor's mood.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 22:46:25 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 ec2f07da77 runs: Tomter Vel keeps its doors and gains the opener; merged
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 22:43:55 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 00db014eae A card with no button is read, never picked
The opener that says what the business does and the look-around card
lead nowhere: they are what the page says before its options, so a
task and a simulation step carry them as `page` context and offer
only the cards that lead somewhere. Five personas per round had been
"choosing" the opener and counted as misroutes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 22:36:20 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 09aea7061c The visitor and the rater read what the page says first
iris now hands a task the cards that lead nowhere as `page` context;
the answerer shows it before the options and the rater before the
cards, and the gutted twin loses it like everything else. The Tomter
Vel plan keeps its four doors and gains the opener, the mails and the
member's own move: flat scored worse and the doors stay.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 22:36:13 +02:00
portal release d2450fcb75 Match portal v0.3.46 2026-09-23 22:21:14 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 e3dae063d4 English in the code: fixtures, identifiers, and one phrase table
The fallback mail phrases move into a `Phrases` table, the one place a
language other than English appears in this code; the `navn` special
case goes (a form names the person's field `name`). Test fixtures
speak English: traffic, board, hazards, report, fixed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 22:09:04 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 713f8ff3a0 build: words follow a card across pages when a site is restructured
`--words-from` matched page by page, so flattening Tomter Vel lost
every heading its door pages carried. Now a second pass pools every
alternative in the repo and hands a rendered card the pooled card
with the same strong identity (bucket, own page, invite group; never
a bare action like `/`). Two things stood in the way and are fixed:
needs.yaml is no longer a source of words (its `via` named the door),
and a live feature's `name` no longer blocks a positional match, so
placeholders and guidance lines come along too. Rebuilding the vel
flat from the live repo now lifts all ten headings and every hint.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 22:01:55 +02:00
portal release 0841ed561a Match portal v0.3.45 2026-09-23 21:26:51 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 a8e9d38a6a runs: uhhm round 6, the mails
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 21:19:38 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 8341089898 build: a plan says who hears when a case moves, and the words write the mail
`mails: { <stage>: submitter | <address> }` on a need becomes `mail:`
on that state in aggregates.yaml (portal 0.3.43+), and `mail: { from,
reply_to }` on the plan becomes site.yaml's sender. The words map
gains `aggregates.yaml`, one subject and body per mailing stage, so
the model writes them like any other page; the fallback, in the
plan's language, says what happened and where the submitter's own
move is. A submitter mail needs a required email on the form; any
mail needs a sender. The uhhm and Tomter Vel plans tell the submitter
at every stage that matters to them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 21:18:14 +02:00
portal release 79f85132c5 Match portal v0.3.44 2026-09-23 21:18:10 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 f5f5132056 build: the lift matches cards by identity, not position
Sequences were walked side by side, so a rebuilt page whose cards sit
in a different order, or with a new card in front, gave every card
its neighbour's words: uhhm.no's front door got "Attention is earned"
on the wrong card that way. Items now match on the bucket they record
into, the page they lead to, a field's name, the group they invite
into or the bucket they read; information features with no identity
still match by position. Lifting live uhhm.no into the current plan
puts each of its three headings on the card with its bucket.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 20:48:47 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 bf60879de9 score: the whole grading of a built site as one command
iris writes the tasks and the model, the blind visitor answers with
descriptions and with headings only, iris scores, rate reads the
cards; the routing numbers land in summary.json. Replaces the
score.sh every run carried. Proven on runs/uhhm-2026-09-23/site.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 20:25:55 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 9ff9924374 build: --words repeats and layers; the desk's confirm slot says what it is
Two things the uhhm rounds ran into. Only the first --words was read,
so a round of hand changes had to be merged into the previous words
by hand; now each file layers over the last. And the desk's one
confirm slot was described like any button, so a model wrote "Send
invite" under the cases list; it now says it serves every list.
README: the lift is positional, and where that bit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 20:02:30 +02:00
portal release 58d68c3bff Match portal v0.3.43 2026-09-23 19:48:01 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 9e7f16c489 build: the front door opens modestly, and a featured role must have a move
`does:` on a plan, at most two features, each `for:` a need: the first
card of the front door says what the business does, one role each,
headed by what that role gets, and asks for nothing. `shows:` is the
second card, portal resource blocks passed through verbatim plus every
public view. Only then the offers, as more alternatives on the same
page; the front-door warning moves to seven and stops recommending
doors. `Plan::spectators()` warns when a featured need gives the
submitter neither a move nor a view. uhhm.no rounds 4 and 5 (flat,
at least as good per persona) and Tomter Vel flat (worse: ten offers
on one page, the close pairs collide) are in runs/.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-23 18:24:23 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 9e511b5b57 runs: uhhm.no from a plan, three rounds of wording
Sonnet writes, qwen3:8b routes: 16 then 19 of 27 with descriptions,
19 then 21 of 27 on headings alone. One card took seven personas
until it named redoal; what remains is on the front door and mostly
a judgment the plan could make differently, not the words.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 15:09:35 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 04a6eeea85 build: a plan keeps a live site's event names, and names its automations
`events:` on a need overrides the event a stage is entered by. Portal
replays records by event name, so rebuilding a site that already holds
records has to keep what its aggregates.yaml says, or the desks empty.
`attended_by:` writes portal's annotation for a bucket an automation
moves. plans/uhhm.yaml: uhhm.no from a plan - the five live buckets
with their names, plus trials (the trainer tried on a client's
business, approved by hand) and custody_requests (UHHM as redoal's
custodian, a desk of its own).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 14:49:25 +02:00
portal release 0cf70502fc Match portal v0.3.42 2026-09-23 14:35:49 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 93a6fc0e10 build: invites from the plan, and rebuilding a live site without losing its words
`invites_by` on a plan (and `invited_by` on a group) put an invite form
per fillable group on the inviting group's desk, plus a list of the
invites sent - portal's `invite:` does the onboarding. Every desk
group invites into itself by default; an inviter without a desk is
refused.

`--words-from <repo>` lifts the words an existing repo carries back
into the words map by structure: the plan is rendered with a token in
every slot and walked alongside the repo's files. Hand edits and
model-chosen icons survive a rebuild; only new slots get fallbacks,
which `--words <json>` can override. The words as used are written to
words.json. First use: Tomter Vel, additions only.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-23 12:42:23 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 255aeb4f4b plan: intake to plan by a model; doors, labelled groups, the whole card
Work from another session, committed as found (tests green):

- `plan` reads an intake into a plan.yaml (a model decides needs,
  stages, forms and budgets; a person reads the result before build).
- Plans gain `doors` (a first question before the forms, when a front
  door would carry more than five needs), `groups` with labels that a
  select may draw its options from (`options_from: groups`), `private`
  fields kept off public pages, `multiple` selects, and `max_fields`
  as what the intake said the person will tolerate.
- `card.rs`: an alternative as the visitor meets it, in text, so the
  answering visitor and `rate` read the served card, not the heading.
- `rate` reads followup pages from the repo and reports "what happens
  next" as not measured rather than zero when it cannot.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-23 12:31:51 +02:00
portal release fb66694b85 Match portal v0.3.41 2026-09-23 11:55:10 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 959e5f6ef0 check: compile and validate the access policy; --access prints the matrix
Every check now compiles the content into portal's Cedar policy and
fails when it does not validate against the schema - a rule the
schema cannot express would grant nothing at runtime. `--access`
prints the matrix: action, resource, who, and the state move where it
applies. Pinned to portal v0.3.40, where the policy lives.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-23 11:48:33 +02:00
portal release 9cd5dff4c2 Match portal v0.3.39 2026-09-23 06:03:18 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 bd8a5e0c6c Versioned as portal: released by portal's publish job
iris reports its own version as the portal it matches; the tag, the
pin and the changelog line are written by portal's release step.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-22 22:05:06 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 e543b41cb0 CI: a writable CARGO_HOME, so the portal git dependency can be fetched
The shared /var/local/cargo is read-only for the runner; 0.1.1 built
only because this machine had already cloned the same portal tag into
it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-22 17:50:53 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 5c5a5e9990 Release 0.1.1
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-22 17:42:31 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 b093ebf0de check: fetch needs.yaml itself, so portal can drop that loader
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-22 17:28:38 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 73906cdf35 iris: the lint over a portal site, as its own repo
question_lint becomes `iris check`, needs_replay becomes `iris
replay`, and the needs module and local-checkout loaders come with
them. Portal is a library dependency pinned to the release iris
matches (v0.3.36), so every type iris reads is the site's own and the
two never disagree about what a page is. `iris --path questions`
still works, so a content repo's one-line CI needs only a new path.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-22 17:25:52 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 baf36319b7 Overlapping roles on one aggregate, relay routes, and a dry run
plan.yaml: `moves_by` says who presses the button into a stage when it
is not `handled_by` - other groups, several groups, or `submitter`,
the person who sent the form, through their own link (the form must
then collect a required email). `watched_by` puts a bucket on a
group's desk with no buttons. Each group's desk carries its own buttons
only; a submitter's moves become a followup page of self_transitions;
needs.yaml gains `also_moved_by` for portal's verifier.

simulate: a route is now a relay across every role that holds a legal
button, the submitter included, and each step is judged as the role
that presses it. `--dry` asks no model anything and walks every simple
route of every aggregate, for needs_replay to put through the real
engine.

plans/contractor-full.yaml: 13 needs, 6 roles, 10 aggregates. Verifier
green by construction; 40 routes, 78 transitions accepted by the real
engine, none refused. What it exposed is in its run README.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-21 21:46:12 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 aef0fe1396 build: slots instead of placeholders, and the first worded run
Fallback words read like finished copy, and nemotron handed the front
door straight back. The prompt now shows every string as a slot saying
what belongs there; a slot echoed back counts as no answer and keeps
the fallback.

runs/contractor-build-2026-09-21: nemotron-3.5-lightning:30b-a3b, the
model that produced no loadable site free-form, words a complete
contractor site in 130 s. Verifier green by construction; held-out
personas route 8/8 with descriptions and 8/8 on headings alone
(qwen3:8b as the visitor). "What happens next" is still 0/2 on the
front door: no heading or description says who reads a submission.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-21 21:08:08 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 8c286a8483 build: structure from the plan, words from the model
A plan.yaml is a needs spec that also says what each form collects
(and which stages a case may pass over). `portal-trainer build`
derives everything structural from it with no model involved:
needs.yaml, aggregates.yaml with the state machine read off `stages`
(walk the line, be turned down anywhere, succeed only from the end),
the front door, a followup page per need, a gated directory per group
holding its desk and the pages only that group may open, and every
desk button the machine allows.

The model is asked for words only, one page at a time, as a JSON object
whose shape is fixed by built-in fallbacks. Its strings are merged over
the fallbacks key by key, so a missing, malformed or partial reply
costs wording, never a working site, and it can neither add nor drop
structure. `via` in needs.yaml is filled mechanically from the heading
the words gave.

plans/contractor.yaml builds with no model into a site portal's
question_lint accepts: 6 needs met, 12 pages, 5 aggregates.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-21 21:01:35 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 e016698dc0 generate: drop a needless mut
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-21 20:22:05 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 b53e7e6aca generate: a Norwegian run on a local model, and what it took to read it
Every prompt and reply is now kept under <out>/llm/. An empty reply is
a retry, not a fatal error; a spec that never parses stops the run
before the structure phase; --visitor-llm lets a different model play
the visitor. The file-block parser finds markers anywhere in a line,
accepts a short END and lets a new FILE close an open one, after a
reply glued two files together with `<<<END>></think>`. The reference
gains a language section: copy in the intake's language, identifiers
in ASCII.

runs/rehab-entreprenor-no-2026-09-21: nemotron-3.5-lightning:30b-a3b
did not produce a loadable site. Written up with the reason and the
way forward: structure from needs.yaml deterministically, words from
the model.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-21 20:21:46 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 b9f2acb7b8 rate and prefer: understanding, readability, friendliness, page load
Readability is counted (LIX), not judged. Understanding is three
yes-or-no questions per persona, with a gutted twin of every page as
the control: an instrument that still says yes to "Option 1, Option 2"
is not measuring the page. Friendliness is a preference between two
versions shown in both orders; a pick that flips with the order counts
as no preference. Page load (options offered, required fields in the
step) flags a page that should be split into a further question or
have fields moved to a later stage.

First run on the generated contractor site, qwen3:8b as the visitor:
control passed on every need; "what happens next" was 0/2 everywhere
and 2/2 everywhere once the page said who reads it and when (LIX 28 to
30); an official-voice control reads LIX 63 against 27. Friendliness
mostly came back "no preference" at two personas per need: directionally
right (never preferred the cold version), too thin to rely on.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-21 19:48:25 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 612745bc66 runs: simulating the generated contractor site, with what held up and what did not
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-21 19:35:47 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 02672547ee simulate: play every case through every state, judge only what a model can
`portal-trainer simulate` reads the model `question_lint --needs-sim`
exports. A visitor model picks an alternative and fills the form in a
manner that varies by run; the case is then walked along the handling
group's own desk buttons to a finished state, a different one each
run, so every state and button is exercised. At each button the
handler model is asked one thing: with only what the form collected,
could this role really do what the button claims? Its question goes
back to the visitor, who may not know.

Who wins is deliberately not simulated. The first version let the
handler decide: qwen3:8b sent every case to "won", and after one
sentence of prompt change, every case to "lost". Outcomes belong to
the live bucket; `success` in needs.yaml is what a report over real
records counts.

`compare` sets two score files side by side. engines/ollama.sh honours
SEED, FORMAT=json and TEMPERATURE so the same case replays the same
way against two versions of a site. generator/reference.md documents
`success` and `stages`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-21 19:16:28 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 e163c22792 First generated site, a held-out test, and the leak it exposed
runs/contractor-2026-09-21: the generator's first end-to-end run, on
intakes/contractor.yaml. Needs parsed first round, structure green
first round, 10/10 on its own personas - and 8/10 headings-only on
ten held-out personas with qwen3:8b as the visitor, because the pages
had been written with the personas in view. Phase 2 now shows the
model the needs without the personas.

`portal-trainer answer` exposes the blind answerer on its own. README
rewritten around what this is: an intake in, a verified content repo
out.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-21 18:18:08 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 b6bdac6f62 Generator, LLM backends, and the onboarding site
`portal-trainer generate` turns a plain-words business intake into a
content repo in three phases, each held to portal's question_lint:
needs.yaml (then frozen, so the generator cannot weaken the spec to
pass), structure (revised against the lint's findings until green),
and wording (personas answered blind, misroutes fed back; a rewrite
that breaks structure is reverted). Model output is written to disk
only under aggregates.yaml, site.yaml and questions/**.yaml.
`portal-trainer answer` is the blind answerer alone.

The LLM is an external command, prompt on stdin, text on stdout:
engines/ollama.sh (local Ollama), engines/anthropic.sh (API key),
engines/mailbox.sh (hand each prompt to an agent or a person).

portal-portal/ is the onboarding site as a portal content repo: the
front door is the intake interview, records land in `onboardings`
(open -> drafted <-> revising -> live | declined), and it passes its
own needs spec.

runs/uhhm-2026-09-21/ollama: qwen3:8b and granite4.1:8b as blind
answerers on the same eight tasks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-21 18:14:25 +02:00
Bendik Aagaard LynghaugandClaude Fable 5.1 7caaa27ba7 portal-trainer: the loop around portal's needs verifier
The trainer procedure as an agent skill, the engine contract, two
sector specs (software-studio: UHHM's own, green; construction: a
target with no pages yet), and the first wording run against uhhm.no.
The verifier itself is portal's question_lint (uhhm/portal 188f9bf).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01L4jrCgLiKKHAEFuZUJjckH
2026-09-21 16:31:37 +02:00
89 changed files with 14782 additions and 222 deletions
+9 -64
View File
@@ -56,75 +56,12 @@ jobs:
- name: Build
run: SITE_NAME=${{ vars.PORTAL_SITE_NAME }} cargo leptos build --release
# The lint (uhhm/iris) is versioned as portal: this step re-pins
# iris to the tag being released, builds and tests it against it,
# and pushes the matching iris tag, which iris's own CI publishes.
# A portal change to something the lint reads fails the release
# right here. Needs IRIS_PUSH_USER (a variable) and IRIS_PUSH_TOKEN
# (a secret) that may push to uhhm/iris; the workflow's own token
# is scoped to this repo. A re-run of a tag whose iris tag already
# exists just builds that.
- name: Release iris to match
env:
# The shared cargo home is read-only for the runner, and a git
# dependency has to be cloned into one (same as uhhm/iris's CI).
CARGO_HOME: /var/local/cargo-target/iris-cargo-home
RUSTC_WRAPPER: /usr/bin/sccache
IRIS_PUSH_USER: ${{ vars.IRIS_PUSH_USER }}
IRIS_PUSH_TOKEN: ${{ secrets.IRIS_PUSH_TOKEN }}
run: |
set -euo pipefail
tag="${{ github.ref_name }}"
ver="${tag#v}"
host="${{ github.server_url }}"
remote="https://${IRIS_PUSH_USER}:${IRIS_PUSH_TOKEN}@${host#https://}/uhhm/iris.git"
# Re-pin, version, changelog: idempotent, so a retry on a fresh
# clone redoes exactly the same edits.
match() {
sed -i -E "s|^(portal = \{ git = \"[^\"]+\", tag = \")[^\"]+(\")|\1$tag\2|" Cargo.toml
sed -i -E "0,/^version = \"[^\"]+\"/s//version = \"$ver\"/" Cargo.toml
cargo update -q -p portal
awk -v h="## $ver ($(date -u +%F)) - portal $tag" -v l="- Matches portal $tag (released by portal's publish job)." \
'done==0 && /^## /{print h; print ""; print l; print ""; done=1} {print}' CHANGELOG.md > CHANGELOG.new
mv CHANGELOG.new CHANGELOG.md
git config user.name "portal release"
git config user.email "portal@uhhm.no"
git commit -qam "Match portal $tag"
git tag "$tag"
}
# Someone may push to iris main while this job builds; a push
# then fails as non-fast-forward, and the answer is to start
# over on a fresh clone, once.
for attempt in 1 2; do
cd "$GITHUB_WORKSPACE"
rm -rf iris-src
git clone -q "$host/uhhm/iris.git" iris-src
cd iris-src
if git rev-parse -q --verify "refs/tags/$tag" >/dev/null; then
echo "iris $tag already exists, building it"
git checkout -q "$tag"
cargo build --release
cargo test
break
fi
match
cargo build --release
cargo test
if git push -q "$remote" main "$tag"; then
echo "pushed iris $tag"
break
fi
echo "push rejected on attempt $attempt (iris main moved), retrying on a fresh clone"
[ "$attempt" = 2 ] && exit 1
done
- name: Package
run: |
set -euo pipefail
tag="${{ github.ref_name }}"
stage=$(mktemp -d)
cp "$CARGO_TARGET_DIR/release/portal" "$stage/portal"
cp "$CARGO_TARGET_DIR/release/iris" "$stage/iris"
# hash-files = true: leptos resolves hash.txt next to the running
# binary, so it ships beside portal in the release dir.
cp "$CARGO_TARGET_DIR/release/hash.txt" "$stage/hash.txt"
@@ -132,7 +69,12 @@ jobs:
# not affected by CARGO_TARGET_DIR - only the plain `cargo build`
# outputs (release/, front/) move with that override.
cp -r target/site "$stage/site"
tar -C "$stage" -czf "portal-$tag.tar.gz" portal iris hash.txt site
tar -C "$stage" -czf "portal-$tag.tar.gz" portal hash.txt site
# The bare binary as well: a content repo's CI runs `portal lint`
# and needs nothing else from the release. Named to sort after
# the tarball: Gitea lists assets by name, and deploy scripts
# written before 0.6 take the first one.
cp "$stage/portal" portal-bin
rm -rf "$stage"
# The run's own ephemeral token has write access to this repo -
@@ -159,4 +101,7 @@ jobs:
curl -sf -X POST -H "$auth" \
-F "attachment=@portal-$tag.tar.gz" \
"$api/releases/$id/assets?name=portal-$tag.tar.gz" > /dev/null
curl -sf -X POST -H "$auth" \
-F "attachment=@portal-bin" \
"$api/releases/$id/assets?name=portal-x86_64-linux" > /dev/null
echo "published $tag"
+57 -1
View File
@@ -4,6 +4,62 @@ One line per change, grouped by the release that shipped it. Newest
first. A release is a Cargo.toml bump plus a `v<version>` tag; the
content repos pin the tag they run (see the end of this file).
## Unreleased
- An upload that did not arrive says why: larger than 20 MB (checked in the browser before anything is sent), a site that takes no files (no Garage configured), not allowed from here, or anything else. It used to say "try again, or with a smaller file" whatever the reason, which sent people looking for a smaller file when the site had no storage at all.
## 0.6.7 (2026-09-30)
- `leaves_after: { minutes: 10 }` on a state: a record that has been there that long leaves its bucket's lists (days, hours and minutes add up; swept every minute; the event log keeps it). Trainer: `leaves_after` per stage on a need. A Klingenberg Bygg card taken off the front page leaves the office's list ten minutes later instead of standing there greyed out.
## 0.6.6 (2026-09-30)
- `one_per_person: true` on an alternative: each signed-in person keeps one record there, their own. The form opens filled in with it, a file left unchosen keeps the one already there (shown beside the picker), and sending again replaces the card instead of adding one. Two sends at once settle on the newest. Trainer: `one_per_person` on a need entered from inside; Klingenberg Bygg's people each edit their own card on the front page.
- Send is disabled from the moment it is pressed. Files upload before the form is sent, and a second press in that time used to send it twice.
- A failed upload stops the send and says so. The form used to go without the file, which made a record that looked complete and was not.
- A refused send says why, under its button. It used to say nothing.
## 0.6.5 (2026-09-30)
- Trainer: `paused: true` on a need. Its card stays on the front door with what the business does and a sentence saying it is not taking new ones right now, with no form and a button that does not press; nothing is recorded. The lint reports a paused need as a warning ("paused, not open now") and counts it on its own in the summary, as `planned` already did for needs not open yet. Klingenberg Bygg's building applications are paused for capacity.
## 0.6.4 (2026-09-30)
- The rate limit is a hundred at once, refilled at ten a second (it was 30, one every two seconds, which a page with a picture strip used up in one load: a few reloads and the stylesheet was refused). The files a page is made of, from portal's own disk, are not counted at all. `PORTAL_RATE_PER_SECOND` replaces `PORTAL_RATE_SECONDS`; no site set it.
## 0.6.3 (2026-09-30)
- Pages move the way their addresses do. Deeper in the address comes in from the right, back up comes in from the left, and a page at the same depth comes from below or above, with the index on top. The cards on screen leave as layers of their own, one after another, and the next page's cards arrive the same way. The old page stays on screen until the new one has loaded, where it used to go blank in between. Only transforms and opacity are animated, through the browser's View Transitions (`public/page-motion.js`, before the router). Browsers without them, and anyone who asks for reduced motion, navigate as before.
- A record that carries a picture, in a list with no buttons, is shown as a card: the picture, the first field as the heading, the rest under it, with no field names, state or time. Cards are shown in the order they were put up. On a desk, the same picture is a thumbnail.
- Trainer: `values` in a plan and `presents: true` on a need make a "who we are" card on the front door. The business's own statements are carried word for word, beside every record the need presents: the people who work there, entered from inside, each with a `picture` field (a file that only takes JPEG, PNG or WebP) that shows as their portrait. A public list keeps the form's field order, so the first field heads each row.
## 0.6.2 (2026-09-30)
- The header knows who is here: on a site with sign-in, a link top right to sign in, or the person's name and the way out. A page with a `slideshow` gets the wordmark as a bar of its own, the strip full width under it, and the question after.
- "My cases": `where: { field: email, equals: "{user.email}" }` lists the records that carry the signed-in person's own address, filled from the session and never from the caller; nobody signed in matches nothing. An attachment is fetched only through a list that shows its record, so a list of my cases opens my files and nobody else's.
- A stored file on a listed record shows as the name it was sent with and opens from the row, for whoever the list shows the record to. It used to show as its storage key, a string nobody could open.
- Form controls scale with the text around them (em, not rem): fields, pills, buttons and labels follow a site's body size. The date picker's calendar icon is the size of the text beside it, and the file picker's button takes the field's colours instead of the browser's.
- `KANIDM_GROUP_PREFIX`: a site on a Kanidm it shares with others keeps plain group names in its content; the prefix is put on when portal adds or removes a member, and the client's claim map takes it off.
- Fixed: `maps` never reached the browser (`serde(skip)`), so a page with a map drew it on the server and dropped it on hydration.
## 0.6.1 (2026-09-30)
- Trainer: `documents` in a plan. A text the site carries word for word (bylaws, terms) becomes a page of its own where every section is one alternative: its heading the card's, its paragraphs the card's words, from a markdown file beside the plan. No model touches it.
- `slideshow` on a page: a strip of pictures the full width of the screen under the question, `max_height` in svh, each picture with its caption laid over it. Swiper when the bundle has loaded, a sideways-scrolling row before. `/site/` serves `jpeg`, and lets a browser keep photographs for an hour.
- The release's bare binary is named `portal-x86_64-linux` (it was `portal` in 0.6.0 only). Gitea lists assets by name, and deploy scripts that take the first asset got the binary instead of the tarball.
## 0.6.0 (2026-09-30)
- One binary. The lint (uhhm/iris) and the trainer (uhhm/portal-trainer) are commands of `portal`: `portal serve` (the default), `portal lint`, and `portal plan`, `build`, `answer`, `rate`, `prefer`, `score`, `simulate`, `compare`, `report`, `generate`. Same source, same version, so the site, the lint and the trainer never disagree about what content means; both histories are merged in. The release attaches the bare `portal` binary beside the tarball, so a content repo's CI downloads it and runs `portal lint`. No more iris releases; the pins that exist keep working. The trainer's `plans/`, `intakes/`, `engines/`, `sectors/` and its reference prompt live here now; its `runs/` stay in uhhm/portal-trainer. Docs gained "Training a site" and "The lint".
## 0.5.11 (2026-09-30, tagged, never published)
The publish job failed at its lint step: iris, built against this tag, did not compile against the storylines change (the same two fixes that went into `src/lint/` when the lint moved in). Nothing was attached to the tag; 0.6.0 is the first release that ships storylines.
- Storylines (`src/content/variants.rs`, `docs/storylines.md`): any text a person reads may be a list, one entry per storyline, every list the same length; a visitor is given one storyline for the whole site (the `portal_storyline` cookie, a year) and reads it on every page and in every mail about their case. What the machine reads - a field's `name`, `options`, states, groups, paths - never varies. The lint refuses a list of another length. Records and answer events carry `storyline`, and `GET /report` gives counts per bucket, per storyline, per state, and nothing else.
## 0.5.10 (2026-09-30)
- The lint lets an invite form collect a required `phone` in place of a required `email`: memberships know a person by number first.
@@ -400,4 +456,4 @@ hosts now, since kasse's runner deploys its own instances.
| redoal.com | ergo | `app@redoal-portal` | v0.5.2 |
| westra.klingenbergbygg.no | kasse | `app@westra-portal` | v0.5.2 |
| portal.klingenbergbygg.no | kasse | `app@klingenberg-portal` | v0.5.2 |
| vel.klingenbergbygg.no | kasse | `tomtervel-portal-1` (podman, tomtervel/infrastructure) | v0.5.8 |
| vel.klingenbergbygg.no | kasse | `tomtervel-portal-1` (podman, tomtervel/infrastructure) | v0.6.0, memberships |
Generated
+1 -1
View File
@@ -3357,7 +3357,7 @@ dependencies = [
[[package]]
name = "portal"
version = "0.5.10"
version = "0.6.7"
dependencies = [
"anyhow",
"arc-swap",
+4 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "portal"
version = "0.5.10"
version = "0.6.7"
edition = "2021"
[lib]
@@ -11,7 +11,9 @@ leptos = { version = "0.8" }
leptos_meta = { version = "0.8" }
leptos_router = { version = "0.8" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# preserve_order: a rendered page is read by the people who own it, so
# the keys come out as written (name, then description), not sorted.
serde_json = { version = "1", features = ["preserve_order"] }
# Inline markdown for content descriptions (links, emphasis, code) -
# runs on both server and client renders, so not feature-gated.
pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] }
+8 -4
View File
@@ -11,14 +11,18 @@ engine does with it.
| [Content reference](content-reference.md) | Every key a content repo may write, and what it does. |
| [State machines](state-machines.md) | `aggregates.yaml`: stages, who moves a case, mail, deadlines, memberships. |
| [Access](access.md) | How the Cedar policy is compiled from content, and who may ask it what. |
| [Storylines](storylines.md) | The same site told several ways: lists of texts, one storyline per visitor, counted per storyline. |
| [Memberships](memberships.md) | Groups kept by portal itself: a membership as a case, a person as a phone number first, and the provider only saying who. |
| [Operations](operations.md) | Releasing, deploying, adding a site, environment variables. |
| [Training a site](training.md) | `portal plan` and `portal build`: a business in plain words becomes a content repo, held to the lint. |
| [The lint](lint.md) | `portal lint`: what a content repo's CI runs before anything reaches a site. |
| [Filesystem routes](design/filesystem-routes.md) | Why the `questions/` tree is the router. |
Two repos in the same family carry their own docs:
One repo in the same family carries its own docs:
- [uhhm/iris](https://project.uhhm.no/uhhm/iris) — the lint. Versioned
as portal and released by portal's publish job; it is the thing a
content repo's CI runs before anything reaches a site.
- [uhhm/gdo](https://project.uhhm.no/uhhm/gdo) — the mailer. Delivers
what content asked to be sent, and carries replies back.
The lint (once uhhm/iris) and the trainer (once uhhm/portal-trainer)
are commands of the `portal` binary since 0.6; their chapters are
above, and the trainer's runs stay in the old repo.
+7
View File
@@ -8,9 +8,15 @@
- [Content reference](content-reference.md)
- [State machines](state-machines.md)
- [Access](access.md)
- [Storylines](storylines.md)
- [Memberships](memberships.md)
- [Operations](operations.md)
# The trainer and the lint
- [Training a site](training.md)
- [The lint](lint.md)
# How it is made
- [Architecture](architecture.md)
@@ -19,3 +25,4 @@
---
[Changelog](changelog.md)
[The lint's changelog, to 0.5.11](lint-changelog.md)
+44 -5
View File
@@ -38,6 +38,11 @@ mail:
`mail.from` is required as soon as any state declares a mail.
Any text a person reads (`name`, `description`, `label`,
`placeholder`, a mail's `subject` and `body`, `consequence`,
`encouragements`) may be a list instead of one string: one entry per
[storyline](storylines.md), all lists the same length.
## A question
One YAML file is one page.
@@ -61,7 +66,7 @@ place: # this page is about somewhere
lat: 59.8938
lon: 11.0332
zoom: 15
name: Tomter
name: The town hall
alternatives: [ ... ]
```
@@ -71,6 +76,26 @@ nearest `_section.yaml`. `event` makes a page an occasion with a time;
opening any `type: location` field on the page there rather than on
the whole world.
### Pictures across the page
`slideshow` lays a strip of pictures under the question, the full
width of the screen: every picture as tall as the strip and as wide as
its own shape, swiped or arrowed through, its caption over its foot.
```yaml
slideshow:
max_height: 60 # svh; 60 unless set, between 20 and 100
slides:
- image: images/built/01.webp # a path in the content repo, or https://
caption: The canteen at the theatre, renewed
width: 3207 # the picture's own size, optional:
height: 1400 # holds its place before it has loaded
```
Pictures in the content repo are served from this origin under
`/site/`; `webp`, `avif` and `jpeg` may be kept by the browser for an
hour. Keep them web-sized: around 1400 pixels tall is plenty.
## An alternative
One choice. Never two actions behind one heading: if two things can be
@@ -202,14 +227,14 @@ The other half is a listing that asks for the children:
And the way there from a list: `link` puts a link on every listed
record to a page about it, with `{id}` for the record's id and
`{field}` for any of its fields. A notice on a public board links to
`/oppslag/{id}`, the dynamic page `/oppslag/[key]` whose form carries
`/notices/{id}`, the dynamic page `/notices/[key]` whose form carries
the notice's id back in with `value: "{key}"`:
```yaml
resource:
source: { kind: kv, bucket: oppslag }
source: { kind: kv, bucket: notices }
public: true
link: { to: "/oppslag/{id}", label: Jeg kan låne ut eller låne denne }
link: { to: "/notices/{id}", label: I can lend or borrow this }
```
## A resource
@@ -226,7 +251,7 @@ reads is never a client-supplied parameter.
where: { field: case, equals: "{key}" }
jq: ".[] | {name, url: .html_url}"
empty: Nothing decided yet.
link: { to: "/oppslag/{id}", label: Answer this } # a page per record
link: { to: "/notices/{id}", label: Answer this } # a page per record
transitions: # the desk's buttons
- { from: complete, to: on_hearing, label: Send it out }
```
@@ -238,6 +263,20 @@ A spec with neither `public: true` nor `requires_group` is
unreachable: reads fail closed, and mutations always need a group
whatever `public` says.
`where: { field: email, equals: "{user.email}" }` is "my cases": the
records carrying the signed-in person's own address, read from the
session. A file on such a record is theirs alone to open.
A record that carries a picture (a `type: file` field holding a JPEG,
PNG, WebP, AVIF or GIF) is shown rather than read when the list has no
`transitions`: a card with the picture on top, the first field as its
heading, and the other fields under it, with no field names, state or
time. The cards appear in the order the records were put up. That is
how a site shows the people who work there, or a gallery of what it
has built. On a desk, the same picture is a thumbnail that opens.
`accept: image/jpeg,image/png,image/webp` on the field makes a phone
send a JPEG whatever it keeps its photos as.
`states` and `where` narrow a listing. They matter most for a register
that is public by law — public about what was decided, not about what
was withdrawn — while the desk working the same bucket is a different
+9 -9
View File
@@ -32,11 +32,11 @@ Three things in the content decide who needs an account:
|---|---|---|
| `responsible: { name, contact }` on a page | the person answering for that question | an account, and a mail saying they are listed as responsible for asking it |
| `responsible: { name, contact, group }` | a group answering for it | nothing: the inbox is not a person; the group's members have the desk, and each of them may suggest changes to the page |
| `qualifies: styret` on a page or `_section.yaml` | members of that group | the pages and desks under it |
| `invite: { group: kasserer }` on a desk page | the desk's own group | the right to bring people into `kasserer` |
| `qualifies: board` on a page or `_section.yaml` | members of that group | the pages and desks under it |
| `invite: { group: treasurer }` on a desk page | the desk's own group | the right to bring people into `treasurer` |
The desk whose group may invite into the most groups is the site's most
privileged one; on a vel that is the board. Portal works that out from
privileged one; for an association that is the board. Portal works that out from
the content (see step 4).
## 2. Set up Kanidm for portal
@@ -58,7 +58,7 @@ $K group add-members idm_people_pii_read portal-onboarding
# One group per `qualifies:` in the content, managed by that account:
# adding a member to a group takes the right to manage it.
for g in styret kasserer trafikk; do
for g in board treasurer traffic; do
$K group create "$g" portal-onboarding
done
@@ -67,7 +67,7 @@ done
$K system oauth2 create portal "My site" https://site.example.no
$K system oauth2 add-redirect-url portal https://site.example.no/auth/callback
$K system oauth2 update-scope-map portal idm_all_persons openid profile email
for g in styret kasserer trafikk; do
for g in board treasurer traffic; do
$K system oauth2 update-claim-map portal groups "$g" "$g"
done
$K system oauth2 update-claim-map-join portal groups array
@@ -94,7 +94,7 @@ and on an empty Kanidm there is no desk anyone can open yet.
| `SEED_ADMIN_EMAIL` | the first person's address |
| `SEED_ADMIN_NAME` | their name, as it should appear (optional) |
| `SEED_GROUP` | a group to put them in, if not the most privileged one (optional) |
| `RESPONSIBLE_GROUP` | a group every responsible person joins, e.g. `redaktor` (optional) |
| `RESPONSIBLE_GROUP` | a group every responsible person joins, e.g. `editors` (optional) |
## 4. Start portal
@@ -151,7 +151,7 @@ A desk that lists the bucket offers the way back with a transition from
```yaml
resource:
source: { kind: kv, bucket: portal_invites }
requires_group: styret
requires_group: board
transitions:
- { from: open, to: done, label: Is in }
- { from: expired, to: open, label: Send again }
@@ -172,7 +172,7 @@ list, and whoever sits there takes it up and settles it:
```yaml
resource:
source: { kind: kv, bucket: portal_edit_suggestions }
requires_group: styret
requires_group: board
transitions:
- { from: open, to: discussed, label: Looking at it }
- { from: open, to: done, label: Changed }
@@ -187,7 +187,7 @@ where each one stands. A content repo that declares the bucket itself
in `aggregates.yaml`, with a `mail:` on a state, sends that instead.
Their group can also be the way into other tools. The vel's
`redaktor` group signs in to the project Gitea with the same account:
`editors` group signs in to the project Gitea with the same account:
a second OAuth2 client scoped to that group alone.
## When it does not work
+104
View File
@@ -0,0 +1,104 @@
# Changelog
One line per change, grouped by the release that shipped it. Newest
first. Each release names the portal tag it is built against.
## Unreleased
- `needs.yaml` may name the site's `tones`, one storyline each; the checks read the first storyline, which is what `build_questions` gives.
## 0.5.10 (2026-09-30) - portal v0.5.10
- Matches portal v0.5.10 (released by portal's publish job).
## 0.5.9 (2026-09-30) - portal v0.5.9
- Matches portal v0.5.9 (released by portal's publish job).
## 0.5.8 (2026-09-30) - portal v0.5.8
- Matches portal v0.5.8 (released by portal's publish job).
## 0.5.7 (2026-09-30) - portal v0.5.7
- Matches portal v0.5.7 (released by portal's publish job).
## Unreleased
- The effort budget counts what a person fills in: a `type: record` field (the case an answer is about, carried on the link) and a `hidden` preset are not asked and no longer count. An objection page whose form carried the application's id used to be one field over.
## 0.5.6 (2026-09-30) - portal v0.5.6
- Matches portal v0.5.6 (released by portal's publish job).
## 0.5.5 (2026-09-30) - portal v0.5.5
- Matches portal v0.5.5 (released by portal's publish job).
## 0.5.4 (2026-09-29) - portal v0.5.4
- Matches portal v0.5.4 (released by portal's publish job).
## 0.5.3 (2026-09-29) - portal v0.5.3
- Matches portal v0.5.3 (released by portal's publish job).
## 0.5.2 (2026-09-28) - portal v0.5.2
- Matches portal v0.5.2 (released by portal's publish job).
## 0.5.1 (2026-09-28) - portal v0.5.1
- Matches portal v0.5.1 (released by portal's publish job).
## 0.5.0 (2026-09-28) - portal v0.5.0
- Matches portal v0.5.0 (released by portal's publish job).
## 0.4.0 (2026-09-24) - portal v0.4.0
- Matches portal v0.4.0 (released by portal's publish job).
## 0.3.47 (2026-09-24) - portal v0.3.47
- Matches portal v0.3.47 (released by portal's publish job).
## 0.3.46 (2026-09-23) - portal v0.3.46
- Matches portal v0.3.46 (released by portal's publish job).
## 0.3.45 (2026-09-23) - portal v0.3.45
- Matches portal v0.3.45 (released by portal's publish job).
## 0.3.44 (2026-09-23) - portal v0.3.44
- Matches portal v0.3.44 (released by portal's publish job).
## 0.3.43 (2026-09-23) - portal v0.3.43
- Matches portal v0.3.43 (released by portal's publish job).
## 0.3.42 (2026-09-23) - portal v0.3.42
- Matches portal v0.3.42 (released by portal's publish job).
## 0.3.41 (2026-09-23) - portal v0.3.41
- Matches portal v0.3.41 (released by portal's publish job).
## 0.3.39 (2026-09-23) - portal v0.3.39
- Matches portal v0.3.39 (released by portal's publish job).
## 0.1.1 (2026-09-22) - portal v0.3.36
- `check --repo` fetches needs.yaml itself; the v0.1.0 tag never published (a cache permission on the runner, since fixed).
## 0.1.0 (2026-09-22) - portal v0.3.36
- First release: the lint moved out of portal (`question_lint` becomes
`iris check`, `needs_replay` becomes `iris replay`), with the
business-needs pass, the wording task export and scoring, and the
simulation model export. Portal is a library dependency pinned to
the release iris matches.
+54
View File
@@ -0,0 +1,54 @@
# The lint
The iris over a site. A content push is an incoming wormhole; nothing
comes through until it checks out.
```
portal lint --path questions # a local checkout
portal lint --repo https://project.uhhm.no/uhhm/questions
portal lint replay --path questions --nats nats://127.0.0.1:14222
```
It was its own binary, iris, until portal 0.6: the same code, released
as portal's twin. Now it is the `portal` binary's `lint` command, so a
content repo's CI downloads the release and runs it:
```yaml
- run: |
curl -sfL "https://project.uhhm.no/uhhm/portal/releases/download/$PORTAL_RELEASE/portal-x86_64-linux" -o portal
chmod +x portal && ./portal lint --path questions
```
`check` loads a content repo exactly the way the running site does,
validates it (every action lands on a page, every transition is one
the state machine allows, every recorded bucket is read back
somewhere), and then holds it to the business needs the repo declares
in `needs.yaml`, when it has one:
- a path of submissions gets each kind of visitor's answer into the
bucket it names, within a submission and required-field budget;
- the handling group holds a desk over that bucket, and every
finished state is reachable through the buttons it (and any
`also_moved_by` group) offers; no record strands on the way;
- every stage the business named is a state of the machine.
A need marked `planned` warns instead of failing. Exit status is the
verdict, so a content repo's CI is one line.
Beyond the verdict, `check` exports what a trainer needs to grade the
wording: `--needs-tasks` writes the personas as typed choice tasks
(`--skim` for headings only), `--needs-score` grades an engine's
answers, and `--needs-sim` writes a resolved model of the whole site.
`portal lint replay` runs simulated cases through the site's real aggregate
engine on a throwaway JetStream and reports every bucket by state;
`--report-only` takes the same scorecard from a live site's buckets.
See [Training a site](training.md) for what sits around those.
## Matching the site
The lint is the site: `portal lint` and `portal serve` are one binary
built from one source, so a content shape the site reads is a shape
the lint knows, at the same version. A content repo pins
`PORTAL_RELEASE` to what its site runs and lints with that release's
`portal`. The `IRIS_RELEASE` pins from before portal 0.6 keep working
against the iris releases that exist; nothing new is published there.
+1 -1
View File
@@ -33,7 +33,7 @@ Because it is a case, a desk lists it like any other bucket:
```yaml
resource:
source: { kind: kv, bucket: portal_memberships }
requires_group: styret
requires_group: board
transitions:
- { from: invited, to: removed, label: Withdraw }
- { from: active, to: removed, label: Take out }
+23 -7
View File
@@ -71,6 +71,7 @@ values.
| `KANIDM_URL`, `OAUTH2_CLIENT_ID`, `OAUTH2_CLIENT_SECRET` | sign-in |
| `PEOPLE_BACKEND` | `kanidm` or `memberships` (see [Memberships](memberships.md)); unset, Kanidm when `KANIDM_API_TOKEN` is set, memberships otherwise |
| `KANIDM_API_TOKEN` | invites and `grants:` through Kanidm |
| `KANIDM_GROUP_PREFIX` | for a Kanidm shared with other sites: the content's `kunder` is the group `<prefix>kunder` there, and the OAuth2 client's claim map gives it back to portal as `kunder` |
| `PHONE_COUNTRY` | the calling code a bare phone number gets, `+47` unless set |
| `OIDC_EXTRA_SCOPES` | scopes to ask the provider for besides `openid profile email`: `phoneNumber` for Vipps. Not for Kanidm, which denies a sign-in that asks for a scope the person does not hold |
| `SEED_ADMIN_EMAIL` or `SEED_ADMIN_PHONE`, `SEED_ADMIN_NAME`, `SEED_GROUP` | the first person in, invited once at start into the most privileged group (or `SEED_GROUP`) |
@@ -81,22 +82,31 @@ values.
| `GARAGE_*` | uploads |
| `MAPBOX_TOKEN` | map tiles, proxied; unset, maps are off |
| `GARAGE_*` (4) | attachments; see below. Unset, upload fields fail closed |
| `PORTAL_RATE_BURST`, `PORTAL_RATE_SECONDS` | the rate limit; see below |
| `PORTAL_RATE_BURST`, `PORTAL_RATE_PER_SECOND` | the rate limit; see below |
Mail is delivered by [gdo](https://project.uhhm.no/uhhm/gdo), a
separate unit on the same host reading the same NATS.
## Rate limiting
Every request passes a per-caller-IP limit before a session is loaded
or a handler is entered: a burst of 30, refilled one every two
seconds. A visitor filling in a form never reaches it (a page load
fetches several resources at once); a script does.
Every request that makes portal do something passes a per-caller-IP
limit before a session is loaded or a handler is entered: a burst of
100, refilled at ten a second. More than a hundred requests in ten
seconds is a script; someone reloading a page again and again stays
well inside it.
The files a page is made of, served from portal's own disk, are not
counted: the stylesheet and scripts under `/pkg`, the fonts, the
favicons, the vendored libraries. Refusing one of those is what turns
a reloaded page into an unstyled mess, and serving one costs next to
nothing. Anything that makes portal ask someone else is counted: a
content picture under `/site/` is fetched from Gitea, a map tile from
the map provider.
| | |
|---|---|
| `PORTAL_RATE_BURST` | how many requests at once, default 30 |
| `PORTAL_RATE_SECONDS` | seconds per refilled request, default 2 |
| `PORTAL_RATE_BURST` | how many requests at once, default 100 |
| `PORTAL_RATE_PER_SECOND` | requests refilled per second, default 10 |
Either set to `0` turns it off, for an instance behind something that
already does this. The caller is read from `X-Forwarded-For` or
@@ -130,6 +140,12 @@ then `GARAGE_S3_ENDPOINT`, `GARAGE_ACCESS_KEY`, `GARAGE_SECRET_KEY` and
`GARAGE_UPLOADS_BUCKET` in that instance's env. Unset, an upload field
fails closed rather than appearing to work and storing nowhere.
## The report
`GET /report` is public and answers with counts only: per bucket, per
[storyline](storylines.md), per state. It is what the trainer reads to
compare the storylines on what people did.
## The docs site
These pages are [portal.uhhm.no](https://portal.uhhm.no): `docs/` built
+16
View File
@@ -116,6 +116,22 @@ the same transition path, fires the same mail, and lands on
The unit is days and the sweep is hourly. This is a deadline, not a
job queue.
### leaves_after
```yaml
taken_down:
event: taken_down
leaves_after: { minutes: 10 }
```
How long a record stays in its bucket's lists once it has entered the
state, when that is not for ever. A card taken off the front page
leaves the desk's list ten minutes later instead of standing there
greyed out, and the ten minutes are the time to see what was just
done. Days, hours and minutes add up, and a sweep takes records out
once a minute. Nothing is decided and no mail goes. The record leaves
the lists, and the event log keeps it.
## attended_by
```yaml
+60
View File
@@ -0,0 +1,60 @@
# Storylines
The same site, told two ways, and counted.
Anywhere content says something to a person, it may say it in several
ways by giving a list instead of one string:
```yaml
name: Want to help out in the neighbourhood?
description:
- The work day, the spring fair and the committees need more hands. Say what you can do.
- The neighbours do most things themselves. Sign up here for whatever you fancy.
alternatives:
- name: [Join in, Sign me up]
consequence: [[Send], [Count me in]]
```
Each index is a *storyline*. A visitor is given one at their first
request, kept in a cookie (`portal_storyline`) for a year, and reads
that storyline on every page, in every button and in every mail the
site sends them about their case. A single string is every storyline.
## The rules
- **Same length everywhere.** Every list of texts in the content has
the site's arity, so a storyline never has a hole in it. The lint
refuses a list of another length and names it.
- **What varies is what a person reads:** `name`, `description`,
`label`, `placeholder`, `title`, a mail's `subject` and `body`, a
list's `empty` line, `consequence` and `encouragements` (those two as
lists of lists).
- **What the machine reads never varies:** a field's `name` (the stored
key), a select's `options` (the stored values), states, groups,
paths, buckets.
- **One storyline per site**, not per page. That is what makes it a
storyline rather than a scatter of variants: a warm front door leads
to a warm form and a warm mail.
- A signed-in person keeps the storyline they had as a visitor.
- A site that tells one storyline sets no cookie.
## What is counted
Every record and every answer event carries the storyline it came
from (`storyline` on `Answer` and on `portal.answers.submitted`). The
mail a case gets tells the same storyline, so a person who read the
warm front door is not thanked in the plain voice.
`GET /report` gives the counts, per bucket, per storyline, per state:
```json
{ "storylines": 2,
"buckets": { "requests": { "0": { "open": 3, "solved": 9 },
"1": { "open": 5, "solved": 14 } } } }
```
Storylines are assigned evenly, so those numbers are the comparison:
which words brought more people to send, and how their cases went. No
record, field, address or time leaves the site. The trainer reads this
(`portal report`) next to what its personas scored offline, and
the plan's `tones` are where the storylines are written.
+490
View File
@@ -0,0 +1,490 @@
# Training a site
A business describes itself in plain words: what it does, who comes to
it, what it keeps track of and through which stages, and who handles
what. The trainer, `portal plan` and `portal build`, turns that into a
working content repo: a question series for every role, the state
machines behind them, and a desk per handling role. No software is
written for the business; the only thing produced is content, and
every line of it is held to the lint (`portal lint`), which is the
same code as the site, at the same version.
The trainer was its own repo, uhhm/portal-trainer, until portal 0.6;
its runs (`runs/`, the lab notebook of every site trained so far)
stay there.
## Build: structure from the plan, words from the model
```
portal build --plan plans/contractor.yaml --out out/nordvik \
--lint "portal lint" --llm "MODEL=sonnet engines/claude.sh"
```
A `plan.yaml` is a needs spec that also says what each form collects
and, per need, `max_fields`: how many required fields that person
will tolerate, taken from what the business said about them, never
from the form. `build` refuses a form over its budget, and hands the
budget to the verifier, so the check still means something after
handover. Everything structural is derived from the plan with no
model involved: the state machines (read off `stages`: walk the line,
be turned down at any point, succeed only from the end, pass over
`skippable` stages), the front door, a followup page per need, a gated
directory per group with its desk and the pages only that group may
open, and every button the machine allows. The verifier accepts the
result by construction; what it still checks is the budget.
The model writes words only, one page at a time, into a JSON object
whose shape is fixed. Its strings are merged over built-in fallbacks
key by key, so a bad reply costs wording, never a working site. `--llm-for <path prefix>` points the model at some pages only
(`aggregates.yaml` for the mails alone); a reply in the wrong language
for the plan is refused, and a mail that lost the submitter's link
gets it back.
### Onboarding from the plan
`invites_by: [board]` on a plan, or `invited_by: [...]` on a group,
puts an invite form on the inviting group's desk for each group it may
fill, and a list of the invites sent. Portal does the rest (an account
in Kanidm, the group, a one-time credential link) through `invite:` on
the alternative. Every group with a desk invites into itself by
default.
### Rebuilding a live site
`--words-from <repo>` lifts the words a repo already has back into the
words map by what each card is (its bucket, the page it leads to, the
group it invites into), across the whole repo, so a rebuild keeps
hand-edited wording even when a card moves page (a door taken away, a
need brought onto the front door) and
adds only the new slots. Cards are matched by what they are (the
bucket they record into, the page they lead to, a field's name, the
group they invite into), not by position, so a rebuild that reorders
or reshapes a page still hands each card its own words; on uhhm.no
the live front door's three headings follow their buckets onto the
new page. `--words
<json>` overrides slots by page and may repeat, each file layered over
the last (the words a build used, then a round of hand changes);
`words.json` in the output is the words as used. See
`runs/tomtervel-invites-2026-09-23` and `runs/uhhm-2026-09-23`.
| Same contractor, same local model (nemotron 30B-A3B on ergo) | Free-form `generate` | `build` |
|---|---|---|
| A site the verifier accepts | never, in 6 rounds and 16 min | first try, 130 s |
| Held-out personas, with descriptions | - | 8 of 8 |
| Held-out personas, headings only | - | 7 of 8 |
The wording numbers are from the re-score of 2026-09-22, one task per
call (`runs/contractor-build-2026-09-21/rescore-2026-09-22/`). The
first score, all tasks in one prompt, said 8 of 8 on headings only;
the apprentice picking the building survey over "Join our carpentry
team" only showed once no other visitor was in the prompt.
For comparison, a Sonnet-class model writing everything free-form
scored 8 of 10 on headings only and silently dropped a stage the owner
had described. `build` cannot drop a stage: it never decides one. The
denominators differ: the `build` site gives the two crew personas a
one-option page, so they generate no task, and 8 of 8 is eight public
personas where the `generate` number is ten. Held out means held out
from the model: the plan's `who` and `wants` lines and the personas
were written by the same person about the same needs, and the fallback
heading is the need's `wants`, so the two are cousins.
### The front door opens modestly
A front door with more buttons than text leaves a visitor paralysed.
So the built front door opens with what the business does, in one or
two features and no button at all (`does:` on the plan, at most two,
each `for:` a need so it speaks to one role and is headed by what
that role gets); then a look-around card, things a visitor may
inspect before asking for anything (`shows:`, each a portal resource
block passed through verbatim, plus every public view the plan
opens); and only then the offers, as more alternatives on the same
page. Nothing is layered: doors still exist for a plan that wants
them, but a second tier is what this shape is there to avoid, and on
uhhm.no a flat front door with an opener routed better than the
doored one.
The house and its players: a role the opener invites in has to see
its win, and the machine has to give it something to do after it
sits down. `build` warns when a featured need gives the submitter
neither a move (`moves_by: {<stage>: [submitter, ...]}`) nor a public
view; a player with no move is a spectator.
### Doors: a first question before the forms
Five or six needs on one page is more than a visitor sorts through
(the full contractor plan had six). A plan can put public needs
behind `doors`: each door is one alternative on the front door
leading to a page of its own, where the needs that name it sit.
```yaml
doors:
- id: patients
who: someone with pain or an injury, or a patient who already has a time here
needs:
- id: new-patient
door: patients
...
```
The door's page is a nav page, public, holding the forms. The spec
gives such a need `max_steps: 2` and pins `via` to the door's heading,
so the verifier walks both pages. A door nobody is behind, a door on
an internal need, or a door named like a group is refused, and a
front door over five alternatives is warned about. The visitor is
scored on both pages: a persona who picks the wrong door is a
misroute on `/`, one who picks the wrong form is a misroute on the
door's page.
Cases with doors: `plans/physio.yaml` (a physiotherapy clinic,
patients and referrers), `plans/fotballklubb.yaml` (a football club,
in Norwegian, parents and helpers), `plans/hire.yaml` (a machine hire
yard, hiring and firms), and `plans/contractor-full.yaml` (three
doors over six public needs). Each has an intake under `intakes/` in
the business's own words and held-out personas.
### What a plan can say about a form and its readers
- `multiple: true` on a `select`: pick any number (portal renders
toggles). What a volunteer can do, which events, which committees.
- `groups:` at the top, a list of `{ id, label }`: the groups with a
name the public knows, such as a vel's committees. A select with
`options_from: groups` offers exactly those labels, so the
application form and the desks cannot drift apart.
- `watched_by: [public]`: an ungated read-only page of the bucket at
`/status/<bucket>`, linked from the followup page. Everyone sees
what was sent in and where it stands. `email` and `tel` fields, and
any field marked `private: true`, are projected away before it is
shown.
- `events: { open: applied, active: onboarded }` on a need: the event
name a stage is entered by, where the builder's default (the stage's
own name, `received` for the first) is not what a live site already
has. Portal replays every record by event name, so a rebuild of a
site that holds records keeps the names its aggregates.yaml has, or
every record vanishes from its desk. `plans/uhhm.yaml` rebuilds
uhhm.no this way.
- `mails: { <stage>: submitter | <address> }` on a need: who hears
when a case enters that stage, sent by portal the moment it moves
(portal 0.3.43, delivered by uhhm/gdo on the host). `submitter` goes
to the email the form collected, so the form must collect a required
`email`; an address is the treasurer, the board. The plan then needs
`mail: { from, reply_to }` at the top, the sender every mail carries
into `site.yaml`. The words model writes each mail's subject and
body (`aggregates.yaml` in the words map); the fallback says what
happened and, where the submitter has a move from that stage, the
link to make it.
- `stages_text: { <stage>: <words> }` on a need: each stage in the
plan's language, where the ASCII id will not do (`ikke_lost` reads
as English). Used by the fallback mails, the "what happens next"
line, the desk buttons' fallback labels, and written into needs.yaml
as `stage_words` so the desk score describes an outcome in the
site's own words. With them, the vel's desks score 26 of 26.
- `turned_down_from: [<stage>, ...]` on a need: the unfinished stages
a case can still be turned down from; omitted, every one. An
applicant is declined before they start and departs after, which
is what uhhm.no's live machine says and what two near-synonymous
desk buttons had been standing in for.
- `reached_from: { <stage>: [<stage>, ...] }` on a need: where a stage
is entered from, when the line a case walks does not say it. Two
shapes need it and nothing else does - a case SENT BACK to a stage it
was already past (a building application returned for the drawing it
was missing, after the hearing turned something up), and a GOOD ENDING
PARTWAY ALONG (an authority that changes its own decision while it is
looking at the appeal, rather than passing it up to the board). A
stage named there is entered from exactly those stages and nowhere
else, so saying where a refusal may come from also says where it may
not: an applicant may withdraw from anywhere, and be refused only once
the papers are in, which `turned_down_from` could not express because
it was one list for every bad ending at once. Found by replaying a
building authority's real cases through portal's engine, which
refused three legal paths and accepted two illegal ones until the
plan could say this; see runs/permits-2026-09-25/README.md.
- `attended_by:` on a need: who moves cases that no desk button moves,
an automation listening on the bucket's events, written into
aggregates.yaml as portal's own annotation for the reader.
## Plan: the intake, read by a model, checked by a person
```
portal plan --intake intakes/contractor.yaml --out out/nordvik \
--personas sectors/construction/needs.yaml \
--llm "MODEL=nemotron-3.5-lightning:30b-a3b engines/ollama.sh"
```
This is the one step where a model decides structure: which needs the
intake implies, the stages, who handles what, the form, the budget.
Its YAML is parsed and validated exactly as `build` will, the errors go
back to it, and what passes is written verbatim for a person to read
before building from it. Personas are never asked of this model; they
are attached from a file, and where their `need:` names an id the plan
does not have, `plan` says so and leaves the mapping to the reader.
`generate` (below) is the older path, a model writing pages free-form
against the lint. It is kept for the record of what it measured.
## How it works
```
intake (plain words)
│
▼ phase 1 frozen after this phase: the generator
needs.yaml ─────────────────────── may not weaken the spec to pass
│
▼ phase 2 ◄── iris findings, until it exits 0
aggregates.yaml + questions/** + desks
│
▼ phase 3 ◄── misroutes from a blind visitor model
wording
```
1. **Needs.** The intake becomes `needs.yaml`: one need per kind of
person and thing they want, including the roles inside the
business. Each names the bucket the answer lands in, the group that
handles it, the states that count as finished, and the effort the
visitor will tolerate.
2. **Structure.** Pages, state machines and desks are generated, then
revised against the lint, `iris check`, until every need is met:
a path within budget, a desk held by the right group, every
finished state reachable, no record stranding. The page-writing
model sees the needs and never the personas.
3. **Wording.** A separate model plays each persona, blind, first with
headings only and then with descriptions. A misroute is a wording
defect and goes back to the generator. A rewrite that breaks
structure is reverted.
Model output is only ever written to `aggregates.yaml`, `site.yaml`
and `questions/**.yaml` inside the output directory.
```
portal generate --intake intakes/contractor.yaml --out out/nordvik \
--lint "portal lint" --llm engines/ollama.sh
portal answer --tasks tasks.jsonl --llm engines/ollama.sh > answers.jsonl
```
`answer` puts one task per call to the visitor model, with the options
shuffled per task and the call seeded from the task id: no visitor
sees another visitor's situation, a heading's place on the page cannot
carry the answer, and a rerun on the same site is the same experiment.
The earlier runs under `runs/` answered all tasks in one prompt.
The verifier is uhhm/iris, not code in this repo: it
reads portal's own content types and ships in every portal release, so
a generated repo's CI keeps enforcing its needs after handover.
## LLM backends
A backend is any command that takes a prompt on stdin and prints text.
| Backend | Use |
|---|---|
| `engines/ollama.sh` | Local Ollama. `MODEL=qwen3:8b` answers a task in about two seconds on ergo's GPU and is the default visitor. Generation wants a larger model (`MODEL=qwen3.6:27b`), which runs mostly on CPU there. |
| `engines/claude.sh` | Claude through Claude Code's own login (a Max or Pro subscription), no API key. `MODEL=sonnet` or `opus`, `EFFORT=low` by default. It drops any `ANTHROPIC_API_KEY` from the environment, because a key outranks the login and a stale one fails every call. Log in once with `claude auth login`. |
| `engines/anthropic.sh` | The Anthropic API, given a working `ANTHROPIC_API_KEY` from the Console. That is separate, prepaid billing; a subscription does not cover it. |
| `engines/mailbox.sh` | Writes each prompt to a directory and waits for a reply file: drive the generator from an agent session, or by hand. |
The visitor and the generator should be different models. A model
grading its own wording agrees with itself.
## The onboarding site
`portal-portal/` is the front end of this: a portal content repo whose
front door is the intake interview. A submission lands in
`onboardings` (`open → drafted ⇄ revising → live | declined`) and is
worked from an owners' desk. Today the desk step is a person running
`generate` and sending the link; the intake record already carries
every field the generator reads, so the step that remains is a
listener on `portal.answers.submitted` that runs it and pushes the
draft to a new repo. It passes its own `needs.yaml`.
## The whole card, not the heading
A visitor never sees a bare heading and description. Portal renders a
card: a button, an encouragement, one or more sections each with an
icon, a title and a line of guidance, and the fields with their
labels and placeholders. Since 2026-09-23 the builder fills all of it
and the scorers read all of it.
- **Slots.** Beside the heading and description, each form alternative
gets a button, an encouragement, an icon, a form title and guidance
line, and a placeholder per field. A door gets an icon and a "for
whom" line. Icons are picked from a fixed list of Iconify lucide
names; anything else is dropped.
- **Context from the plan.** Every form alternative also carries two
sections built from what the plan already knows, before the form:
what happens next (the stages, in order, as one sentence) and who
reads it (the handling group and the contact). Their fallbacks are
true before a model has written a word; the model rewords them.
- **Scoring.** `answer --repo <content dir>` shows the visitor each
option as its whole card (headings-only tasks stay headings only).
`rate --repo` does the same and asks a fourth question, "where": do
you know where you are, who this is for, and what the button does.
All four are controlled against the gutted twin.
## Scoring a built site
```
portal score --site out/nordvik --out out/scored \
--iris /var/local/cargo-target/release/iris \
--llm "MODEL=qwen3:8b engines/ollama.sh"
```
One command for the whole grading, which every run under `runs/`
before 2026-09-23 carried as its own `score.sh`: iris writes the
visitor tasks and the simulation model, the blind visitor answers
them with descriptions and with headings only, iris scores the
answers (the misroutes are printed), and `rate` reads the cards. The
two routing numbers land in `summary.json`, the rating in
`rated/rate.json`. The pieces still run alone: `answer --tasks` for
one visitor model against tasks iris wrote, and:
```
iris check --path out/nordvik/questions --needs-sim model.json
portal rate --model model.json --out out/rated --repo out/nordvik \
--llm "MODEL=qwen3:8b engines/ollama.sh"
```
Four yes-or-no questions per persona (which option is mine, where am
I and what does the button do, what will I be asked, what happens
after I send it), each also put to a gutted
twin of the page with headings, descriptions, the form and the
followup removed. A question the twin still gets a yes on is not
measuring the page, and `rate` says which. The followup page is read
from the repo (`--repo`); without it "what happens next" is reported
as not measured rather than as zero. LIX is over the prose only
(question, descriptions, followup): headings and labels are not
sentences and would pull every page down to "very easy". The
`rate.json` in `runs/contractor-build-2026-09-21/` predates this and
its `asked` and `next` columns are the old, pinned ones.
`rate --repo` also scores the **desks**, the inside of the business,
which reads button labels and nothing else: for every desk and bucket
with two or more buttons, a worker is told what has just happened to
a case (in the state's own words, never the label's) and picks the
button among the ones a row in that state shows, in a rotated order.
Scored per desk as right of total, with what each miss was mistaken
for. Measured on 2026-09-24 on the live vel: 24 of 26, the misses
one button each on the neighbour-help desk and the notice board. Two
limits: the outcome is put from the state id, and a Norwegian id with
its accents stripped (`ikke_lost`) reads as English even to a strong
model; and a first version that offered every button of the bucket,
not the row's, scored the same desks 17 of 26 and sent a rewrite
chasing an instrument fault. A desk that scores full marks has labels
a stranger to the business could press right.
`prefer` has a positive control on record
(`runs/tomtervel-opener-2026-09-23`, "The friendliness judge"): the
live vel front door against a bureaucratic twin, friendlier 9 of 10
to the live page and 0 to the twin. A pair that comes back "no
preference" throughout is alike in tone, not an instrument that
cannot see; and the rejected door rewrite that was judged clearer on
5 of 10 needs routed worse across three seeds, so clarity as judged
and routing as measured are different things, and routing decides.
## Measured so far
**Generated: a building contractor** (`runs/contractor-2026-09-21/`),
from `intakes/contractor.yaml`, a Sonnet-class model generating.
- Phase 1 derived six needs from the owner's prose, including one
nobody asked for: a project manager logging a phone enquiry, taken
from "enquiries arrive by phone, email and text and get lost".
- Phase 2 was green on the first round: 14 files, four state machines
(`enquiries: open → quoted → won | lost`, `subcontractors` with an
`awaiting_papers` loop, `applicants`, `site_issues`), two desks.
- Phase 3, its own personas: 10 of 10 in both modes. That number is
flattering, because in that run the pages were written with the
personas in view. Against ten **held-out** personas, with qwen3:8b
as the visitor:
| Visitor could read | Routed right |
|---|---|
| Headings and descriptions | 10 of 10 |
| Headings only | 8 of 10 |
A scaffolding firm asking "how do I get to do jobs for you?" chose
"Ask about working with us" (the hiring door). An attic conversion
chose "Get someone to look at a building". The generator has since
been changed to hide personas from the page-writing phase.
**Built: the same contractor from a plan** (`runs/contractor-build-2026-09-21/`),
nemotron writing words only, and re-scored one task per call the day
after (`rescore-2026-09-22/` in it): 8 of 8 with descriptions, 7 of 8
on headings alone, the miss being an apprentice bricklayer reading
"Join our carpentry team" as not for them. `rate` on the same site,
with the followup shown and every question controlled, passes its
controls and puts the pages at LIX 18 to 35.
**Built behind doors, 2026-09-22.** Five plans with a first question
before the forms, each built and then scored by qwen3:8b one task per
call, against held-out personas. Behind a door a persona is asked
twice, on the front door and on the door's page.
| Case | Words by | With descriptions | Headings only | Notes |
|---|---|---|---|---|
| Machine hire (`hire`) | nemotron | 10 of 10 | 10 of 10 | doors that ask a question the visitor already knows the answer to |
| Physio clinic (`physio`) | nemotron | 8 of 10 | 9 of 10 | "Book your first appointment" fails a daughter booking for her mother |
| Football club, Norwegian (`fotballklubb`) | nemotron | 14 of 16 | 11 of 16 | three parents walk past "Er det på tide å melde inn?" |
| Football club, Norwegian | Claude Sonnet | 13 of 16 | 12 of 16 | better sentences, same driver/sponsor blur |
| Whole contractor (`contractor-full`) | nemotron | 18 of 22 | 15 of 22 | "Apply to work with us" and "Find a job with us" cross over for all four |
| Tomter Vel, Norwegian (`tomtervel`), first plan | Claude Sonnet | 25 of 30 | 22 of 30 | "utstyr" for a swing, hearing input behind the wrong door |
| Tomter Vel, plan revised 2026-09-23, whole card | Claude Sonnet | 31 of 38 | 30 of 38 | committees as groups, public lists, hearing input on the front door |
Each run's README names the misroutes and what in the plan or the
heading caused them. A stronger word model did not route better on
the one plan built with both: routing is decided by which distinctions
sit on one page, and the visitor grades that the same whoever wrote
the words.
**Planned: the contractor intake read by a local model**
(`runs/contractor-plan-2026-09-22/`), nemotron, one round, 41 s. The
plan passed every check `build` makes and a reader finds three
structural misses in it the checks cannot: the crew's report made
public, the "papers missing" stage dropped, and no need for the
project manager logging a call. The person reading the plan is not
optional.
**Existing site: uhhm.no** (`runs/uhhm-2026-09-21/`), eight tasks.
| Visitor model | With descriptions | Headings only |
|---|---|---|
| small LLM, blind | 7 of 8 | 5 of 8 |
| qwen3:8b (Ollama) | 7 of 8 | 7 of 8 |
| granite4.1:8b (Ollama) | 7 of 8 | 6 of 8 |
All three send a paying client through **"Work happens through
dialogue, not tickets"**, the collaborator door. Different models,
same defect: that is what a wording problem looks like.
**The noise floor, 2026-09-23** (`runs/spread.sh`, `answer --seed`).
The same tasks answered by qwen3:8b with four seeds (0 is the run
every score above used):
| Run | With descriptions | Headings only |
|---|---|---|
| uhhm.no round 6, 15 tasks | 11, 10, 10, 10 | 12, 12, 7, 7 |
| Tomter Vel with the opener, 38 tasks | 30, 29, 29, 31 | 26, 24, 26, 23 |
With descriptions the visitor is steady: one task in fifteen, two in
thirty-eight. On headings alone it is not: five of fifteen on uhhm.no
between seeds, three of thirty-eight on the vel. A headings-only
difference smaller than that is the visitor's mood. Compare
descriptions-mode scores; read headings-only as a sanity check, and
run several seeds before believing it.
Small numbers, one run each. Leads, not measurements.
## What else is here
- `skill/SKILL.md` - the same procedure for an agent or a person
working by hand.
- `sectors/` - needs specs to start from. `construction/` doubles as
the held-out persona set above.
- `generator/reference.md` - everything the generating model is told
about portal content. When the lint rejects something the reference
did not warn about, the fix belongs there.
## Toward a trained model
Nothing here trains weights yet. What would make it possible is
accumulating: every run leaves the intake, the needs, the pages at
each revision and the scores. With a fast local visitor as the scorer,
generating many variants per need and keeping the winners is cheap,
and those winners are the fine-tuning set for a small generator. The
verifier has to be trusted before any of that: a generator trained
against a judge that is often wrong learns the judge.
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# LLM backend for portal-trainer: prompt on stdin, text on stdout.
# Needs ANTHROPIC_API_KEY, curl and jq. MODEL and MAX_TOKENS override.
set -eu
: "${ANTHROPIC_API_KEY:?set ANTHROPIC_API_KEY}"
jq -Rs --arg model "${MODEL:-claude-sonnet-5}" --argjson max "${MAX_TOKENS:-16000}" \
'{model: $model, max_tokens: $max, messages: [{role: "user", content: .}]}' |
curl -sS --fail-with-body --max-time "${TIMEOUT:-600}" https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" -H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" --data-binary @- |
jq -er '[.content[] | select(.type == "text") | .text] | join("")'
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# LLM backend for portal-trainer on Claude Code's own login (a Max or
# Pro subscription): prompt on stdin, text on stdout. No API key
# needed: an ANTHROPIC_API_KEY in the environment would outrank the
# login, so it is dropped here. Log the CLI in once with
# `claude auth login`; `claude auth status` shows what it uses.
# MODEL is an alias or id (sonnet, opus, claude-sonnet-5); EFFORT is
# low, medium or high. Not --bare: that mode skips the stored login.
#
# The generator's SEED and TEMPERATURE hints cannot be honoured;
# FORMAT=json is turned into an instruction.
set -eu
unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN CLAUDECODE CLAUDE_CODE_ENTRYPOINT
prompt=$(cat)
if [ "${FORMAT:-}" = json ]; then
prompt="$prompt
Reply with the JSON object only, no prose, no code fences."
fi
printf '%s' "$prompt" | claude -p --model "${MODEL:-sonnet}" --effort "${EFFORT:-low}" \
--output-format text --permission-mode dontAsk --no-session-persistence \
--tools ""
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# LLM backend that hands each prompt to whoever watches $MAILBOX:
# prompt-N.md goes out, the reply is read from reply-N.md. For driving
# the generator from an agent session, or by hand.
set -eu
: "${MAILBOX:?set MAILBOX to a directory}"
mkdir -p "$MAILBOX"
n=$(( $(ls "$MAILBOX" | grep -c '^prompt-' || true) + 1 ))
cat > "$MAILBOX/prompt-$n.md"
until [ -s "$MAILBOX/reply-$n.md" ]; do sleep 2; done
sleep 1
cat "$MAILBOX/reply-$n.md"
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# LLM backend for portal-trainer on a local Ollama: prompt on stdin,
# text on stdout. MODEL, OLLAMA_HOST, NUM_CTX and TIMEOUT override.
# Thinking is off: the generator wants files, the answerer wants JSONL.
# The simulator sets SEED (so the same case replays the same way
# against two versions of a site), FORMAT=json and TEMPERATURE.
set -eu
jq -Rs --arg model "${MODEL:-qwen3:8b}" --argjson ctx "${NUM_CTX:-32768}" \
--argjson temp "${TEMPERATURE:-0.2}" --arg seed "${SEED:-}" --arg format "${FORMAT:-}" \
'{model: $model, stream: false, think: false,
options: ({num_ctx: $ctx, temperature: $temp}
+ (if $seed == "" then {} else {seed: ($seed | tonumber)} end)),
messages: [{role: "user", content: .}]}
+ (if $format == "json" then {format: "json"} else {} end)' |
curl -sS --fail-with-body --max-time "${TIMEOUT:-1800}" \
"${OLLAMA_HOST:-http://127.0.0.1:11434}/api/chat" \
-H "content-type: application/json" --data-binary @- |
jq -er '.message.content'
+28
View File
@@ -0,0 +1,28 @@
# Held out from every model that writes words. Each is one real person
# arriving with one real thing, in their own register: a homeowner who
# has never read a regulation, a firm that files for a living, an
# inspector on a roof in the wind, a politician reading a bundle.
personas:
- { id: garage-owner, need: pre-application-meeting, text: "We want to put a double garage where the old shed is. Before I pay an architect I'd like to know whether you'll even allow it, because the neighbour says it's too close to the road." }
- { id: shop-to-flats, need: pre-application-meeting, text: "I own the old grocery on Torget and want to make four flats out of it. There are a lot of questions - parking, fire, the facade is listed. Can we sit down with someone?" }
- { id: firm-files-extension, need: permit-application, text: "We are the responsible applicant for an extension at Bjorkeveien 14. Drawings, site plan and the neighbour notices are all ready. We file maybe forty of these a year." }
- { id: owner-small-window, need: permit-application, text: "I want to put a dormer window in my roof. The man at the counter said I have to apply even though it's small." }
- { id: missing-drawings, need: permit-application, text: "You wrote that our section drawing is missing and the case is on hold. I've got it here now, where do I send it so the clock starts again?" }
- { id: too-close-to-boundary, need: exemption-request, text: "The garage ends up one and a half metres from the boundary and the plan says four. We are asking you to allow it anyway - the ground falls away steeply everywhere else on the plot." }
- { id: neighbour-view, need: objection, text: "I got a notice about the extension at number 14. It takes the afternoon sun off my entire terrace and I want that on the record before you decide anything." }
- { id: neighbour-parking, need: objection, text: "The flats they want to build in the old grocery have four parking places for four flats and everyone here already parks on the street. I object." }
- { id: road-authority, need: hearing-answer, text: "Regarding your case 2026/418: the access onto the county road is within the sight line and we cannot accept it as drawn. Our formal reply is attached." }
- { id: fire-service, need: hearing-answer, text: "We have looked at the conversion on Torget. We have no objection provided the stairwell is upgraded. Reference your case 2026/501." }
- { id: refused-applicant, need: appeal, text: "You refused our exemption on the ninth. We don't accept the reasoning - you've allowed the same thing twice in the same street. We're appealing." }
- { id: neighbour-appeals, need: appeal, text: "You approved the extension next door even though I objected. I'm appealing the decision. What do I need to send?" }
- { id: board-member, need: appeal, text: "I sit on the appeals board. I need the case, our own decision, and what the neighbours wrote, before Tuesday." }
- { id: inspector-on-roof, need: inspection-finding, text: "I'm up on the scaffold at Bjorkeveien. The fire wall isn't built to the drawing at all. I've got gloves on and it's blowing. I want this logged before I climb down." }
- { id: inspector-all-good, need: inspection-finding, text: "Been out at Torget. Everything is as approved. Nothing to report but I have to record that I was there." }
- { id: firm-wants-certificate, need: completion-request, text: "The work at Bjorkeveien 14 is finished and inspected. We're asking for the completion certificate so the owners can get their mortgage released." }
- { id: wants-to-move-in, need: completion-request, text: "The house is done apart from the outside steps, which we can't pour until spring. The family has sold their flat. Can we get a temporary permission to move in?" }
- { id: something-behind-fence, need: illegal-building-report, text: "There's a large structure going up behind the fence at Solbakken 7. Nobody has had a notice about it and it's been going on for two weeks." }
- { id: owner-explains, need: illegal-building-report, text: "I got your letter about the terrace. I genuinely did not know it needed an application, it's been there since we moved in. What happens now?" }
- { id: new-firm, need: firm-approval, text: "We are a three-person architecture firm that has just started. We want to be approved so we can file applications for our clients in your municipality." }
- { id: firm-insurance-lapsed, need: firm-approval, text: "You wrote that our liability insurance certificate has expired. We have renewed it, here it is." }
- { id: counter-phone-call, need: log-counter-enquiry, text: "A woman rang about the case behind her house. Wants to know where it stands. I'm at the counter and there's a queue - I need to write it down and send it to whoever has that case." }
- { id: where-is-my-case, need: case-status-enquiry, text: "I sent in my application five weeks ago and I've heard nothing. Is anyone looking at it? Is it in the six weeks with the neighbours or is it waiting on me?" }
+91
View File
@@ -0,0 +1,91 @@
# A building authority's intake: the hardest sector the trainer has
# been given. Cases that pause and resume, cases that belong to other
# cases, a decision two roles sign, a deadline nobody in the building
# controls, and an appeal that reopens something already finished.
# Written the way the department head would write it, in plain words.
business: Vestmark kommune - Building and Planning
contact: { name: Solveig Hauge, email: byggesak@vestmark.example }
language: en
what_we_do: >
We are the building authority for a municipality of twenty-one
thousand people. Anyone who wants to build, demolish, divide a
property or change what a building is used for has to come to us
first. We check the drawings against the zoning map and the building
regulations, we let the neighbours and the other authorities have
their say, and then we approve or refuse. We also decide exemptions
from the zoning rules, we inspect what is actually built, we sign off
finished work, and we deal with building that was never applied for.
who_comes_to_us: >
Homeowners who want a garage, an extension or a new window, and who
have never read a regulation in their life. Architects and
engineering firms who file on behalf of owners; they have to be
approved by us before they may file anything. Neighbours who got a
notice in the post and do not agree with what is planned next door.
The other authorities we are obliged to ask: the road authority, the
fire service, the heritage office, the county. People who ring to say
something is going up behind their fence without permission. And
anyone who wants to sit down with us before they spend eighty
thousand on drawings.
what_we_keep_track_of: >
Pre-application meetings: someone asks for one, we find a time, we
meet, and we write down what we told them so they can hold us to it.
Applications: they arrive, someone checks whether the papers are all
there, and if something is missing we write and ask for it, and the
twelve-week clock stops until they answer. Often we have to ask
twice. When it is complete we send it out to the neighbours and to
the agencies and wait six weeks. Then a case officer writes a
recommendation, and the head of section signs the decision: approved,
approved with conditions, or refused. People can withdraw at any
point, and quite a few do once they hear from the neighbours.
Exemptions: if what someone wants breaks the zoning rules they can
ask for an exemption. It rides along with the application but it is a
decision of its own, and we are not allowed to grant one before the
county has been asked.
Objections: a neighbour who got a notice writes to us within the
hearing period. Each objection belongs to an application. We register
it, the applicant gets to answer it, and the case officer has to
address every single one in the decision, by name.
Hearing answers: we ask an agency, they answer, or they do not, and
when the deadline has passed we go on without them.
Appeals: for three weeks after a decision anyone with an interest can
appeal it. We go through it ourselves first, and if we change our own
mind that is the end of it. If we do not, it goes to the appeals
board, who meet once a month and either uphold us or overturn us.
Inspections: we pick cases and go and look, on site. Either it is as
approved, or we write up what is wrong and set a date for it to be
put right, and then we go back.
Finishing: when the work is done the firm asks for a completion
certificate. If they want to move in before everything is done they
can ask for a temporary permission instead. We check what was
inspected and what is still outstanding before we sign anything.
Illegal building: someone reports it, we go and look, we write to the
owner and they have to explain themselves, and then they either apply
for it properly, take it down, or we fine them weekly until they do.
Approved firms: a firm sends us their registration, their insurance
and what they are qualified for, we check it, and then they are on
the list and may file applications.
who_is_involved: >
The front desk logs what comes in over the counter and on the phone,
and keeps the archive. Four case officers carry the cases. The head
of section signs every decision and every exemption; a case officer
may not sign their own. Two inspectors are out on site most of the
week and write up what they find on a phone in a cold wind. The
appeals board is seven elected politicians who meet on the third
Tuesday of the month and read what we send them. The agencies are
outside the building altogether and only ever answer hearings. The
approved firms file applications and answer objections on behalf of
their clients.
what_slows_us_down: >
The twelve-week clock, and the fact that stopping it and starting it
again is done by hand in a spreadsheet. Applications that arrive
missing half the drawings. Objections that come in on paper and get
stapled to the wrong case. Neighbours ringing to ask what is
happening with the case behind their house, which we are obliged to
tell them and which takes ten minutes every time. Agencies that never
answer at all. And nobody outside this building can see a case
without asking us for it.
+44
View File
@@ -0,0 +1,44 @@
# An intake as the owner of a small building contractor would fill it
# in: plain words, no portal vocabulary. These are the fields the
# onboarding site asks for.
business: Nordvik Bygg
contact: { name: Ingrid Nordvik, email: ingrid@nordvikbygg.example }
language: en
what_we_do: >
We are twelve people. We survey old buildings, draw up rehabilitation
plans, handle the permit application, and do the building work with
our own carpenters plus subcontractors for electrical, plumbing and
scaffolding.
who_comes_to_us: >
Housing boards and private owners who have a problem with a building
and want someone to look at it. Owners who already know what they
want built and need drawings, a permit and a price. Trade firms who
want to be on our list of subcontractors. Carpenters and apprentices
asking if we are hiring.
what_we_keep_track_of: >
Enquiries: they come in, we go and look at the building, we send a
quote, and then we either win it or lose it. Sometimes it is simply
not for us and we say so straight away.
Subcontractors: they apply, we check their company registration,
trade approval and insurance. Often papers are missing and we have to
ask again. Then they are approved or turned down.
Job applications: we read them, invite some to an interview, and hire
or decline.
Things that go wrong on site: a hazard, a near miss, wrong materials
delivered. Someone reports it, the safety officer decides what is
done about it, and closes it when it is fixed.
who_is_involved: >
Two project managers handle enquiries, subcontractors and hiring.
One safety officer handles everything reported from site.
The crew, ours and the subcontractors' people, are the ones on site
who report things. They are on their phones, with gloves on, and
will not fill in a long form.
what_slows_us_down: >
Enquiries arrive by phone, email and text and get lost. We never know
which subcontractors have valid papers. Site problems get mentioned
at lunch and forgotten.
+38
View File
@@ -0,0 +1,38 @@
# Slik lederen i en fotballgruppe ville fylt det ut.
business: Lia IL Fotball
contact: { name: Kari Lien, email: kari@liail.example }
language: no
what_we_do: >
Fotballgruppa i et idrettslag på bygda. Rundt hundre og tjue unger
fra seks til sekstenår, fordelt på lag etter årskull. Alt drives av
foreldre på fritida: trenere, lagledere, en kasserer og et styre.
who_comes_to_us: >
Foreldre som vil ha ungen med på et lag. Foreldre som sliter med
treningsavgiften og vil dele den opp eller slippe. Folk som vil
hjelpe til, som trener, lagleder, sjåfør eller på dugnad. Bedrifter
i bygda som vil sponse.
what_we_keep_track_of: >
Innmeldinger: en forelder melder inn, treneren på årskullet
godkjenner at det er plass, kassereren ser at avgiften er betalt.
Noen trekker seg underveis.
Avgiftssaker: noen ber om å dele opp eller slippe avgiften; styret
vurderer og sier ja eller nei.
Frivillige: noen tilbyr seg, styret tar kontakt og plasserer dem der
det trengs, eller takker nei.
Sponsorer: en bedrift melder interesse, vi tar en prat, og det blir
en avtale eller ikke.
Ting på banen: lys som ikke virker, mål som er ødelagt, drakter som
mangler. Trenerne melder fra, styret tar tak i det og ordner det.
who_is_involved: >
Trenerne godkjenner innmeldinger på sitt årskull og melder fra om
banen. Kassereren følger opp betaling. Styret tar frivillige,
sponsorer, avgiftssaker og alt som gjelder anlegget.
what_slows_us_down: >
Alt går i en gruppechat og et regneark. Trenerne vet ikke hvem som
har betalt, kassereren vet ikke hvem som er godkjent, og en som
tilbød seg å kjøre i høst fikk aldri svar.
+38
View File
@@ -0,0 +1,38 @@
# An intake as the owner of a machine hire yard would fill it in.
business: Fjellstad Hire
contact: { name: Ola Fjellstad, email: ola@fjellstadhire.example }
language: en
what_we_do: >
We hire out machines: mini diggers, lifts, compactors, generators,
that kind of thing. A counter with two people, a yard with three who
deliver, collect and fix, and me in the office doing accounts and
the business customers.
who_comes_to_us: >
Private people who need a machine for a weekend and have often never
driven one. Building and landscaping firms who need something on a
site from a date for a period. Anyone whose hired machine has
stopped working while they have it. Firms who hire often and want
an account so they can send anyone to collect and get one invoice a
month.
what_we_keep_track_of: >
Hires: someone asks, the counter reserves it, the yard hands it out
or delivers it, and the yard takes it back. Some are cancelled
before they go out.
Breakdowns: a machine stops during a hire; the yard takes it on and
either fixes it on site or swaps it.
Account applications: a firm applies, I check the company and its
credit, and it is approved or turned down.
Damage on return: the yard finds damage when a machine comes back; I
either invoice the customer or write it off.
who_is_involved: >
The counter handles hires. The yard handles breakdowns and the
handing out and taking back. The office does accounts and damage.
what_slows_us_down: >
The yard finds out about breakdowns from whoever picks up the phone.
Damage found on return is written on a whiteboard and half of it is
never invoiced.
+42
View File
@@ -0,0 +1,42 @@
# An intake as the manager of a physiotherapy clinic would fill it in.
business: Bakken Fysioterapi
contact: { name: Marit Bakken, email: marit@bakkenfysio.example }
language: en
what_we_do: >
Six physiotherapists and a receptionist. People come to us with
pain, injuries and after operations; we assess them and treat them
over a course of sessions. Some come on their own, some are sent by
a GP or a hospital, and some have insurance that pays if the insurer
approves the course first.
who_comes_to_us: >
People with something that hurts who want to see the right
therapist. Patients who already have a time and need to move or
drop it. GPs and hospital wards sending us someone, who want to
hear how it went. Insurers, through us, when a course has to be
approved before it starts.
what_we_keep_track_of: >
Requests for a first appointment: they come in, we offer a time with
a therapist who suits, and it is either booked or they go elsewhere.
Cancellations: someone can't come; we either find them a new time or
give the slot to someone waiting.
Referrals: a doctor sends someone, we accept it, book them in, treat
them, and send the doctor a report at the end. Sometimes we send it
back because it isn't something we treat.
Insurance approvals: for some patients we have to ask the insurer
before we start; we send the request and it comes back approved or
refused.
No-shows: someone doesn't turn up and doesn't call. The receptionist
rings them and either rebooks or, after a couple of times, closes it.
who_is_involved: >
The receptionist handles every request, cancellation, referral and
approval. The therapists treat and write the report back to the
doctor, and they are the ones who notice a no-show.
what_slows_us_down: >
Referrals, cancellations and insurance approvals all go through one
inbox that only the receptionist understands. Therapists tell her
about no-shows in the corridor and they get forgotten.
+48
View File
@@ -0,0 +1,48 @@
# En fiktiv norsk rehabiliteringsentreprenør, inspirert av hva
# Klingenberg Bygg driver med: tilstandsrapporter, prosjektering,
# byggesøknader og utførelse på eldre murgårder. Skrevet slik eieren
# ville sagt det, uten portal-ord.
business: Åsrud Bygg og Rehabilitering AS
contact: { name: Marte Åsrud, email: marte@asrudbygg.example }
language: "no"
what_we_do: >
Vi er fjorten ansatte og jobber mest med eldre murgårder og
trehus. Vi lager tilstandsrapporter, prosjekterer rehabilitering,
sender byggesøknad med ansvarsrett, og utfører arbeidet med egne
tømrere og murere. Elektriker, rørlegger, stillas og blikkenslager
leier vi inn som underentreprenører.
who_comes_to_us: >
Styreledere i borettslag og sameier, og private huseiere, som har
et problem med bygget og vil at noen skal se på det. Eiere som
allerede vet hva de vil bygge eller endre, og trenger tegninger,
søknad til kommunen og en pris. Håndverksfirmaer som vil stå på
lista vår over underentreprenører. Tømrere, murere og lærlinger som
lurer på om vi trenger folk.
what_we_keep_track_of: >
Henvendelser: de kommer inn, vi avtaler og drar på befaring, vi
sender tilbud, og så vinner vi jobben eller taper den. Noen ganger
er det rett og slett ikke noe for oss, og da sier vi det med en gang.
Underentreprenører: de melder seg, vi sjekker organisasjonsnummer,
sentral godkjenning, forsikring og at folka har HMS-kort. Ofte
mangler det papirer og vi må etterlyse dem. Så blir de godkjent
eller avslått.
Jobbsøknader: vi leser dem, kaller inn noen til intervju, og
ansetter eller takker nei.
Avvik og uønskede hendelser på byggeplass: løse rekkverk,
nestenulykker, feil materialer levert. Noen melder fra, HMS-ansvarlig
bestemmer tiltak, og lukker saken når det er utbedret.
who_is_involved: >
To prosjektledere tar seg av henvendelser, underentreprenører og
ansettelser. En HMS-ansvarlig tar alt som meldes fra byggeplass.
Mannskapet, både våre egne og underentreprenørenes folk, er de som
står på plassen og melder fra. De sitter med telefonen, har hansker
på, og fyller ikke ut lange skjemaer.
what_slows_us_down: >
Henvendelser kommer på telefon, e-post og SMS og blir borte. Vi vet
aldri sikkert hvilke underentreprenører som har papirene i orden.
Avvik blir nevnt i lunsjen og glemt.
+62
View File
@@ -0,0 +1,62 @@
# Tomter Vel, slik en i styret ville fylt det ut. Det som står om
# velet er hentet fra tomtervel.no (komiteer, kontingent, medlemstall,
# arrangementer); det som står om deling av utstyr er et forslag til
# en ny tjeneste.
business: Tomter Vel
contact: { name: Styret i Tomter Vel, email: post@tomtervel.no }
language: no
what_we_do: >
Velforeningen for Tomter, stiftet i 1947. Vi er et styre på sju og
sju komiteer som alle drives av folk på fritida: arrangementer
(17. mai-frokost, juletregranstenning, skøytedag), elvestien langs
Hobølelva, to lekeplasser vi holder i stand og får kontrollert hvert
år, høringssvar til kommunen, miljøgata i sentrum, pendlerforhold
mot Ruter, og trafikkforhold. 157 husstander betaler kontingent på
250 kroner i året.
who_comes_to_us: >
Husstander som vil bli medlem, eller som har flyttet eller byttet
e-post og vil at vi skal ha det riktig. Folk som har sett noe i
nabolaget som ikke er som det skal: en farlig sving, en huske som
henger i én kjetting, en råtten planke på stien. Beboere som vil
si sin mening om en sak kommunen har på høring. Folk som vil hjelpe
til på et arrangement eller en dugnad, eller sitte i en komité.
Og naboer som har en tilhenger, en stige eller en hekksaks som står
ubrukt, og naboer som trenger å låne en. Eldre og nyopererte som
trenger en hånd med snømåking, handling eller en skyss, og naboer
som gjerne stiller opp hvis noen spør.
what_we_keep_track_of: >
Medlemskap: en husstand melder seg inn, kassereren ser at
kontingenten er betalt, og noen melder seg ut når de flytter.
Meldinger om trafikk: noen melder fra, trafikkomiteen tar det opp
med kommunen eller veieier, og det blir ordnet eller avvist.
Feil på lekeplass og sti: noen melder fra, komiteen tar tak i det
og utbedrer det.
Høringsinnspill: en beboer sender inn, styret tar det med i svaret
eller lar være.
Frivillige: noen tilbyr seg, arrangementskomiteen tar kontakt og
setter dem opp, eller takker nei.
Komitésøknader: noen vil være med, styret plasserer dem eller sier
nei.
Utlegg: en i en komité har lagt ut for noe, kassereren godkjenner og
betaler ut, eller avviser.
Nabohjelp: noen ber om en hånd, nabohjelpsgruppa finner en som kan,
og den som fikk hjelp sier fra når det er ordnet. Naboer som vil
hjelpe melder seg, og kan trekke seg igjen.
Deling av utstyr: en nabo melder at de har noe å låne ut, eller
trenger å låne noe; styret legger det ut på oppslagstavla og tar
det ned når det er gjort.
who_is_involved: >
Kassereren har medlemskap og utlegg. Trafikkomiteen har
trafikkmeldinger, lekeplasskomiteen har feil på anlegg,
arrangementskomiteen har frivillige. Styret har høringsinnspill,
komitésøknader og oppslagstavla. Nabohjelpsgruppa kobler dem som
trenger hjelp med dem som kan. Komiteene leverer utlegg.
what_slows_us_down: >
Medlemslista er en bankutskrift og et regneark. Ting som meldes på
Facebook eller i butikken blir husket av den som hørte det. Folk
som tilbyr seg å hjelpe får svar sent eller aldri.
+487
View File
@@ -0,0 +1,487 @@
# A building authority, written by hand to find where the plan language
# stops. 14 needs, 7 roles, 12 buckets, two needs sharing a bucket in
# each direction (public and internal), a decision no case officer may
# sign, a group outside the building that moves records and nothing
# else, a stage a deadline moves rather than a person, and four things
# the plan language cannot say at all - each named in the run's README
# rather than smuggled past.
business: Vestmark kommune - Building and Planning
language: en
contact: { name: Solveig Hauge, email: byggesak@vestmark.example }
mail: { from: "Vestmark Building and Planning <byggesak@vestmark.example>", reply_to: byggesak@vestmark.example }
about: >
The building authority for twenty-one thousand people. Anything built,
demolished, divided or changed in use is decided here: the drawings are
checked against the zoning map, the neighbours and the other
authorities have their say, and then the head of section signs. The
same office inspects what is actually built, signs off finished work,
and deals with building nobody applied for.
# Two features, two roles, no button. The authority exists for the
# person who wants to build; the next one it serves is the neighbour
# who finds out what is planned next door. Both have a move of their
# own after sending: the applicant withdraws, the objector withdraws,
# and both buckets are open to read.
does:
- id: we-decide-what-may-be-built
for: small-works-application
text: >
Everything built in Vestmark is decided here. You send the drawings,
the neighbours and the road, fire and heritage authorities are heard,
and you get a written decision you can hold us to.
- id: your-neighbours-case-is-readable
for: objection
text: >
If a notice landed in your postbox, the case behind it is open to
read here, and what you write to us has to be answered by name in
the decision.
doors:
- id: want-to-build
who: an owner or a firm with something to build, divide or change
- id: building-near-me
who: someone who lives next to what is being built
groups:
- { id: front_desk, label: Front desk }
- { id: case_officers, label: Case officers }
- { id: section_head, label: Head of section }
- { id: inspectors, label: Inspectors }
- { id: appeals_board, label: Appeals board, invited_by: [section_head] }
- { id: agencies, label: Hearing bodies, invited_by: [case_officers, section_head] }
- { id: approved_firms, label: Approved firms, invited_by: [section_head] }
invites_by: [section_head, case_officers]
needs:
# --- the public: something they want to build ----------------------
- id: pre-application-meeting
door: want-to-build
who: someone with an idea for a building and no drawings yet
wants: to hear what we will allow before paying an architect
lands_in: meetings
handled_by: case_officers
stages: [open, scheduled, met, advised, cancelled]
done_when: [advised, cancelled]
success: [advised]
# They can call it off themselves; the front desk does it when they ring.
moves_by: { cancelled: [submitter, front_desk] }
watched_by: [front_desk]
mails: { open: submitter, scheduled: submitter, advised: submitter }
stages_text: { met: we have met, advised: written advice sent }
max_fields: 5
collects:
- { name: name }
- { name: email, type: email }
- { name: property_address }
- { name: what_you_want, type: textarea }
- { name: phone, type: tel, optional: true }
- { name: site, type: location, optional: true }
- id: small-works-application
door: want-to-build
who: an owner applying for something small enough to file themselves
wants: permission to build it, and to know where the case stands
lands_in: applications
handled_by: case_officers
stages: [open, incomplete, complete, on_hearing, recommended, approved, approved_with_conditions, refused, withdrawn]
done_when: [approved, approved_with_conditions, refused, withdrawn]
success: [approved, approved_with_conditions]
skippable: [incomplete]
# A case is sent back for the drawing it was missing, and the
# hearing turns things up that send it back again. It may be
# withdrawn from anywhere, and refused only once we have seen
# everything: not on the day it arrives.
reached_from:
incomplete: [open, complete, on_hearing]
refused: [complete, on_hearing, recommended]
# No case officer signs their own case: only the head of section
# moves one into a decision. The applicant answers a request for
# missing papers, and may withdraw right up to the signature.
moves_by:
complete: [submitter, case_officers]
approved: [section_head]
approved_with_conditions: [section_head]
refused: [section_head]
withdrawn: [submitter]
watched_by: [public, front_desk, inspectors, section_head]
mails:
open: submitter
incomplete: submitter
on_hearing: submitter
approved: submitter
approved_with_conditions: submitter
refused: submitter
stages_text:
incomplete: papers missing
complete: papers complete
on_hearing: out to the neighbours and the agencies
recommended: recommendation written
approved_with_conditions: approved on conditions
max_fields: 6
collects:
- { name: email, type: email }
- { name: property_address }
- { name: property_number }
- { name: what_is_planned, type: textarea }
- { name: neighbours_notified, type: select, options: ["Yes", Not yet] }
- { name: site, type: location, optional: true }
- { name: drawings_url, optional: true }
- id: exemption-request
door: want-to-build
who: someone whose plans break a rule in the zoning map
wants: to be allowed it anyway, with reasons on the record
requires: An application already with us, and the case number from its receipt.
lands_in: exemptions
handled_by: case_officers
stages: [open, county_asked, county_answered, recommended, granted, denied, withdrawn]
done_when: [granted, denied, withdrawn]
success: [granted]
# The county answers from outside the building; nothing may be
# granted before it has. The head of section signs, as for a permit.
moves_by:
county_answered: [agencies]
granted: [section_head]
denied: [section_head]
withdrawn: [submitter]
watched_by: [public, section_head]
mails: { open: submitter, county_asked: submitter, granted: submitter, denied: submitter }
stages_text: { county_asked: with the county, county_answered: the county has answered }
max_fields: 4
collects:
- { name: email, type: email }
- { name: case_number }
- { name: which_rule }
- { name: why_it_should_be_allowed, type: textarea }
- { name: site, type: location, optional: true }
- id: completion-request
door: want-to-build
who: an owner or firm whose building work is finished
wants: the certificate that lets the building be used
requires: A case number, and the work finished or close enough to move in.
lands_in: completions
handled_by: case_officers
stages: [open, checked, temporary_permission, certificate_issued, refused]
done_when: [certificate_issued, refused]
success: [certificate_issued]
# Most go straight through; the ones who want to move in before the
# last of it is done detour past a temporary permission.
skippable: [temporary_permission]
moves_by:
temporary_permission: [section_head]
certificate_issued: [section_head]
refused: [section_head]
watched_by: [public, inspectors]
turned_down_from: [open, checked]
mails: { open: submitter, temporary_permission: submitter, certificate_issued: submitter, refused: submitter }
stages_text: { checked: checked against the inspections, temporary_permission: temporary permission to use, certificate_issued: certificate issued }
max_fields: 5
collects:
- { name: email, type: email }
- { name: case_number }
- { name: property_address }
- { name: work_finished, type: date }
- { name: asking_for, type: select, options: [Completion certificate, Temporary permission to move in] }
- { name: what_is_outstanding, type: textarea, optional: true }
# --- the public: someone else is building ---------------------------
- id: objection
door: building-near-me
who: a neighbour who got a notice about what is planned next door
wants: what they think on the record, and answered in the decision
requires: The notice that came in the post, which has the case number on it.
lands_in: objections
handled_by: case_officers
stages: [open, registered, answered_by_applicant, addressed, withdrawn]
done_when: [addressed, withdrawn]
success: [addressed]
# The firm that filed the case answers the objection; the neighbour
# can take it back if they are satisfied.
moves_by: { answered_by_applicant: [approved_firms, case_officers], withdrawn: [submitter] }
watched_by: [public, section_head]
mails: { open: submitter, answered_by_applicant: submitter, addressed: submitter }
stages_text: { registered: on the case file, answered_by_applicant: the applicant has answered, addressed: answered in the decision }
max_fields: 4
collects:
- { name: email, type: email }
- { name: case_number }
- { name: your_property }
- { name: your_objection, type: textarea }
- id: case-status-enquiry
door: building-near-me
who: someone waiting on a case and getting nothing back
wants: to be told where it actually stands
lands_in: enquiries
handled_by: front_desk
stages: [open, in_hand, answered]
done_when: [answered]
success: [answered]
moves_by: { in_hand: [front_desk, case_officers] }
watched_by: [case_officers]
mails: { open: submitter, answered: submitter }
max_fields: 3
collects:
- { name: email, type: email }
- { name: case_number_or_address }
- { name: what_you_want_to_know, type: textarea }
- id: illegal-building-report
door: building-near-me
who: someone who can see building going up that nobody was told about
wants: us to go and look, and to hear that we did
lands_in: illegal_building
handled_by: inspectors
stages: [open, inspected, owner_asked, explained, resolved, fined, dropped]
done_when: [resolved, fined, dropped]
success: [resolved, dropped]
# An inspector goes and looks; the letter to the owner is a case
# officer's, and so is the fine.
moves_by: { owner_asked: [case_officers], explained: [case_officers], fined: [section_head] }
watched_by: [case_officers, section_head]
turned_down_from: [open, inspected]
mails: { open: submitter, inspected: submitter, resolved: submitter, dropped: submitter }
stages_text: { owner_asked: the owner has been written to, explained: the owner has answered, dropped: nothing to pursue }
max_fields: 3
collects:
- { name: email, type: email }
- { name: address }
- { name: what_you_saw, type: textarea }
- { name: where, type: location, optional: true }
# --- the public: after a decision ------------------------------------
- id: appeal
who: anyone with an interest who will not accept a decision of ours
wants: the decision looked at again, by us and then by the board
requires: A decision from us less than three weeks old, and its case number.
lands_in: appeals
handled_by: case_officers
stages: [open, reconsidered, changed_by_us, before_the_board, upheld, overturned, withdrawn]
done_when: [changed_by_us, upheld, overturned, withdrawn]
success: [changed_by_us, upheld]
# If we change our own mind that is the end of it, and it happens
# while we are looking - not after the board has the case. The
# board can only decide what has reached it.
reached_from:
changed_by_us: [reconsidered]
upheld: [before_the_board]
overturned: [before_the_board]
# We look at ourselves first and the head of section decides whether
# we were wrong. What we will not change goes to seven elected
# people who meet once a month and move nothing else in this office.
moves_by:
changed_by_us: [section_head]
before_the_board: [section_head]
upheld: [appeals_board]
overturned: [appeals_board]
withdrawn: [submitter]
watched_by: [public, front_desk, section_head]
mails:
open: submitter
reconsidered: submitter
changed_by_us: submitter
before_the_board: submitter
upheld: submitter
overturned: submitter
stages_text:
reconsidered: we are looking at it again
changed_by_us: we changed our own decision
before_the_board: with the appeals board
upheld: the board kept our decision
overturned: the board overturned us
max_fields: 5
collects:
- { name: email, type: email }
- { name: case_number }
- { name: property }
- { name: what_you_disagree_with, type: textarea }
- { name: your_interest, type: select, options: [I applied, I am a neighbour, Other] }
# --- the public: a firm that wants to file here -----------------------
- id: firm-approval
who: an architect or engineering firm that files for its clients
wants: to be on the list, and then to file without asking again
lands_in: firms
handled_by: case_officers
stages: [open, papers_missing, checked, approved, declined]
done_when: [approved, declined]
success: [approved]
skippable: [papers_missing]
moves_by: { checked: [submitter, case_officers], approved: [section_head], declined: [section_head] }
watched_by: [section_head, front_desk]
turned_down_from: [open, papers_missing, checked]
mails: { open: submitter, papers_missing: submitter, approved: submitter, declined: submitter }
stages_text: { papers_missing: waiting on papers, checked: papers checked }
max_fields: 6
collects:
- { name: firm_name }
- { name: org_number }
- { name: email, type: email }
- { name: qualified_for, type: select, multiple: true, options: [Design, Execution, Independent control, Site management] }
- { name: insurance_expires, type: date }
- { name: insurance_document, optional: true }
# --- approved firms ----------------------------------------------------
- id: permit-application
who: an approved firm filing on behalf of an owner
wants: a decision inside twelve weeks, and to know when the clock stops
enters_as: approved_firms
lands_in: applications
handled_by: case_officers
stages: [open, incomplete, complete, on_hearing, recommended, approved, approved_with_conditions, refused, withdrawn]
done_when: [approved, approved_with_conditions, refused, withdrawn]
success: [approved, approved_with_conditions]
skippable: [incomplete]
# A case is sent back for the drawing it was missing, and the
# hearing turns things up that send it back again. It may be
# withdrawn from anywhere, and refused only once we have seen
# everything: not on the day it arrives.
reached_from:
incomplete: [open, complete, on_hearing]
refused: [complete, on_hearing, recommended]
moves_by:
complete: [submitter, case_officers]
approved: [section_head]
approved_with_conditions: [section_head]
refused: [section_head]
withdrawn: [submitter]
watched_by: [public, front_desk, inspectors, section_head]
mails:
open: submitter
incomplete: submitter
on_hearing: submitter
approved: submitter
approved_with_conditions: submitter
refused: submitter
stages_text:
incomplete: papers missing
complete: papers complete
on_hearing: out to the neighbours and the agencies
recommended: recommendation written
approved_with_conditions: approved on conditions
max_fields: 6
collects:
- { name: email, type: email }
- { name: property_address }
- { name: property_number }
- { name: what_is_planned, type: textarea }
- { name: neighbours_notified, type: select, options: ["Yes", Not yet] }
- { name: site, type: location, optional: true }
- { name: drawings_url, optional: true }
# --- the front desk -----------------------------------------------------
- id: log-counter-enquiry
who: whoever is on the counter with a queue and a caller on the line
wants: the question written down and sent to whoever has the case
enters_as: front_desk
lands_in: enquiries
handled_by: front_desk
stages: [open, in_hand, answered]
done_when: [answered]
success: [answered]
moves_by: { in_hand: [front_desk, case_officers] }
watched_by: [case_officers]
mails: { open: submitter, answered: submitter }
max_fields: 3
collects:
- { name: email, type: email }
- { name: case_number_or_address }
- { name: what_you_want_to_know, type: textarea }
# --- case officers ------------------------------------------------------
- id: request-hearing
who: a case officer sending a case out to the authority that must see it
wants: an answer by the deadline, or a record that none came
enters_as: case_officers
lands_in: hearings
handled_by: case_officers
stages: [open, answered, no_answer, cancelled]
done_when: [answered, no_answer, cancelled]
success: [answered]
# This is how an agency sees what it has been asked. Nobody presses
# a button for the deadline passing.
moves_by: { answered: [agencies] }
watched_by: [agencies, section_head, front_desk]
attended_by: >
the six-week deadline: when it passes with nothing from the agency
the case goes to no_answer and the application goes on without one
stages_text: { no_answer: the deadline passed with no answer }
max_fields: 4
collects:
- { name: case_number }
- { name: which_authority, type: select, options: [Road authority, Fire service, Heritage office, The county] }
- { name: what_we_ask, type: textarea }
- { name: answer_by, type: date }
- { name: site, type: location, optional: true }
# --- the authorities outside the building --------------------------------
- id: hearing-answer
who: a road, fire, heritage or county officer who has been asked about a case
wants: their answer on the file, in their own words
requires: The hearing letter we sent you, which has the case number on it.
enters_as: agencies
lands_in: hearing_answers
handled_by: case_officers
stages: [open, read, followed, set_aside]
done_when: [followed, set_aside]
success: [followed]
watched_by: [section_head, front_desk]
stages_text: { read: read by the case officer, followed: followed in the decision, set_aside: set aside with reasons }
max_fields: 4
collects:
- { name: case_number }
- { name: which_authority, type: select, options: [Road authority, Fire service, Heritage office, The county] }
- { name: our_answer, type: select, options: [No objection, Objection, Conditions required] }
- { name: what_we_say, type: textarea }
# --- inspectors -----------------------------------------------------------
- id: inspection-finding
who: an inspector on a scaffold with gloves on and the wind blowing
wants: what they found logged before they climb down
enters_as: inspectors
lands_in: inspections
handled_by: inspectors
stages: [open, as_approved, deviation, put_right, escalated]
done_when: [as_approved, put_right, escalated]
success: [as_approved, put_right]
# Anything that has to become a fine or a refusal leaves the
# inspectors and becomes a case officer's problem.
moves_by: { escalated: [case_officers, section_head] }
watched_by: [case_officers, section_head]
stages_text: { as_approved: built as approved, deviation: built differently, put_right: put right, escalated: handed to a case officer }
max_fields: 3
collects:
- { name: case_number }
- { name: site_address }
- { name: what_i_found, type: textarea }
- { name: where, type: location, optional: true }
# Held out from every model that writes words.
# arriving with one real thing, in their own register: a homeowner who
# has never read a regulation, a firm that files for a living, an
# inspector on a roof in the wind, a politician reading a bundle.
personas:
- { id: garage-owner, need: pre-application-meeting, text: "We want to put a double garage where the old shed is. Before I pay an architect I'd like to know whether you'll even allow it, because the neighbour says it's too close to the road." }
- { id: shop-to-flats, need: pre-application-meeting, text: "I own the old grocery on Torget and want to make four flats out of it. There are a lot of questions - parking, fire, the facade is listed. Can we sit down with someone?" }
- { id: firm-files-extension, need: permit-application, text: "We are the responsible applicant for an extension at Bjorkeveien 14. Drawings, site plan and the neighbour notices are all ready. We file maybe forty of these a year." }
- { id: owner-small-window, need: permit-application, text: "I want to put a dormer window in my roof. The man at the counter said I have to apply even though it's small." }
- { id: missing-drawings, need: permit-application, text: "You wrote that our section drawing is missing and the case is on hold. I've got it here now, where do I send it so the clock starts again?" }
- { id: too-close-to-boundary, need: exemption-request, text: "The garage ends up one and a half metres from the boundary and the plan says four. We are asking you to allow it anyway - the ground falls away steeply everywhere else on the plot." }
- { id: neighbour-view, need: objection, text: "I got a notice about the extension at number 14. It takes the afternoon sun off my entire terrace and I want that on the record before you decide anything." }
- { id: neighbour-parking, need: objection, text: "The flats they want to build in the old grocery have four parking places for four flats and everyone here already parks on the street. I object." }
- { id: road-authority, need: hearing-answer, text: "Regarding your case 2026/418: the access onto the county road is within the sight line and we cannot accept it as drawn. Our formal reply is attached." }
- { id: fire-service, need: hearing-answer, text: "We have looked at the conversion on Torget. We have no objection provided the stairwell is upgraded. Reference your case 2026/501." }
- { id: refused-applicant, need: appeal, text: "You refused our exemption on the ninth. We don't accept the reasoning - you've allowed the same thing twice in the same street. We're appealing." }
- { id: neighbour-appeals, need: appeal, text: "You approved the extension next door even though I objected. I'm appealing the decision. What do I need to send?" }
- { id: board-member, need: appeal, text: "I sit on the appeals board. I need the case, our own decision, and what the neighbours wrote, before Tuesday." }
- { id: inspector-on-roof, need: inspection-finding, text: "I'm up on the scaffold at Bjorkeveien. The fire wall isn't built to the drawing at all. I've got gloves on and it's blowing. I want this logged before I climb down." }
- { id: inspector-all-good, need: inspection-finding, text: "Been out at Torget. Everything is as approved. Nothing to report but I have to record that I was there." }
- { id: firm-wants-certificate, need: completion-request, text: "The work at Bjorkeveien 14 is finished and inspected. We're asking for the completion certificate so the owners can get their mortgage released." }
- { id: wants-to-move-in, need: completion-request, text: "The house is done apart from the outside steps, which we can't pour until spring. The family has sold their flat. Can we get a temporary permission to move in?" }
- { id: something-behind-fence, need: illegal-building-report, text: "There's a large structure going up behind the fence at Solbakken 7. Nobody has had a notice about it and it's been going on for two weeks." }
- { id: owner-explains, need: illegal-building-report, text: "I got your letter about the terrace. I genuinely did not know it needed an application, it's been there since we moved in. What happens now?" }
- { id: new-firm, need: firm-approval, text: "We are a three-person architecture firm that has just started. We want to be approved so we can file applications for our clients in your municipality." }
- { id: firm-insurance-lapsed, need: firm-approval, text: "You wrote that our liability insurance certificate has expired. We have renewed it, here it is." }
- { id: counter-phone-call, need: log-counter-enquiry, text: "A woman rang about the case behind her house. Wants to know where it stands. I'm at the counter and there's a queue - I need to write it down and send it to whoever has that case." }
- { id: where-is-my-case, need: case-status-enquiry, text: "I sent in my application five weeks ago and I've heard nothing. Is anyone looking at it? Is it in the six weeks with the neighbours or is it waiting on me?" }
+294
View File
@@ -0,0 +1,294 @@
# A contractor's whole operation, to stress the builder and the
# harness: 13 needs, 6 roles, 9 buckets, needs sharing a bucket,
# skippable stages, and a front door that had to be tiered.
business: Nordvik Bygg
language: en
contact: { name: Ingrid Nordvik, email: ingrid@nordvikbygg.example }
about: >
Twelve people who survey old buildings, draw up rehabilitation plans,
handle the permit application, and do the building work with their
own carpenters plus subcontractors for electrical, plumbing and
scaffolding. Project managers win and run the jobs, site managers run
each building site day to day, and one safety officer owns everything
reported from site.
# Six public needs is one over what a front door carries, so the
# public comes through three doors: a building of theirs, work with
# us, and a site of ours next to them (that one is a need on its own).
doors:
- id: your-building
who: an owner, a housing board or a past customer with a building
- id: work-with-us
who: a trade firm, a carpenter or an apprentice who wants work from us
needs:
# --- the public ---------------------------------------------------
- id: survey-enquiry
door: your-building
who: a housing board or private owner with a problem in a building
wants: someone qualified to come and look at it and say what it takes
lands_in: enquiries
handled_by: project_managers
stages: [open, surveyed, quoted, won, lost]
done_when: [won, lost]
success: [won]
# Whoever went to the building marks it surveyed; site managers
# see what is coming their way.
moves_by: { surveyed: [project_managers, site_managers] }
watched_by: [site_managers]
max_fields: 4
collects:
- { name: name }
- { name: phone, type: tel }
- { name: address }
- { name: problem, type: textarea }
- { name: access, optional: true }
- id: build-enquiry
door: your-building
who: an owner who already knows what they want built or changed
wants: drawings, a permit application and a price
lands_in: enquiries
handled_by: project_managers
stages: [open, surveyed, quoted, won, lost]
done_when: [won, lost]
success: [won]
# Whoever went to the building marks it surveyed; site managers
# see what is coming their way.
moves_by: { surveyed: [project_managers, site_managers] }
watched_by: [site_managers]
max_fields: 5
collects:
- { name: name }
- { name: phone, type: tel }
- { name: address }
- { name: project, type: textarea }
- { name: timeframe, type: select, options: [This year, Next year, No fixed date] }
- id: warranty-claim
door: your-building
who: a past customer who has found a fault in work we handed over
wants: us to come back, look at it, and put it right
lands_in: claims
handled_by: project_managers
stages: [open, inspected, accepted, fixed, rejected]
done_when: [fixed, rejected]
success: [fixed]
# The site manager inspects and puts it right; whether it is ours
# to fix is the project manager's call.
moves_by: { inspected: [site_managers], fixed: [site_managers] }
max_fields: 4
collects:
- { name: name }
- { name: phone, type: tel }
- { name: address }
- { name: fault, type: textarea }
- { name: handed_over, type: date, optional: true }
- id: neighbour-complaint
who: someone living or working next to one of our building sites
wants: the noise, dust or blocked access dealt with, and an answer
lands_in: complaints
handled_by: site_managers
stages: [open, answered]
done_when: [answered]
success: [answered]
watched_by: [project_managers]
max_fields: 3
collects:
- { name: site_address }
- { name: what_is_wrong, type: textarea }
- { name: reach_me_on }
- id: subcontractor-application
door: work-with-us
who: a trade firm doing electrical, plumbing or scaffolding work
wants: to be approved once, and then be called when a job needs them
lands_in: subcontractors
handled_by: project_managers
stages: [open, awaiting_papers, approved, declined]
done_when: [approved, declined]
success: [approved]
watched_by: [site_managers]
skippable: [awaiting_papers]
max_fields: 5
collects:
- { name: company }
- { name: registration_number }
- { name: trade, type: select, options: [Electrical, Plumbing, Scaffolding, Sheet metal, Other] }
- { name: contact_email, type: email }
- { name: insurance_confirmed, type: select, options: ["Yes", Not yet] }
- { name: trade_approval, optional: true }
- id: job-application
door: work-with-us
who: a carpenter, bricklayer or apprentice looking for work
wants: to be considered, without writing a letter
lands_in: applicants
handled_by: project_managers
stages: [open, interviewing, offered, hired, declined]
done_when: [hired, declined]
success: [hired]
max_fields: 3
collects:
- { name: name }
- { name: phone, type: tel }
- { name: trade, type: select, options: [Carpenter, Bricklayer, Apprentice, Other] }
- { name: experience, type: textarea, optional: true }
# --- clients with a job under way ---------------------------------
- id: change-request
who: a client whose job is under way and who wants something changed
wants: a price for the change, and the change done if they accept it
enters_as: clients
lands_in: change_orders
handled_by: project_managers
stages: [open, priced, approved, completed, declined]
done_when: [completed, declined]
success: [completed]
# The project manager prices it, the client says yes or no through
# their own link, the site manager does the work.
moves_by: { approved: [submitter], declined: [submitter, project_managers], completed: [site_managers] }
watched_by: [site_managers]
max_fields: 3
collects:
- { name: email, type: email }
- { name: job_address }
- { name: change, type: textarea }
- { name: needed_by, type: date, optional: true }
# --- project managers ---------------------------------------------
- id: log-phone-enquiry
who: a project manager who just took a call or a text about a building
wants: the enquiry written down before it gets lost
enters_as: project_managers
lands_in: enquiries
handled_by: project_managers
stages: [open, surveyed, quoted, won, lost]
done_when: [won, lost]
success: [won]
# Whoever went to the building marks it surveyed; site managers
# see what is coming their way.
moves_by: { surveyed: [project_managers, site_managers] }
watched_by: [site_managers]
max_fields: 4
collects:
- { name: caller }
- { name: phone, type: tel }
- { name: address }
- { name: problem, type: textarea }
- id: post-job-request
who: a project manager with work to hand to a subcontractor
wants: approved subcontractors to see the job and answer with a price
enters_as: project_managers
lands_in: job_requests
handled_by: project_managers
stages: [open, awarded, withdrawn]
done_when: [awarded, withdrawn]
success: [awarded]
# This is how subcontractors see what there is to bid on.
watched_by: [subcontractors, site_managers]
max_fields: 4
collects:
- { name: site_address }
- { name: trade, type: select, options: [Electrical, Plumbing, Scaffolding, Sheet metal, Other] }
- { name: work, type: textarea }
- { name: start, type: date }
# --- approved subcontractors --------------------------------------
- id: submit-bid
who: an approved subcontractor who has seen a job they can take
wants: to say yes with a price and a start date
enters_as: subcontractors
lands_in: bids
handled_by: project_managers
stages: [open, shortlisted, accepted, declined]
done_when: [accepted, declined]
success: [accepted]
watched_by: [site_managers]
skippable: [shortlisted]
max_fields: 3
collects:
- { name: job }
- { name: price }
- { name: can_start, type: date }
# --- on site --------------------------------------------------------
- id: report-site-issue
who: anyone on site, ours or a subcontractor's, on a phone with gloves on
wants: to report a hazard, a near miss or wrong materials before they forget
enters_as: crew
lands_in: site_issues
handled_by: safety_officer
stages: [open, in_hand, closed]
done_when: [closed]
success: [closed]
# A site manager can take an issue in hand on the spot; only the
# safety officer closes it.
moves_by: { in_hand: [safety_officer, site_managers] }
watched_by: [project_managers]
max_fields: 3
collects:
- { name: kind, type: select, options: [Hazard, Near miss, Wrong materials, Other] }
- { name: where }
- { name: what_happened, type: textarea }
- id: order-materials
who: a carpenter or bricklayer who is about to run out of something
wants: it ordered and on site before work stops
enters_as: crew
lands_in: material_orders
handled_by: site_managers
stages: [open, ordered, delivered, refused]
done_when: [delivered, refused]
success: [delivered]
# The crew confirms it arrived.
moves_by: { delivered: [crew, site_managers] }
max_fields: 3
collects:
- { name: site_address }
- { name: what, type: textarea }
- { name: needed_by, type: date }
- id: safety-round-finding
who: the safety officer walking a site on the weekly round
wants: each thing found written down where the reported issues already are
enters_as: safety_officer
lands_in: site_issues
handled_by: safety_officer
stages: [open, in_hand, closed]
done_when: [closed]
success: [closed]
# A site manager can take an issue in hand on the spot; only the
# safety officer closes it.
moves_by: { in_hand: [safety_officer, site_managers] }
watched_by: [project_managers]
max_fields: 3
collects:
- { name: kind, type: select, options: [Hazard, Near miss, Wrong materials, Other] }
- { name: where }
- { name: what_happened, type: textarea }
# No model that writes words ever sees these.
personas:
- { id: housing-board-damp, need: survey-enquiry, text: "I chair the board of a housing cooperative from the seventies. Two ground-floor flats have damp in the walls and we don't know if it's drainage or the facade. We need someone to tell us." }
- { id: buyer-before-purchase, need: survey-enquiry, text: "We are about to buy an old timber house. Before we sign we want a professional to go through it and tell us what is wrong with it." }
- { id: attic-conversion, need: build-enquiry, text: "We want to turn our attic into two bedrooms and a bathroom. We need drawings and someone who handles the application to the municipality." }
- { id: shop-to-flat, need: build-enquiry, text: "I own a former shop on the ground floor and want to make it a flat. I have no idea what is allowed. Can you sort that out and give me a price?" }
- { id: leaking-bathroom, need: warranty-claim, text: "You redid our bathroom two years ago. Now water is coming through the ceiling of the flat below. I want you to come and fix it." }
- { id: cracked-render, need: warranty-claim, text: "The render you put on our gable wall last summer has cracked right across. That can't be right after one winter." }
- { id: noisy-mornings, need: neighbour-complaint, text: "I live next door to the block you are working on. You start drilling at half past six every morning and I have a baby. Who do I talk to?" }
- { id: blocked-driveway, need: neighbour-complaint, text: "Your skip and a van have been parked across the entrance to our shop's loading bay for three days. We can't get deliveries." }
- { id: electrician-firm, need: subcontractor-application, text: "We are a four-person electrical firm, fully certified. We would like to get on your list so you call us when you need electricians." }
- { id: scaffolder, need: subcontractor-application, text: "I run a scaffolding company. How do I get to do jobs for you?" }
- { id: carpenter-jobseeker, need: job-application, text: "I'm a certified carpenter with eight years on rehabilitation jobs. Are you hiring?" }
- { id: apprentice, need: job-application, text: "I finish vocational school this spring and need an apprenticeship as a bricklayer." }
- { id: extra-window, need: change-request, text: "You are in the middle of our attic conversion. We have decided we want a roof window over the stairs as well. What would that cost?" }
- { id: pm-took-a-call, need: log-phone-enquiry, text: "A woman from a housing board in Storgata just rang about water in their basement. I'm in the van. I need to note it before I forget her number." }
- { id: pm-needs-plumber, need: post-job-request, text: "The bathroom job in Kirkeveien needs a plumber for two weeks from the first of next month. I want prices from the ones we have approved." }
- { id: plumber-bidding, need: submit-bid, text: "We are an approved plumbing firm. I saw you need someone in Kirkeveien next month. We can do it, I have a price." }
- { id: loose-railing, need: report-site-issue, text: "The railing on the third level of the scaffold on the north side is loose. Nobody got hurt but someone will." }
- { id: wrong-membrane, need: report-site-issue, text: "The bathroom membrane delivered today is not the one in the specification. We stopped work on it." }
- { id: out-of-battens, need: order-materials, text: "We have enough roof battens for today and maybe half of tomorrow. Need another two hundred metres on site by Thursday." }
- { id: weekly-round, need: safety-round-finding, text: "On my Friday round I found the first-aid box on level two empty and an extension lead run through a puddle." }
+122
View File
@@ -0,0 +1,122 @@
# The contractor from intakes/contractor.yaml as a plan: the needs spec
# plus what each form collects. Everything structural in the generated
# site comes from this file; a model only writes the words.
business: Nordvik Bygg
language: en
contact: { name: Ingrid Nordvik, email: ingrid@nordvikbygg.example }
about: >
Twelve people who survey old buildings, draw up rehabilitation plans,
handle the permit application, and do the building work with their
own carpenters plus subcontractors for electrical, plumbing and
scaffolding.
needs:
- id: survey-enquiry
who: a housing board or private owner with a problem in a building
wants: someone qualified to come and look at it and say what it takes
lands_in: enquiries
handled_by: project_managers
stages: [open, surveyed, quoted, won, lost]
done_when: [won, lost]
success: [won]
max_fields: 4
collects:
- { name: name }
- { name: phone, type: tel }
- { name: address }
- { name: problem, type: textarea }
- { name: access, optional: true }
- id: build-enquiry
who: an owner who already knows what they want built or changed
wants: drawings, a permit application and a price
lands_in: enquiries
handled_by: project_managers
stages: [open, surveyed, quoted, won, lost]
done_when: [won, lost]
success: [won]
max_fields: 5
collects:
- { name: name }
- { name: phone, type: tel }
- { name: address }
- { name: project, type: textarea }
- { name: timeframe, type: select, options: [This year, Next year, No fixed date] }
- id: log-phone-enquiry
who: a project manager who just took a call or a text about a building
wants: the enquiry written down before it gets lost
enters_as: project_managers
lands_in: enquiries
handled_by: project_managers
stages: [open, surveyed, quoted, won, lost]
done_when: [won, lost]
success: [won]
max_fields: 4
collects:
- { name: caller }
- { name: phone, type: tel }
- { name: address }
- { name: problem, type: textarea }
- id: subcontractor-application
who: a trade firm doing electrical, plumbing or scaffolding work
wants: to be approved once, and then be called when a job needs them
lands_in: subcontractors
handled_by: project_managers
stages: [open, awaiting_papers, approved, declined]
done_when: [approved, declined]
success: [approved]
skippable: [awaiting_papers]
max_fields: 5
collects:
- { name: company }
- { name: registration_number }
- { name: trade, type: select, options: [Electrical, Plumbing, Scaffolding, Sheet metal, Other] }
- { name: contact_email, type: email }
- { name: insurance_confirmed, type: select, options: ["Yes", Not yet] }
- { name: trade_approval, optional: true }
- id: job-application
who: a carpenter, bricklayer or apprentice looking for work
wants: to be considered, without writing a letter
lands_in: applicants
handled_by: project_managers
stages: [open, interviewing, hired, declined]
done_when: [hired, declined]
success: [hired]
max_fields: 3
collects:
- { name: name }
- { name: phone, type: tel }
- { name: trade, type: select, options: [Carpenter, Bricklayer, Apprentice, Other] }
- { name: experience, type: textarea, optional: true }
- id: report-site-issue
who: anyone on site, ours or a subcontractor's, on a phone with gloves on
wants: to report a hazard, a near miss or wrong materials before they forget
enters_as: crew
lands_in: site_issues
handled_by: safety_officer
stages: [open, in_hand, closed]
done_when: [closed]
success: [closed]
max_fields: 3
collects:
- { name: kind, type: select, options: [Hazard, Near miss, Wrong materials, Other] }
- { name: where }
- { name: what_happened, type: textarea }
# Held out from every model that writes words: these are the personas
# from sectors/construction, which no generator has seen.
personas:
- { id: housing-board-damp, need: survey-enquiry, text: "I chair the board of a housing cooperative from the seventies. Two ground-floor flats have damp in the walls and we don't know if it's drainage or the facade. We need someone to tell us." }
- { id: buyer-before-purchase, need: survey-enquiry, text: "We are about to buy an old timber house. Before we sign we want a professional to go through it and tell us what is wrong with it." }
- { id: attic-conversion, need: build-enquiry, text: "We want to turn our attic into two bedrooms and a bathroom. We need drawings and someone who handles the application to the municipality." }
- { id: shop-to-flat, need: build-enquiry, text: "I own a former shop on the ground floor and want to make it a flat. I have no idea what is allowed. Can you sort that out and give me a price?" }
- { id: electrician-firm, need: subcontractor-application, text: "We are a four-person electrical firm, fully certified. We would like to get on your list so you call us when you need electricians." }
- { id: scaffolder, need: subcontractor-application, text: "I run a scaffolding company. How do I get to do jobs for you?" }
- { id: carpenter-jobseeker, need: job-application, text: "I'm a certified carpenter with eight years on rehabilitation jobs. Are you hiring?" }
- { id: apprentice, need: job-application, text: "I finish vocational school this spring and need an apprenticeship as a bricklayer." }
- { id: loose-railing, need: report-site-issue, text: "The railing on the third level of the scaffold on the north side is loose. Nobody got hurt but someone will." }
- { id: wrong-membrane, need: report-site-issue, text: "The bathroom membrane delivered today is not the one in the specification. We stopped work on it." }
+88
View File
@@ -0,0 +1,88 @@
# Vedtekter
### av 23.04.2018
##### § 1
Tomter vel er upolitisk. Foreningen har som formål å virke for stedets velferd, forskjønnelse og utvikling og ellers ivareta Tomters interesser.
##### § 2
Alle som er bosatt i Tomter kan bli medlem av foreningen. Midlertidig utflyttede medlemmer kan beholde sitt medlemskap.
##### § 3
Årsmøte, som er vellets øverste myndighet, holdes innen utgangen av mars hvert år. Møtet kunngjøres med minst tre ukers varsel. Forslag skal også gjøres kjent minst to uker før møtet. Årsmøte godkjenner beretning, regnskap og budsjett. Den velger styre, komitéledere, og valgkomite.
##### § 4.
Ekstraordinært årsmøte holdes når styret, eller minst 15 medlemmer krever det i skriftlig form. Gjennomføringen følger samme prosedyre som ordinært årsmøte
##### § 5
Tomter Vel ledes av et styre på seks medlemmer. Leder, nestleder, sekretær, kasserer og to styremedlemmer, som alle velges på årsmøtet. Funksjonstiden er to år. Leder, sekretær og ett styremedlem velges det ene året, nestleder, kasserer og det andre styremedlemmet det andre året. Det skal dessuten på årsmøte velges ett varamedlem til styret med funksjonstid to år. Styret engasjerer revisor eller ekstern regnskapsfører. Oppnevning av andre komitémedlemmer og representanter foretas av styret etter behov. Komitéledere har møterett på styremøter.
##### § 6
Medlemsmøte avholdes når styret finner det nødvendig og skal bekjentgjøres minst en uke i forveien. Det bør avholdes minst ett medlemmsmøte mellom hvert årsmøte.
##### § 7.1
Styret skal:
iverksette årsmøtets vedtak og bestemmelser.
Stå for velforeningens daglige ledelse og ivareta medlemmenes interesser overfor andre instanser.
Stå for den alminnelige forvaltningen av foreningen, herunder forvalte velforeningens eiendeler og føre kontroll med foreningens økonomi.
etter behov opprette komitéer eller bemyndige personer for å løse spesielle oppgaver.
etter beste evne søke å oppfylle foreningens formål eller gjeldende regler.
sørge for at foreningen er forsvarlig forsikret.
##### § 7.2
Styret har disposisjonsrett over velforeningens midler til alminnelige administrative formål og rett til å bevilge beløp til gjennomføring av vedtak på årsmøtet. Alle utbetalinger skal attesteres av leder og kasserer før utbetaling. Styret har imidlertid ikke adgang til uten samtykke fra årsmøtet å treffe beslutninger av større betydning for foreningen.
##### § 7.3
Styret holder møte når leder bestemmer eller et flertall av styremedlemmene forlanger det. Varamedlemmet kan møte på samtlige styremøter, men har kun stemmerett når styret ikke er fulltallig.
Alle saker og all korrespondanse skal legges fram på styremøtet. Styrets vedtak skal protokolleres. Det skal fremgå av protokollen om vedtaket er enstemmig, og eventuelle dissenser protokolleres. Alle medlemmene har rett til innsyn i protokollene fra styremøtene. Innsyn kan nektes av styret i enkeltsaker, dersom hensynet til tredjemann tilsier det eller dersom andre saklige grunner for nektelse foreligger.
##### § 7.4
Styret er beslutningsdyktig når et flertall av styremedlemmene, deriblant leder eller nestleder, er tilstede. Leder eller i hans/hennes fravær nestleder, leder styrets møter. Styrebeslutninger krever alminnelig flertall. Ved stemmelikhet har fungerende leder dobbeltstemme.
Et styremedlem kan ikke være med å stemme i saker hvor dette har særinteresser.
##### § 8
Regnskapsåret går fra 01.01–31.12. Styret skal påse at regnskapet blir ført.
##### § 9
Medlemskontingenten er den som til enhver tid er/blir fastsatt av Årsmøte. Kontingenten innkreves av styret. Den betales forskuddsvis.
##### § 10
Tomter Vel kan bare oppløses ved vedtak på Årsmøte etter forslag fra styret. Til slikt vedtak kreves to tredjedels stemmeflertall blant de frammøtte medlemmer. Forslag om oppløsning skal gjøres kjent 3 uker før årsmøtet holdes. Eventuelle midler som Tomter Vel sitter inne med, anvendes da straks til formål som kommer Tomter til gode.
##### § 11
Styret eller årsmøtet oppretter komiteer for definerte formål. Komitéer skal bestå av komiteleder som rapporterer til styret. Komiteleder tilknytter et egnet antall personer til formålet og organiserer arbeidet.
##### § 12
Valgkomiteen består av to medlemmer med funksjonstid ett år. Valgkomiteen foreslår overfor Årsmøte medlemmer og varamedlemmer til styre, komitéer og valgkomite, samt revisor.
##### § 13
Tomter Vel skal ha en revisorer med funksjonstid to år. Revisoren skal revidere regnskapet og legge fram revisjonsberetning for Årsmøtet.
##### § 14
Forandringer i disse lover kan bare skje ved vedtak på Årsmøte. Slikt vedtak krever to tredjedels stemmeflertall blant de frammøtte medlemmene.
+119
View File
@@ -0,0 +1,119 @@
# Fotballgruppa i et idrettslag, på norsk: to dører på forsiden
# (foresatte, og de som vil bidra), roller som overlapper på én
# innmelding (treneren godkjenner, kassereren ser betalingen), og en
# intern melding fra trenerne til styret.
business: Lia IL Fotball
language: no
contact: { name: Kari Lien, email: kari@liail.example }
mail: { from: "Liail IL <post@liail.example>", reply_to: kari@liail.example }
about: >
Fotballgruppa i et idrettslag på bygda. Rundt hundre og tjue unger
fra seks til seksten år, fordelt på lag etter årskull, drevet av
foreldre på fritida.
doors:
- id: foresatte
who: en forelder eller foresatt til et barn som vil spille, eller allerede spiller
- id: bidra
who: noen som vil hjelpe til i klubben, eller en bedrift som vil støtte den
needs:
- id: innmelding
who: en forelder som vil ha ungen med på et lag
wants: at barnet får plass på laget for sitt årskull
door: foresatte
lands_in: innmeldinger
handled_by: trenere
stages: [open, godkjent, betalt, trukket]
stages_text: { open: "mottatt", godkjent: "godkjent av treneren", betalt: "betalt", trukket: "trukket" }
mails: { open: submitter, godkjent: submitter, betalt: submitter }
done_when: [betalt, trukket]
success: [betalt]
# Treneren godkjenner plassen, kassereren ser at det er betalt.
moves_by: { betalt: [kasserer] }
watched_by: [kasserer]
max_fields: 5
collects:
- { name: barnets_navn }
- { name: fodselsar, type: select, options: ["2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020"] }
- { name: foresatt }
- { name: telefon, type: tel }
- { name: email, type: email }
- { name: spilt_for, optional: true }
- id: avgiftssak
who: en forelder som sliter med treningsavgiften
wants: å dele den opp, eller slippe den
door: foresatte
lands_in: avgiftssaker
handled_by: styret
stages: [open, vurdert, innvilget, avslatt]
stages_text: { open: "mottatt", vurdert: "vurdert", innvilget: "innvilget", avslatt: "avslått" }
done_when: [innvilget, avslatt]
success: [innvilget]
max_fields: 3
collects:
- { name: barnets_navn }
- { name: foresatt }
- { name: hva_gjelder_det, type: textarea }
- { name: telefon, type: tel, optional: true }
- id: frivillig
who: en som vil hjelpe til, som trener, lagleder, sjåfør eller på dugnad
wants: å bli brukt der det trengs
door: bidra
lands_in: frivillige
handled_by: styret
stages: [open, kontaktet, plassert, avslatt]
stages_text: { open: "mottatt", kontaktet: "kontaktet", plassert: "satt opp", avslatt: "takket nei" }
done_when: [plassert, avslatt]
success: [plassert]
max_fields: 3
collects:
- { name: navn }
- { name: telefon, type: tel }
- { name: hva_kan_du, type: select, options: [Trene et lag, Være lagleder, Kjøre til kamper, Dugnad, Annet] }
- id: sponsor
who: en bedrift i bygda som vil støtte klubben
wants: en prat om hva de kan bidra med, og en avtale
door: bidra
lands_in: sponsorer
handled_by: styret
stages: [open, i_dialog, avtalt, avslatt]
stages_text: { open: "mottatt", i_dialog: "i dialog", avtalt: "avtalt", avslatt: "avslått" }
done_when: [avtalt, avslatt]
success: [avtalt]
max_fields: 3
collects:
- { name: bedrift }
- { name: kontaktperson }
- { name: telefon, type: tel }
- { name: hva_tenker_dere, type: textarea, optional: true }
- id: baneproblem
who: en trener som ser at noe på anlegget ikke er i orden
wants: at styret får vite det og ordner det
enters_as: trenere
lands_in: baneproblemer
handled_by: styret
stages: [open, tatt_tak_i, ordnet]
stages_text: { open: "mottatt", tatt_tak_i: "tatt tak i", ordnet: "ordnet" }
done_when: [ordnet]
success: [ordnet]
max_fields: 2
collects:
- { name: hvor }
- { name: hva, type: textarea }
# Holdt unna alle modeller som skriver ord.
personas:
- { id: ny-i-bygda, need: innmelding, text: "Vi flyttet hit i sommer og sønnen vår på ni har spilt fotball før. Hvordan får vi ham med på et lag her?" }
- { id: tvillinger, need: innmelding, text: "Jeg har tvillingjenter på sju som maser om å begynne. Er det plass, og hva koster det?" }
- { id: alenefar, need: avgiftssak, text: "Jeg er alene med tre unger og treningsavgiften for alle tre blir for mye på en gang. Går det an å dele den opp?" }
- { id: permittert, need: avgiftssak, text: "Jeg ble permittert i vinter. Kan dattera mi fortsette å spille selv om vi ikke klarer avgiften akkurat nå?" }
- { id: pensjonist, need: frivillig, text: "Jeg er pensjonert og spilte selv i mange år. Har dere bruk for en som kan ta de minste et par kvelder i uka?" }
- { id: stor-bil, need: frivillig, text: "Jeg kan ikke trene noen, men jeg har stor bil og kan kjøre til bortekamper." }
- { id: rorlegger, need: sponsor, text: "Jeg driver rørleggerfirma her i bygda og vil gjerne ha logoen vår på draktene til et lag. Hvem snakker jeg med?" }
- { id: kafeen, need: sponsor, text: "Vi har kafé i sentrum og kan bidra med noe til cupen i mai, kanskje vafler eller litt penger." }
- { id: lyset-slukker, need: baneproblem, text: "Lyset på kunstgresset slår seg av halv åtte og vi trener til åtte. Ungene løper i mørket." }
+94
View File
@@ -0,0 +1,94 @@
# A machine hire yard: two doors (hiring, and an account for firms),
# one aggregate walked by two roles (the counter reserves, the yard
# hands out and takes back), and the yard's own damage report.
business: Fjellstad Hire
language: en
contact: { name: Ola Fjellstad, email: ola@fjellstadhire.example }
about: >
Machine hire: mini diggers, lifts, compactors, generators. A counter,
a yard that delivers, collects and fixes, and an office.
doors:
- id: hiring
who: someone who needs a machine, or has one of ours that has stopped
- id: firms
who: a firm that hires often and wants an account with us
needs:
- id: hire-request
who: a private person or a firm who needs a machine for a while
wants: the right machine, from a date, for as long as they need it
door: hiring
lands_in: hires
handled_by: counter
stages: [open, reserved, out, returned, cancelled]
done_when: [returned, cancelled]
success: [returned]
# The counter reserves; the yard hands it out and takes it back.
moves_by: { out: [yard], returned: [yard] }
max_fields: 5
collects:
- { name: name }
- { name: phone, type: tel }
- { name: what, type: textarea }
- { name: from, type: date }
- { name: until, type: date }
- { name: deliver_to, optional: true }
- id: breakdown
who: someone whose hired machine has stopped working
wants: it running again, or swapped, today
door: hiring
lands_in: breakdowns
handled_by: yard
stages: [open, in_hand, resolved]
done_when: [resolved]
success: [resolved]
max_fields: 3
collects:
- { name: phone, type: tel }
- { name: machine }
- { name: what_happened, type: textarea }
- { name: where, optional: true }
- id: account-request
who: a firm that hires often
wants: to send anyone to collect, and get one invoice a month
door: firms
lands_in: accounts
handled_by: office
stages: [open, checked, approved, declined]
done_when: [approved, declined]
success: [approved]
max_fields: 4
collects:
- { name: company }
- { name: registration_number }
- { name: contact }
- { name: phone, type: tel }
- { name: invoice_email, type: email, optional: true }
- id: damage-on-return
who: someone in the yard who finds damage when a machine comes back
wants: it written down before the customer has left
enters_as: yard
lands_in: damage_reports
handled_by: office
stages: [open, invoiced, written_off]
done_when: [invoiced, written_off]
success: [invoiced]
max_fields: 3
collects:
- { name: machine }
- { name: hire_or_customer }
- { name: damage, type: textarea }
# Held out from every model that writes words.
personas:
- { id: garden-wall, need: hire-request, text: "I'm building a stone wall in the garden and need a small digger for a weekend. I've never driven one." }
- { id: roofer-lift, need: hire-request, text: "We're a roofing crew and need a scissor lift on site in Dalen from Monday for about two weeks." }
- { id: stuck-compactor, need: breakdown, text: "The plate compactor I picked up this morning won't start. I've got a crew standing around." }
- { id: lift-error, need: breakdown, text: "The lift you delivered keeps showing an error and stops halfway up. It's on our site at the school." }
- { id: landscaper-account, need: account-request, text: "We're a landscaping firm hiring from you almost every month and I'm tired of paying by card each time. Can we get invoiced monthly?" }
- { id: builder-account, need: account-request, text: "Small building firm, six people. We'd like to be able to send whoever is nearest to pick things up and have it on our account." }
- { id: yard-window, need: damage-on-return, text: "The mini digger from the Berg job came back with a smashed rear window and hydraulic oil everywhere." }
+284
View File
@@ -0,0 +1,284 @@
# Klingenberg Bygg: tilstand, prosjektering og søknad for bygg, for
# kommuner, borettslag, bedrifter og private. Bygget på det gamle
# spørreskjemaet (klingenbergbygg/kundeportal, questions.ts) og et
# intervju 2026-09-30: alle fire kundegrupper, én pult (Fredrik), og
# hele oppdraget på siden - fra henvendelse over befaring og tilbud til
# levert, med kunden innlogget for å følge saken og hente dokumentene.
# Færre felt enn det gamle skjemaet: det som må til for å ta kontakt og
# komme på befaring, resten tar vi der.
business: Klingenberg Bygg
language: "no"
contact: { name: Fredrik Borch Lynghaug, email: fredrik@klingenbergbygg.no }
mail: { from: "Klingenberg Bygg <portal@klingenbergbygg.no>", reply_to: fredrik@klingenbergbygg.no }
about: >
Med vår erfaring får vi kartlagt **tilstand**, utarbeidet **prosjekt**
og godkjent **søknad** for ditt bygg.
# Kontoret er pulten; kundene får konto i det de takker ja til et
# tilbud, og ser da sine egne oppdrag og dokumentene vi leverer.
groups:
- { id: kontor, label: Kontoret }
- { id: kunder, label: Kunder }
invites_by: [kontor]
# Forsiden åpner med det vi gjør, uten knapp: to trekk.
does:
- id: tilstand
for: tilstand
text: >
Vi utarbeider tilstandsrapporter etter NS-EN 3424 og NS 3423, med
befaring, materialprøver og termofotografering. Skal bygget rives,
leverer vi miljøsaneringsrapport; energibruk og besparelser hører
med i vurderingen. Du får et tilbud og sier selv ja eller nei.
- id: soknad
for: soknad
text: >
Vi prosjekterer og søker: arbeidsbeskrivelse opp mot NS 3420,
fremdriftsplan, og byggesøknad med ansvarsrett. Vi har sentral
godkjenning innen flere fagområder. Når tilbudet er godtatt,
følger du oppdraget og henter dokumentene innlogget.
# Hvem vi er: erfaringen, i våre egne ord, og menneskene. Verdiene
# skriver Fredrik selv; de legges inn her som en `values`-linje til.
values:
- id: erfaring
text: >
Skoler i drift, brannstasjoner, omsorgsboliger, kantina på Det
Norske Teatret og en Munch-eiendom på Hvitsten. Vi har gått over,
prosjektert og fulgt opp bygg for kommuner, borettslag, bedrifter
og private, fra borprøver i gammel mur til kunstgress på
Fredrikstad stasjon.
needs:
- id: tilstand
who: en eier eller forvalter som må vite hvilken forfatning bygget er i, for en kommune, et borettslag, en bedrift eller seg selv
wants: en tilstandsrapport å planlegge og beslutte ut fra
lands_in: tilstandsrapporter
handled_by: kontor
followed_by: [kunder]
stages: [open, befaring, tilbud, akseptert, i_arbeid, levert, avslatt]
stages_text: { open: "mottatt", befaring: "befaring avtalt", tilbud: "tilbud sendt", akseptert: "tilbud godtatt", i_arbeid: "i arbeid", levert: "levert", avslatt: "avsluttet uten oppdrag" }
done_when: [levert, avslatt]
success: [levert]
turned_down_from: [open, befaring, tilbud]
# Kunden sier selv ja eller nei til tilbudet, gjennom sin egen lenke.
moves_by: { akseptert: [submitter], avslatt: [submitter, kontor] }
mails: { open: submitter, befaring: submitter, tilbud: submitter, akseptert: fredrik@klingenbergbygg.no, levert: submitter }
# Et godtatt tilbud er kundeforholdet: konto og plass blant kundene.
grants: { akseptert: kunder }
max_fields: 4
collects:
- { name: name }
- { name: email, type: email }
- { name: telefon, type: tel, optional: true }
- { name: eiendom, type: select, options: [Skole eller annet offentlig bygg, Borettslag eller sameie, Næringsbygg, Enebolig, Leilighet, Fritidsbolig, Annet] }
- { name: adresse }
- { name: mangler, type: textarea, optional: true }
- { name: tegninger, type: file, optional: true }
- id: prosjekt
who: en byggherre som har planer for bygget og trenger dem prosjektert før noen kan bygge
wants: en arbeidsbeskrivelse og fremdriftsplan som gir det beste grunnlaget for utførelse
lands_in: prosjekteringer
handled_by: kontor
followed_by: [kunder]
stages: [open, befaring, tilbud, akseptert, i_arbeid, levert, avslatt]
stages_text: { open: "mottatt", befaring: "befaring avtalt", tilbud: "tilbud sendt", akseptert: "tilbud godtatt", i_arbeid: "i arbeid", levert: "levert", avslatt: "avsluttet uten oppdrag" }
done_when: [levert, avslatt]
success: [levert]
turned_down_from: [open, befaring, tilbud]
moves_by: { akseptert: [submitter], avslatt: [submitter, kontor] }
mails: { open: submitter, befaring: submitter, tilbud: submitter, akseptert: fredrik@klingenbergbygg.no, levert: submitter }
grants: { akseptert: kunder }
max_fields: 4
collects:
- { name: name }
- { name: email, type: email }
- { name: telefon, type: tel, optional: true }
- { name: adresse }
- { name: planer, type: textarea }
- { name: oppstart, type: date, optional: true }
- { name: skisser, type: file, optional: true }
# På pause: fullt hos oss. Ta linjen ut for å åpne igjen.
- id: soknad
paused: true
who: en byggherre med et ferdig prosjektert bygg som trenger offentlig godkjenning før første spadetak
wants: en godkjent byggesøknad, med ansvarsrett der det kreves
lands_in: soknader
handled_by: kontor
followed_by: [kunder]
stages: [open, befaring, tilbud, akseptert, i_arbeid, levert, avslatt]
stages_text: { open: "mottatt", befaring: "forhåndskonferanse eller befaring avtalt", tilbud: "tilbud sendt", akseptert: "tilbud godtatt", i_arbeid: "søknad under arbeid", levert: "søknad levert", avslatt: "avsluttet uten oppdrag" }
done_when: [levert, avslatt]
success: [levert]
turned_down_from: [open, befaring, tilbud]
moves_by: { akseptert: [submitter], avslatt: [submitter, kontor] }
mails: { open: submitter, befaring: submitter, tilbud: submitter, akseptert: fredrik@klingenbergbygg.no, levert: submitter }
grants: { akseptert: kunder }
max_fields: 4
collects:
- { name: name }
- { name: email, type: email }
- { name: telefon, type: tel, optional: true }
- { name: adresse }
- { name: tiltak, type: textarea }
- { name: tegninger, type: file, optional: true }
# Det kontoret leverer: rapporten, tegningene, vedtaket. Kunden får
# e-post og henter dokumentet innlogget, fra sin egen liste.
- id: leveranse
who: kontoret, når en rapport, tegninger eller et vedtak er klart til kunden
wants: at kunden får dokumentet og vet at det ligger der
enters_as: kontor
lands_in: leveranser
handled_by: kontor
followed_by: [kunder]
stages: [open, arkivert]
stages_text: { open: "levert", arkivert: "arkivert" }
done_when: [arkivert]
success: [arkivert]
mails: { open: submitter }
max_fields: 3
collects:
- { name: email, type: email }
- { name: hva }
- { name: dokument, type: file }
# Menneskene: hver ansatt har sitt eget kort på forsiden, med rolle,
# erfaring og portrett, og retter det selv. Kontoret kan ta et kort ned.
- id: ansatt
who: en av oss på kontoret, som vil vise hvem hen er og hva hen kan
wants: at den som vurderer oss ser hvem som gjør jobben
enters_as: kontor
one_per_person: true
# Et kort som er tatt ned, forsvinner fra kontorets liste etter ti minutter.
leaves_after: { sluttet: { minutes: 10 } }
lands_in: ansatte
handled_by: kontor
watched_by: [public]
presents: true
public_states: [open]
stages: [open, sluttet]
stages_text: { open: "vises på forsiden", sluttet: "sluttet" }
done_when: [sluttet]
success: [sluttet]
max_fields: 4
collects:
- { name: name }
- { name: rolle }
- { name: erfaring, type: textarea }
- { name: portrett, type: picture }
personas:
- { id: kommune-skole, need: tilstand, text: "Vi i kommunen skal legge fram en sak om rehabilitering av en barneskole fra 1972 og trenger en tilstandsanalyse politikerne kan beslutte ut fra." }
- { id: borettslag, need: tilstand, text: "Styret i borettslaget lurer på hva som haster mest av tak, fasade og rør. Vi trenger noen som kan gå over byggene og si hva det står til." }
- { id: sprekk, need: tilstand, text: "Det har kommet en sprekk midt på stueveggen og jeg vet ikke om det er farlig. Kan noen komme og se på det?" }
- { id: tilbygg, need: prosjekt, text: "Vi vil bygge på et tilbygg på lageret vårt og trenger noen som kan beskrive arbeidet så vi kan hente inn priser fra entreprenører." }
- { id: skole-i-drift, need: prosjekt, text: "Skolen skal utvides mens den er i drift. Vi trenger en beskrivelse og en fremdriftsplan med byggetrinn." }
- { id: soke-garasje, need: soknad, text: "Tegningene til garasjen er ferdige, men jeg aner ikke hvordan jeg søker kommunen. Kan dere ta søknaden?" }
- { id: ansvarsrett, need: soknad, text: "Vi har prosjektert ombyggingen selv, men mangler noen med ansvarsrett som kan stå for søknaden." }
slideshow:
max_height: 60
slides:
- image: images/bildeserie/01.webp
width: 1867
height: 1400
caption: Tilstandsanalyse for politisk vurdering.
- image: images/bildeserie/02.webp
width: 2365
height: 1400
caption: Tilleggsisolert fasade uten fasadeendring. Tanum skole.
- image: images/bildeserie/03.webp
width: 1867
height: 1400
caption: Fundamenteringen av brannstasjonen i Ytre Enebakk
- image: images/bildeserie/04.webp
width: 1867
height: 1400
caption: Gammel stjernehimmel skal fornyes
- image: images/bildeserie/05.webp
width: 1050
height: 1400
caption: Sprekk midt på stuevegg
- image: images/bildeserie/06.webp
width: 1867
height: 1400
caption: Snart klart for overlevering! Løvenstad omsorgsboliger.
- image: images/bildeserie/07.webp
width: 1867
height: 1400
caption: Omlegging av vannforsyning før etablering av nye boliger
- image: images/bildeserie/08.webp
width: 1777
height: 1400
caption: Utbedring parkett i gymsal, sliping og lakking.
- image: images/bildeserie/09.webp
width: 3629
height: 1400
caption: Tilbygg på skole i drift, i Ås
- image: images/bildeserie/10.webp
width: 3207
height: 1400
caption: Fornying kantine Det Norske Teatret
- image: images/bildeserie/11.webp
width: 1050
height: 1400
caption: Solid veggprofil tilpasset lyd- og brannkrav
- image: images/bildeserie/12.webp
width: 1867
height: 1400
caption: Nye vinduer med tradisjonelt utseende «Restover»-glass som avslører utsikten fra Munkeramme på Hvitsten
- image: images/bildeserie/13.webp
width: 2571
height: 1400
caption: Kjerneved til verandaen og inngangspartiet til Muncheramme
- image: images/bildeserie/14.webp
width: 1050
height: 1400
caption: Drenering og riktige rammer før kunstgressbanen legges mesterfullt ned helt uten gummikuler
- image: images/bildeserie/15.webp
width: 2098
height: 1400
caption: Navnebror sprenger plass til ny brannstasjon
- image: images/bildeserie/16.webp
width: 1283
height: 1400
caption: Kontroll av betong før støping
- image: images/bildeserie/17.webp
width: 1050
height: 1400
caption: Etablering av ny byggekran
- image: images/bildeserie/18.webp
width: 1050
height: 1400
caption: Armeringskontroll før støping
- image: images/bildeserie/19.webp
width: 1867
height: 1400
caption: Brannstasjonens tårn under oppføring blir også klatrevegg
- image: images/bildeserie/20.webp
width: 1867
height: 1400
caption: Her heises Moelvens modulskole i Vestby på plass. Den blir stående i 10 år.
- image: images/bildeserie/21.webp
width: 1867
height: 1400
caption: Nyetablering av vei.
- image: images/bildeserie/22.webp
width: 838
height: 1400
caption: Støpefeil med frosset treverk i søyle fra 1960, avdekket og utbedret
- image: images/bildeserie/23.webp
width: 2095
height: 1400
caption: Nytt kunstgress med varme på Fredrikstad stasjon.
- image: images/bildeserie/24.webp
width: 1050
height: 1400
caption: Sydvendte fasader er utsatt for slagregn. Dette bygget er på byantikvarens gule liste.
- image: images/bildeserie/25.webp
width: 1487
height: 1400
caption: pH-test av borprøver i mur fra forskjellige dybder
+113
View File
@@ -0,0 +1,113 @@
# A physiotherapy clinic: two doors on the front, patients and the
# people who send them; the reception handles everything, therapists
# write the report back and notice who did not turn up.
business: Bakken Fysioterapi
language: en
contact: { name: Marit Bakken, email: marit@bakkenfysio.example }
about: >
Six physiotherapists and a receptionist. People come with pain,
injuries and after operations, on their own or sent by a doctor,
and we treat them over a course of sessions.
doors:
- id: patients
who: someone with pain or an injury, or a patient who already has a time here
- id: referrers
who: a doctor, a hospital ward or an insurer sending someone to us
needs:
- id: new-patient
who: someone with something that hurts
wants: a first appointment with a therapist who suits them
door: patients
lands_in: requests
handled_by: reception
stages: [open, offered, booked, declined]
done_when: [booked, declined]
success: [booked]
max_fields: 4
collects:
- { name: name }
- { name: phone, type: tel }
- { name: what_hurts, type: textarea }
- { name: when, type: select, options: [Mornings, Afternoons, Any time] }
- { name: sent_by_doctor, type: select, options: ["Yes", "No"], optional: true }
- id: move-or-cancel
who: a patient who already has a time and cannot come
wants: the time moved, or the slot freed
door: patients
lands_in: cancellations
handled_by: reception
stages: [open, rebooked, released]
done_when: [rebooked, released]
success: [rebooked]
max_fields: 3
collects:
- { name: name }
- { name: phone, type: tel }
- { name: appointment_day, type: date }
- { name: new_time_wish, optional: true }
- id: referral
who: a GP or a hospital ward sending a patient
wants: the patient seen, and a report back when the course ends
door: referrers
lands_in: referrals
handled_by: reception
stages: [open, accepted, booked, reported, returned]
done_when: [reported, returned]
success: [reported]
# The therapist who treated them writes the report; they see the
# referral from the start.
moves_by: { reported: [therapists] }
watched_by: [therapists]
max_fields: 5
collects:
- { name: patient_name }
- { name: patient_phone, type: tel }
- { name: referrer }
- { name: what_for, type: textarea }
- { name: urgency, type: select, options: [This week, Within a month, Routine] }
- id: insurance-approval
who: the receptionist, before a course that an insurer has to approve
wants: the request sent and its answer kept where the patient's case is
enters_as: reception
lands_in: approvals
handled_by: reception
stages: [open, sent, approved, refused]
done_when: [approved, refused]
success: [approved]
max_fields: 3
collects:
- { name: patient_name }
- { name: insurer }
- { name: sessions }
- { name: case_number, optional: true }
- id: no-show
who: a therapist whose patient did not turn up and did not call
wants: the reception to ring them and get them back in
enters_as: therapists
lands_in: no_shows
handled_by: reception
stages: [open, contacted, rebooked, closed]
done_when: [rebooked, closed]
success: [rebooked]
max_fields: 2
collects:
- { name: patient_name }
- { name: appointment_day, type: date }
- { name: note, optional: true }
# Held out from every model that writes words.
personas:
- { id: runner-knee, need: new-patient, text: "I've been running for years and the outside of my right knee has started hurting after about five kilometres. I'd like someone to have a look, preferably in the mornings." }
- { id: post-surgery-mother, need: new-patient, text: "My mother had a hip replacement three weeks ago and the hospital said she needs training. She can't do much on her own and I'll drive her." }
- { id: sick-child, need: move-or-cancel, text: "I have a session on Thursday at ten but my daughter has a fever and I can't come. Can I move it?" }
- { id: sent-abroad, need: move-or-cancel, text: "Work is sending me abroad next week so my appointment on the 3rd is off. Just free the slot, I'll be in touch when I'm back." }
- { id: gp-shoulder, need: referral, text: "I'm a GP. A patient of mine has a frozen shoulder that isn't improving with what I can offer. I'd like her to start with you and hear how it goes." }
- { id: hospital-discharge, need: referral, text: "Orthopaedic ward here. We're discharging a man after an ankle fracture on Friday and need follow-up rehab arranged near where he lives. He'll need a report for his sick leave." }
- { id: reception-approval, need: insurance-approval, text: "The patient in room two has a policy that covers twelve sessions if the insurer signs off first. I need to send that off and keep track of the answer." }
- { id: therapist-no-show, need: no-show, text: "My two o'clock didn't turn up and didn't call. Second time. Someone needs to ring him." }
+339
View File
@@ -0,0 +1,339 @@
# Tomter Vel, en velforening: fire dører på forsiden (medlemskap,
# melde fra, bidra, naboer imellom) og høringsinnspill rett på
# forsiden, siden den som har en mening om en sak ikke ser seg selv
# som frivillig. Komiteene er gruppene: en søknad om plass i en
# komité velger blant de samme sju som har hver sin pult. Trafikk,
# anlegg og oppslagstavla kan alle lese; kontaktopplysninger vises
# ikke der. Nabohjelp begge veier. Oppslagstavla for deling av utstyr
# står ute med en gang: en nabo som kan låne ut, eller vil låne, sier
# fra rett fra oppslaget, og den som la det ut hører fra dem. Køen er
# innboksen til den som la ut; siden holder ikke rede på hvem som ble
# valgt. Redaktøren, de som står som ansvarlige, tar ned det som står
# igjen.
business: Tomter Vel
language: no
# Styret svarer for sidene som gruppe: ingen konto for innboksen, og
# hvert styremedlem kan foreslå endringer på dem.
contact: { name: Styret i Tomter Vel, email: post@tomtervel.no, group: styret }
# Portal holder gruppene selv: en invitasjon er en plass som venter til
# personen logger inn, og en person er telefonnummeret sitt først. Med
# Vipps-innlogging kan alle logge inn med en gang; til da lager Kanidm
# kontoen ved siden av.
people: memberships
# Avsenderen for all e-post fra siden (gdo på kasse leverer); det
# kasses postfix kan sende for i dag.
mail: { from: "Tomter Vel <tomtervel@klingenbergbygg.no>", reply_to: post@tomtervel.no }
about: >
Velforeningen for Tomter, stiftet i 1947. Sju komiteer drevet på
fritida: arrangementer, elvestien, lekeplassene, høringssvar,
miljøgata, pendlerforhold og trafikk. 157 husstander er medlemmer.
# Komiteene, som gruppene heter, med navnet folk kjenner dem under.
groups:
- { id: arrangementer, label: Arrangementer }
- { id: elvesti, label: Elvesti }
- { id: horingsinstans, label: Høringsinstans }
- { id: lekeplasser, label: Leke- og møteplasser }
- { id: miljogate, label: Miljøgate }
- { id: pendlerforhold, label: Pendlerforhold }
- { id: trafikk, label: Trafikkforhold }
# Styret kan invitere inn i alle grupper som har en pult; hver gruppe kan
# invitere inn i seg selv. Portal oppretter kontoen og en engangslenke.
invites_by: [styret]
# Forsiden åpner beskjedent: to trekk, én rolle hver, ingen knapp,
# før tilbudene lenger ned på samme side. De to velet er til for: en
# husstand som blir medlem, og en nabo som trenger en hånd. Begge har
# noe å gjøre etterpå: medlemmet melder seg ut selv, den som fikk
# hjelp sier selv fra at det er ordnet.
does:
- id: medlem
for: bli-medlem
text: >
Velet taler for Tomter overfor kommunen, holder lekeplassene og
stien i stand og samler naboene på 17. mai og dugnad. 157
husstander er med. Du melder deg inn her, og ut igjen selv når
du vil.
- id: nabo
for: trenger-hjelp
text: >
Trenger du en hånd med snømåking, handling eller skyss, kobler
nabohjelpsgruppa deg med en nabo som kan. Du sier selv fra når
det er ordnet.
# Vedtektene, ord for ord slik årsmøtet vedtok dem: en side der hver
# paragraf er sitt eget kort. Ingen modell rører teksten.
documents:
- id: vedtekter
question: Hva sier vedtektene?
description: Vedtektene for Tomter Vel, av 23.04.2018.
file: documents/tomtervel-vedtekter.md
doors:
- id: medlem
who: en husstand i Tomter som vil bli medlem, betale kontingent, eller melde flytting, ny e-post eller utmelding
- id: melde-fra
who: noen som har sett noe farlig i trafikken, eller noe ødelagt på lekeplassen eller stien
- id: bidra
who: noen som vil stille opp på 17. mai, dugnad eller et arrangement, eller sitte i en komité
- id: naboer
who: en nabo som trenger en hånd med snømåking, handling eller skyss, kan gi en, eller har noe å låne ut
needs:
- id: bli-medlem
who: en husstand i Tomter
wants: å bli medlem og få betalt kontingenten
lands_in: husstander
door: medlem
handled_by: kasserer
stages: [open, betalt, utmeldt]
stages_text: { open: "mottatt", betalt: "betalt", utmeldt: "meldt ut" }
done_when: [betalt, utmeldt]
success: [betalt]
# Medlemmet melder seg ut selv, gjennom sin egen lenke.
moves_by: { utmeldt: [submitter, kasserer] }
mails: { open: submitter, betalt: submitter }
# Betalt kontingent er medlemskapet: husstanden får konto og plass
# blant medlemmene i samme trekk, og det som er medlemmenes eget
# (komitéplass) ligger bak innloggingen.
grants: { betalt: medlemmer }
max_fields: 3
collects:
- { name: name }
- { name: adresse }
- { name: email, type: email }
- { name: telefon, type: tel, optional: true }
- id: endre-medlemskap
who: et medlem som har flyttet, byttet e-post eller vil melde seg ut
wants: at velet har riktige opplysninger om dem
lands_in: medlemsendringer
door: medlem
handled_by: kasserer
stages: [open, oppdatert]
stages_text: { open: "mottatt", oppdatert: "oppdatert" }
done_when: [oppdatert]
success: [oppdatert]
max_fields: 3
collects:
- { name: navn }
- { name: adresse }
- { name: hva_er_nytt, type: textarea }
- id: trafikkfare
who: en som har sett et farlig sted i trafikken
wants: at velet tar det opp med kommunen eller den som eier veien
lands_in: trafikkmeldinger
door: melde-fra
handled_by: trafikk
stages: [open, tatt_opp, ordnet, avvist]
stages_text: { open: "mottatt", tatt_opp: "tatt opp med kommunen", ordnet: "ordnet", avvist: "avvist" }
done_when: [ordnet, avvist]
success: [ordnet]
# Alle kan se hva som er meldt og hvor det står; e-posten vises ikke.
watched_by: [styret, public]
max_fields: 2
collects:
- { name: hvor }
- { name: hva, type: textarea }
- { name: epost, type: email, optional: true }
- id: anleggsfeil
who: en som ser at noe på lekeplassen eller stien er ødelagt
wants: at det blir fikset før noen skader seg
lands_in: anleggsfeil
door: melde-fra
handled_by: lekeplasser
stages: [open, tatt_tak_i, utbedret]
stages_text: { open: "mottatt", tatt_tak_i: "tatt tak i", utbedret: "utbedret" }
done_when: [utbedret]
success: [utbedret]
watched_by: [public]
max_fields: 2
collects:
- { name: hvor, type: select, options: [Lekeplassen, Elvestien, Skøytebanen, Et annet sted] }
- { name: hva, type: textarea }
# Rett på forsiden: den som har en mening om en sak er ikke frivillig.
- id: horingsinnspill
who: en beboer som har en mening om en sak kommunen har på høring
wants: at velet tar det med i sitt svar
lands_in: innspill
handled_by: horingsinstans
watched_by: [styret]
stages: [open, tatt_med, ikke_tatt_med]
stages_text: { open: "mottatt", tatt_med: "tatt med i høringssvaret", ikke_tatt_med: "ikke tatt med" }
done_when: [tatt_med, ikke_tatt_med]
success: [tatt_med]
max_fields: 3
collects:
- { name: navn }
- { name: sak }
- { name: innspill, type: textarea }
- id: hjelpe-til
who: en som vil hjelpe til på et arrangement eller en dugnad
wants: å bli satt opp på noe som passer dem
lands_in: frivillige
door: bidra
handled_by: arrangementer
stages: [open, kontaktet, satt_opp, takket_nei]
stages_text: { open: "mottatt", kontaktet: "kontaktet", satt_opp: "satt opp", takket_nei: "takket nei" }
done_when: [satt_opp, takket_nei]
success: [satt_opp]
max_fields: 3
collects:
- { name: navn }
- { name: telefon, type: tel }
- { name: hva, type: select, multiple: true, options: [17. mai, Juletregranstenning, Skøytedag, Dugnad på elvestien, Det som trengs] }
# Komitéplass er for medlemmer: døra viser veien, skjemaet ligger på
# medlemmenes side bak innloggingen.
- id: komite
who: et medlem som vil sitte i en komité
wants: en plass i den komiteen som driver med det de bryr seg om
lands_in: komitesoknader
door: bidra
enters_as: medlemmer
handled_by: styret
stages: [open, plassert, avslatt]
stages_text: { open: "mottatt", plassert: "plassert i en komité", avslatt: "avslått" }
done_when: [plassert, avslatt]
success: [plassert]
max_fields: 3
collects:
- { name: navn }
- { name: epost, type: email }
- { name: komite, type: select, multiple: true, options_from: groups }
# Nabohjelp: den som trenger en hånd, og den som kan gi en. En
# nabohjelpsgruppe kobler dem; den som fikk hjelp sier fra selv at
# det er ordnet.
- id: trenger-hjelp
who: en beboer som ikke får til noe selv for tiden, som snømåking, handling eller en skyss
wants: at en nabo stiller opp
lands_in: hjelpebehov
# Et behov ingen har tatt tak i på en uke går opp til styret: samme
# sak, samme knapper, på styrets pult i tillegg.
escalate: { open: { days: 7, to: styret } }
door: naboer
handled_by: nabohjelp
stages: [open, formidlet, ordnet, ikke_lost]
stages_text: { open: "mottatt", open_escalated: "hos styret, siden ingen tok den på en uke", formidlet: "formidlet til en nabo", ordnet: "ordnet", ikke_lost: "ikke løst" }
done_when: [ordnet, ikke_lost]
success: [ordnet]
moves_by: { ordnet: [submitter, nabohjelp] }
mails: { open: submitter, formidlet: submitter, ordnet: submitter }
max_fields: 4
collects:
- { name: navn }
- { name: email, type: email }
- { name: adresse }
- { name: hva, type: textarea }
- { name: telefon, type: tel, optional: true }
- id: kan-hjelpe
who: en nabo som kan stille opp når noen trenger det
wants: å bli spurt når det passer
lands_in: hjelpere
door: naboer
handled_by: nabohjelp
stages: [open, registrert, trukket]
stages_text: { open: "mottatt", registrert: "registrert som hjelper", trukket: "trukket" }
done_when: [registrert, trukket]
success: [registrert]
moves_by: { trukket: [submitter, nabohjelp] }
max_fields: 4
collects:
- { name: navn }
- { name: email, type: email }
- { name: telefon, type: tel }
- { name: kan, type: select, multiple: true, options: [Snømåking, Handling, Kjøring, Småfiks i huset, En prat og litt selskap, Det som trengs] }
# Oppslagstavla: ut med en gang, styret hører om det. Svar går
# rett til den som la ut; køen er innboksen deres. Tas ned av den
# som la ut, av redaktøren, eller av klokka etter en måned.
- id: dele-utstyr
who: en nabo som har noe å låne ut, eller trenger å låne noe
wants: et oppslag naboene ser med en gang
lands_in: oppslag
door: naboer
handled_by: redaktor
stages: [open, tatt_ned]
stages_text: { open: "ute", tatt_ned: "tatt ned" }
done_when: [tatt_ned]
success: [tatt_ned]
moves_by: { tatt_ned: [submitter, redaktor] }
mails: { open: post@tomtervel.no }
deadlines: { open: { days: 30, to: tatt_ned } }
# Tavla er offentlig: det er den naboene leser; navn og e-post
# vises ikke der.
watched_by: [public]
public_states: [open]
max_fields: 4
collects:
- { name: navn, private: true }
- { name: email, type: email }
- { name: har_eller_trenger, type: select, options: [Jeg har noe å låne ut, Jeg trenger å låne noe] }
- { name: hva, type: textarea }
# Svaret på et oppslag: fra oppslagets egen rad på tavla, med
# e-post eller innlogget, rett til den som la ut. Redaktøren ser
# svarene og merker dem lest.
- id: melde-seg
who: en nabo som kan låne ut, eller vil låne, det et oppslag gjelder
wants: at den som la ut oppslaget får vite det
about: dele-utstyr
lands_in: svar
handled_by: redaktor
stages: [open, lest]
stages_text: { open: "sendt", lest: "lest" }
done_when: [lest]
success: [lest]
mails: { open: owner }
max_fields: 2
collects:
- { name: email, type: email }
- { name: hilsen, type: textarea, optional: true }
- id: utlegg
who: en i en komité som har lagt ut for noe
wants: pengene tilbake
enters_as: komiteer
lands_in: utlegg
handled_by: kasserer
stages: [open, godkjent, utbetalt, avvist]
stages_text: { open: "mottatt", godkjent: "godkjent", utbetalt: "utbetalt", avvist: "avvist" }
done_when: [utbetalt, avvist]
success: [utbetalt]
max_fields: 3
collects:
- { name: navn }
- { name: belop }
- { name: hva, type: textarea }
# Holdt unna alle modeller som skriver ord.
personas:
- { id: nyinnflyttet, need: bli-medlem, text: "Vi flyttet til Tomter i mars og har hørt at det finnes et vel. Hvordan blir vi med, og hva koster det?" }
- { id: glemte-a-betale, need: bli-medlem, text: "Jeg har vært medlem før men fikk ikke betalt i fjor. Kan jeg bare vippse, og til hvem?" }
- { id: ny-epost, need: endre-medlemskap, text: "Vi har byttet e-postadresse og får ikke lenger noe fra dere." }
- { id: flytter, need: endre-medlemskap, text: "Vi selger huset og flytter til Ski i august, så vi må ut av medlemslista." }
- { id: skolevei, need: trafikkfare, text: "Bilene kjører altfor fort i svingen ved skolen om morgenen, og det er ikke fortau der ungene går." }
- { id: busslomme, need: trafikkfare, text: "Det er umulig å se om det kommer noen når man skal ut fra busslomma ved butikken, hekken har blitt kjempehøy." }
- { id: huske, need: anleggsfeil, text: "Huska på lekeplassen henger i én kjetting. Sønnen min dro i den i går og den holdt så vidt." }
- { id: bru, need: anleggsfeil, text: "Planken på den lille brua på stien langs elva er råtten, jeg gikk nesten gjennom." }
- { id: blokker, need: horingsinnspill, text: "Kommunen skal bygge blokker på jordet bak stasjonen, og jeg synes det er alt for høyt. Kan velet si ifra?" }
- { id: togtider, need: horingsinnspill, text: "Ruter vil kutte det tidlige toget. Jeg pendler til Oslo hver dag og vil at velet skriver til dem om det." }
- { id: vafler, need: hjelpe-til, text: "Jeg kan steke vafler på 17. mai-frokosten hvis dere trenger folk." }
- { id: motorsag, need: hjelpe-til, text: "Har motorsag og ledig helg, kan ta trær langs elvestien hvis det er en dugnad." }
- { id: pendler, need: komite, text: "Jeg pendler og er lei av at ingen snakker med Ruter. Jeg vil gjerne være med i gjengen som jobber med det." }
- { id: planlegger, need: komite, text: "Jeg er arealplanlegger av yrke og kunne bidratt når kommunen sender saker på høring." }
- { id: tilhenger, need: dele-utstyr, text: "Jeg har en tilhenger som står ubrukt mesteparten av året, naboer kan gjerne låne den for en hundrelapp." }
- { id: stige, need: dele-utstyr, text: "Trenger en lang stige en dag i helga for å rense takrenna, er det noen i nærheten som har?" }
- { id: snomaking, need: trenger-hjelp, text: "Jeg er 84 og klarer ikke å måke innkjørselen lenger. Er det noen som kan hjelpe meg når det snør?" }
- { id: nyoperert, need: trenger-hjelp, text: "Jeg er nyoperert i hofta og kommer meg ikke til butikken på noen uker. Kunne noen handlet for meg?" }
- { id: hjemmekontor, need: kan-hjelpe, text: "Jeg jobber hjemmefra og kan godt måke eller handle for noen som ikke får det til selv." }
- { id: pensjonert-elektriker, need: kan-hjelpe, text: "Pensjonert elektriker, har bil og god tid. Si fra om noen trenger skyss eller en hånd med småting." }
- { id: kvittering, need: utlegg, text: "Jeg kjøpte pølser og kakao til skøytedagen for 1 840 kroner, her er kvitteringa, vil ha det igjen." }
+233
View File
@@ -0,0 +1,233 @@
# UHHM, uhhm.no: the studio that builds portal and carries redoal.
# Rebuilt from the live site (uhhm/questions) on 2026-09-23. The five
# buckets the site already holds keep their live state and event
# names (`events:`), so every record on the owners' desk stays where
# it is. Two are new: a business trying the trainer on its own
# workflow (`trials`, approved by a person before anything is built),
# and what reaches UHHM as the custodian of the redoal network
# (`custody_requests`, a desk of its own).
business: UHHM
language: en
contact: { name: Bendik Aagaard Lynghaug, email: bl@uhhm.no }
# Every mail the site sends comes from here (gdo on ergo delivers).
mail: { from: "UHHM <portal@uhhm.no>", reply_to: bl@uhhm.no }
about: >
UHHM builds software around a clear argument: infrastructure, tools
and products for organizations that can say what problem they have.
It also builds and carries the redoal network - the gesture math,
the relay, the first node, and the portal this site runs on - and
answers for what that network keeps.
groups:
- { id: owners, label: Owners }
# The people who answer for the redoal network: they host its first
# node and relay, keep what is left there, and decide what stays.
- { id: custodians, label: redoal custodians, invited_by: [owners] }
# Owners onboard into every desk; a custodian can vouch for another.
invites_by: [owners]
# The front door opens modestly: one or two features, one role each,
# and no button, before the offers further down the same page. The
# two roles UHHM exists for: an organization with a problem, and the
# people on the redoal network it keeps.
does:
- id: software
for: commission
text: >
Software built around a clear argument. Infrastructure, tools
and products for organizations that can say what problem they
have - and a working draft of your own workflow as a site,
before you pay for anything.
- id: redoal
for: custody
text: >
The redoal network, built and carried here: the gesture math,
the relay, the first node, and the portal this site runs on.
UHHM answers for what that network keeps.
# Things to look at before asking for anything.
shows:
- id: built
text: A few things already out in the world.
resource:
public: true
source: { kind: gitea_starred, username: bl }
jq: >
.[] | {name: .name, description: .description,
url: (if .website != null and .website != "" then .website
elif .private then null
else .html_url end)}
- id: voices
text: Live from the redoal relay - what has been left at places so far.
resource:
public: true
source: { kind: url, url: https://relay.redoal.com/pulse }
jq: >
{ "name": (.voices_echoed | tostring),
"description": "voices echoed so far" }
empty: The first voice has not echoed yet.
needs:
- id: commission
who: an organization with a problem it wants software to solve
wants: a considered reply to a brief, from people who read the whole thing
lands_in: projects
handled_by: owners
stages: [open, accepted, declined]
done_when: [accepted, declined]
success: [accepted]
events: { open: submitted }
stages_text: { open: "received", accepted: "taken on", declined: "not a fit for us" }
# The client plays too: they can withdraw the brief themselves.
moves_by: { declined: [submitter, owners] }
mails: { open: submitter, accepted: submitter, declined: submitter }
max_fields: 4
collects:
- { name: name }
- { name: email, type: email }
- { name: project, type: textarea }
- { name: organization }
- { name: org_contact, optional: true }
# The client feature: the trainer tried on a real business. A person
# approves each intake before anything is built from it.
- id: trial
who: someone who runs a business where requests, approvals and handovers get lost, and wants to see it as a site before committing to anything
wants: a first draft of a site for their own roles, built from their own words and approved by a person first
lands_in: trials
handled_by: owners
stages: [open, approved, previewed, declined]
done_when: [previewed, declined]
success: [previewed]
stages_text: { open: "received", approved: "approved for a draft", previewed: "a preview is ready", declined: "not a fit for us" }
mails: { open: submitter, approved: submitter, previewed: submitter, declined: submitter }
attended_by: >
approved -> previewed: the n8n workflow that builds the draft
site from an approved intake (docker, rauthy, portal content)
and sends the preview link. Until it exists, owners run
portal-trainer by hand and press the button.
max_fields: 6
collects:
- { name: business }
- { name: email, type: email }
- { name: what_we_do, type: textarea }
- { name: who_comes_to_us, type: textarea }
- { name: what_we_keep_track_of, type: textarea }
- { name: who_is_involved, type: textarea }
- { name: what_slows_us_down, type: textarea, optional: true }
- id: collaborate
who: someone who wants to work with us on what we build
wants: to be read as a person, and invited in if there is a fit
lands_in: applicants
handled_by: owners
stages: [open, invited, active, departed, declined]
done_when: [departed, declined]
success: [departed]
events: { open: applied, active: onboarded }
# Declined before starting; after that a person departs.
turned_down_from: [open, invited]
stages_text: { open: "received", invited: "invited in", active: "working with us", departed: "moved on", declined: "not a fit for us" }
max_fields: 3
collects:
- { name: name }
- { name: email, type: email }
- { name: interest, type: textarea }
- { name: note, type: textarea, optional: true }
- id: subscribe
who: someone who wants to hear from us when there is something to say
wants: a note now and then, and an easy way out
lands_in: subscribers
handled_by: owners
stages: [open, unsubscribed]
done_when: [unsubscribed]
events: { open: subscribed }
stages_text: { open: "on the list", unsubscribed: "off the list" }
moves_by: { unsubscribed: [submitter, owners] }
max_fields: 2
collects:
- { name: name }
- { name: email, type: email }
# This site proposes its own changes through itself.
- id: propose
who: a visitor who sees how a page on this site should change
wants: the change read by a person and, if approved, made
lands_in: development_proposals
handled_by: owners
stages: [open, approved, rejected]
done_when: [approved, rejected]
success: [approved]
events: { open: proposed }
stages_text: { open: "received", approved: "approved", rejected: "turned down" }
# The site changes in the open: anyone can read what was approved,
# without who proposed it.
watched_by: [public]
public_states: [approved]
max_fields: 3
collects:
- { name: submitted_by, private: true }
- { name: email, type: email, optional: true }
- { name: page, optional: true }
- { name: rationale, type: textarea }
- { name: proposed_yaml, type: textarea }
# The custodian role, on the front door: UHHM answers for the redoal
# network it hosts. Owners see these too, and move nothing.
- id: custody
who: someone who runs, builds on, or is affected by the redoal network and needs the people who keep its first node
wants: an answer from a custodian, and action where the network keeps something it should not
lands_in: custody_requests
handled_by: custodians
watched_by: [owners]
stages: [open, in_dialogue, resolved, declined]
done_when: [resolved, declined]
success: [resolved]
stages_text: { open: "received", in_dialogue: "in dialogue with a custodian", resolved: "resolved", declined: "closed without action" }
# The person affected says when it is resolved, not only the custodian.
moves_by: { resolved: [submitter, custodians] }
mails: { open: submitter, resolved: submitter, declined: submitter }
max_fields: 4
collects:
- { name: name }
- { name: email, type: email }
- { name: about, type: select, options: [Running a node of my own, Building on the network, Something the network keeps about me, Something else] }
- { name: what, type: textarea }
# Internal: a relationship worth tracking before it is a project.
- id: prospect
who: an owner who has met an organization worth following up
wants: it written down and walked through its states from the desk
enters_as: owners
lands_in: organizations
handled_by: owners
stages: [prospect, client, past_client]
done_when: [past_client]
skippable: [client]
stages_text: { prospect: "a prospect", client: "a client", past_client: "a past client" }
events: { prospect: identified, client: became_client, past_client: churned }
max_fields: 2
collects:
- { name: name }
- { name: contact }
- { name: note, type: textarea, optional: true }
# Held out from every model that writes words. The first eight are the
# 2026-09-21 set (runs/uhhm-2026-09-21); the rest are for what is new.
personas:
- { id: architecture-firm, need: commission, text: "We run a small architecture firm and our project files are scattered across three cloud drives. We want to pay someone to set up proper storage and backups we control ourselves." }
- { id: climbing-gym-founder, need: commission, text: "I have an idea for a booking app for climbing gyms and I'm looking for a team that can build the first version with me." }
- { id: municipality-buyer, need: commission, text: "Our municipality needs an internal tool for tracking building permits. We are looking for a vendor who can scope it and deliver it." }
- { id: exhibition-visitor, need: subscribe, text: "I saw your drawing network at an exhibition and liked it. I don't want to get involved, I'd just like to know when there is news." }
- { id: tech-journalist, need: subscribe, text: "I write about Nordic technology. Keep me posted on what you release so I can cover it." }
- { id: rust-developer, need: collaborate, text: "I'm a Rust developer between jobs and I like that you build in the open. I would love to contribute, and maybe join you." }
- { id: interaction-designer, need: collaborate, text: "I'm an interaction designer. I want to work with you on the drawing interface." }
- { id: student-intern, need: collaborate, text: "I'm a computer science student looking for a summer internship doing infrastructure work." }
- { id: plumber-owner, need: trial, text: "I run a plumbing company with four vans. Jobs come in by phone and text and some get lost. I'd like to see how this would look for us before I spend any money." }
- { id: dance-school, need: trial, text: "We are a dance school. Enrolments, cancellations and invoices all go through one email inbox that only I understand. Can you show me a version made for us?" }
- { id: node-runner, need: custody, text: "I run a small server in Berlin and want to host a redoal node that peers with yours. Who do I talk to?" }
- { id: recorded-name, need: custody, text: "Someone left a recording on redoal that says my full name and where I live. I want it gone, and I want to know who is responsible for that network." }
- { id: app-builder, need: custody, text: "I'm building a music app and would like to use redoal's gesture addresses in it. Is that possible, and who decides?" }
- { id: wording-fix, need: propose, text: "The subscribe page should say how often you actually write. I'd like to suggest that exact change to the page." }
- { id: rewrite, need: propose, text: "One page on this site reads wrong to me and I know exactly how I'd rewrite it. Where do I send the new text?" }
+526
View File
@@ -0,0 +1,526 @@
{
"questions/index.yaml": {
"question": "Hvordan inkluderer vi ditt bygg i framtiden?",
"description": "Med vår erfaring får vi kartlagt **tilstand**, utarbeidet **prosjekt** og godkjent **søknad** for ditt bygg.",
"opener": {
"heading": "Dette gjør vi",
"description": "For kommuner, borettslag, bedrifter og private.",
"features": {
"tilstand": {
"heading": "Tilstand, målt og dokumentert",
"description": "Vi utarbeider tilstandsrapporter etter NS-EN 3424 og NS 3423, med befaring, materialprøver og termofotografering. Skal bygget rives, leverer vi miljøsaneringsrapport; energibruk og besparelser hører med i vurderingen. Vi har samarbeidet med [Drammen Kommune](https://drammen.kommune.no), [Nordre Follo Kommune](https://nordrefollo.kommune.no) og [Bølerskogens Borettslag](https://bolerskogenborettslag.no/).",
"icon": "clipboard-check"
},
"soknad": {
"heading": "Prosjekt og søknad, med ansvarsrett",
"description": "Vi lager arbeidsbeskrivelse opp mot [NS 3420](https://standard.no/fagomrader/ns-3420-/) og fremdriftsplan, og utarbeider byggesøknaden. Vi har sentral [godkjenning](https://sgregister.dibk.no/enterprises/976015711) innen flere fagområder og kan stå med det offentligrettslige ansvaret. Samarbeidspartner: [Westra Engineering AS](https://www.westra-engineering.no/).",
"icon": "file-check"
}
}
},
"needs": {
"tilstand": {
"heading": "Få kartlagt byggets tilstand",
"description": "Vi utarbeider tilstandsrapporter som representerer bygget med hensyn til fremtidige mål.",
"button": "Kom i gang",
"encouragement": "Mindre stillstand etter dette.",
"icon": "clipboard-list",
"road_title": "Slik går det videre",
"road_description": "Vi avtaler befaring og sender deg et tilbud. Du sier selv ja eller nei, og med et ja får du en innlogging der du følger oppdraget og henter dokumentene.",
"road_icon": "route",
"who_title": "Hvem leser dette",
"who_description": "Fredrik på kontoret leser henvendelsen og tar kontakt. Du når ham også på fredrik@klingenbergbygg.no.",
"who_icon": "users",
"form_title": "Om bygget",
"form_description": "Det vi trenger for å komme på befaring. Har du tegninger, bilder eller video, tar vi gjerne imot dem.",
"labels": {
"name": "Navn",
"email": "E-post",
"telefon": "Telefon",
"adresse": "Hvor ligger eiendommen?",
"eiendom": "Hva slags eiendom er det?",
"mangler": "Hvilke mangler ønskes adressert?",
"tegninger": "Bilder, tegninger, skisser eller video"
},
"hints": {
"name": "Navn",
"email": "bruker@eksempel.no",
"telefon": "Telefonnummer",
"adresse": "Adresse",
"mangler": "Forfall, skader eller annet…"
}
},
"prosjekt": {
"heading": "Prosjektér dine planer med oss",
"description": "Ivareta eksisterende ressurser for et velfungerende og helhetlig bygg.",
"button": "Start samarbeidet",
"encouragement": "Gi det beste grunnlaget for utførelse.",
"icon": "ruler",
"road_title": "Slik går det videre",
"road_description": "Vi avtaler befaring og sender deg et tilbud. Du sier selv ja eller nei, og med et ja får du en innlogging der du følger oppdraget og henter dokumentene.",
"road_icon": "route",
"who_title": "Hvem leser dette",
"who_description": "Fredrik på kontoret leser henvendelsen og tar kontakt. Du når ham også på fredrik@klingenbergbygg.no.",
"who_icon": "users",
"form_title": "Om planene",
"form_description": "Beskriv hva du ønsker for bygget. Har du noe digitalt å vise oss, blir det lettere å vite hvor vi skal starte.",
"labels": {
"name": "Navn",
"email": "E-post",
"telefon": "Telefon",
"adresse": "Hvor ligger eiendommen?",
"planer": "Hva er dine planer for bygget?",
"oppstart": "Ønsket start",
"skisser": "Bilder, CAD-filer og skisser"
},
"hints": {
"name": "Navn",
"email": "bruker@eksempel.no",
"telefon": "Telefonnummer",
"adresse": "Adresse",
"planer": "Ønsker for bygget…"
}
},
"soknad": {
"heading": "Ta det første spadetaket med en godkjent søknad",
"description": "Er bygget ferdig prosjektert, kan vi utarbeide en byggesøknad og utførelsesbeskrivelse for offentlig godkjenning.",
"button": "Send henvendelse",
"encouragement": "Nesten som å ha gravemaskin!",
"icon": "file-text",
"road_title": "Slik går det videre",
"road_description": "Vi går gjennom det du har, avtaler befaring eller forhåndskonferanse, og sender deg et tilbud. Du sier selv ja eller nei, og med et ja får du en innlogging der du følger søknaden og henter dokumentene.",
"road_icon": "route",
"who_title": "Hvem leser dette",
"who_description": "Fredrik på kontoret leser henvendelsen og tar kontakt. Du når ham også på fredrik@klingenbergbygg.no.",
"who_icon": "users",
"form_title": "Om tiltaket",
"form_description": "Hva skal bygges, og hvor. Avhengig av størrelsen kan vi holde forhåndskonferanse med kommunen først.",
"labels": {
"name": "Navn",
"email": "E-post",
"telefon": "Telefon",
"adresse": "Hvor ligger eiendommen?",
"tiltak": "Hva går tiltaket ut på?",
"tegninger": "Tegninger og prosjektering"
},
"hints": {
"name": "Navn",
"email": "bruker@eksempel.no",
"telefon": "Telefonnummer",
"adresse": "Adresse",
"tiltak": "Tilbygg, ombygging, nybygg…"
},
"paused": "Akkurat nå har vi ikke kapasitet til nye søknadsoppdrag; vi åpner igjen så snart vi kan."
}
},
"who": {
"heading": "Hvem består Klingenberg Bygg av?",
"description": "Mennesker, verdier og erfaringer.",
"items": {
"erfaring": {
"heading": "Erfaringene",
"description": "Skoler i drift, brannstasjoner, omsorgsboliger, kantina på Det Norske Teatret og en Munch-eiendom på Hvitsten. Vi har gått over, prosjektert og fulgt opp bygg for kommuner, borettslag, bedrifter og private, fra borprøver i gammel mur til kunstgress på Fredrikstad stasjon.",
"icon": "award"
},
"people-ansatte": {
"heading": "Menneskene",
"description": "De som går befaringene, skriver rapportene og står for søknadene.",
"empty": "Snart presenterer vi oss her.",
"icon": "users"
}
}
}
},
"questions/received/tilstand.yaml": {
"question": "Vent på svar på din henvendelse!",
"description": "Vi vil gå gjennom din henvendelse og om mulig komme med et tilbud så fort vi kan.",
"next_heading": "Vi tar kontakt for befaring",
"next_description": "Du har fått en e-post som bekrefter at henvendelsen om tilstandsrapport er mottatt. Fredrik tar kontakt for å avtale befaring; spørsmål i mellomtiden går til fredrik@klingenbergbygg.no."
},
"questions/received/prosjekt.yaml": {
"question": "Vent på svar på din henvendelse!",
"description": "Vi vil gå gjennom din henvendelse og om mulig komme med et tilbud så fort vi kan.",
"next_heading": "Vi tar kontakt for befaring",
"next_description": "Du har fått en e-post som bekrefter at henvendelsen om prosjektering er mottatt. Fredrik tar kontakt for å avtale befaring; spørsmål i mellomtiden går til fredrik@klingenbergbygg.no."
},
"questions/received/soknad.yaml": {
"question": "Vent på svar på din henvendelse!",
"description": "Vi vil gå gjennom din henvendelse og om mulig komme med et tilbud så fort vi kan.",
"next_heading": "Vi tar kontakt for befaring",
"next_description": "Du har fått en e-post som bekrefter at henvendelsen om byggesøknad er mottatt. Fredrik tar kontakt for å avtale befaring; spørsmål i mellomtiden går til fredrik@klingenbergbygg.no."
},
"questions/decide/tilstand.yaml": {
"question": "Vil du gå videre med tilbudet?",
"description": "Tilbudet på tilstandsrapporten har du fått i egen e-post fra oss. Her sier du ja eller nei.",
"moves": {
"akseptert": {
"heading": "Ja, jeg godtar tilbudet",
"description": "Vi setter i gang. Du får en innlogging på e-post, der du følger oppdraget og henter dokumentene når de er klare.",
"button": "Godta tilbudet"
},
"avslatt": {
"heading": "Nei takk",
"description": "Henvendelsen avsluttes hos oss uten oppdrag. Du kan når som helst sende en ny.",
"button": "Takk nei"
}
}
},
"questions/decide/prosjekt.yaml": {
"question": "Vil du gå videre med tilbudet?",
"description": "Tilbudet på prosjekteringen har du fått i egen e-post fra oss. Her sier du ja eller nei.",
"moves": {
"akseptert": {
"heading": "Ja, jeg godtar tilbudet",
"description": "Vi setter i gang. Du får en innlogging på e-post, der du følger oppdraget og henter dokumentene når de er klare.",
"button": "Godta tilbudet"
},
"avslatt": {
"heading": "Nei takk",
"description": "Henvendelsen avsluttes hos oss uten oppdrag. Du kan når som helst sende en ny.",
"button": "Takk nei"
}
}
},
"questions/decide/soknad.yaml": {
"question": "Vil du gå videre med tilbudet?",
"description": "Tilbudet på byggesøknaden har du fått i egen e-post fra oss. Her sier du ja eller nei.",
"moves": {
"akseptert": {
"heading": "Ja, jeg godtar tilbudet",
"description": "Vi setter i gang. Du får en innlogging på e-post, der du følger oppdraget og henter dokumentene når de er klare.",
"button": "Godta tilbudet"
},
"avslatt": {
"heading": "Nei takk",
"description": "Henvendelsen avsluttes hos oss uten oppdrag. Du kan når som helst sende en ny.",
"button": "Takk nei"
}
}
},
"questions/kontor/index.yaml": {
"question": "Hva ligger på pulten nå?",
"description": "Alle henvendelser og oppdrag, fra første melding til levert dokument.",
"confirm": "Bekreft",
"buckets": {
"tilstandsrapporter": {
"heading": "Tilstandsrapporter",
"description": "Henvendelser om tilstandsrapport, fra mottatt til levert.",
"moves": {
"open->befaring": "Befaring avtalt",
"open->avslatt": "Avslutt uten oppdrag",
"befaring->tilbud": "Tilbud sendt",
"befaring->avslatt": "Avslutt uten oppdrag",
"tilbud->avslatt": "Avslutt uten oppdrag",
"akseptert->i_arbeid": "Arbeidet er i gang",
"i_arbeid->levert": "Levert"
},
"list_title": "Tilstandsrapporter",
"list_note": "Hver rad er én henvendelse. Knappene fører opp det du nettopp har gjort; kunden får e-post ved befaring, tilbud og levering, og sier selv ja til tilbudet."
},
"prosjekteringer": {
"heading": "Prosjekteringer",
"description": "Henvendelser om prosjektering, fra mottatt til levert.",
"moves": {
"open->befaring": "Befaring avtalt",
"open->avslatt": "Avslutt uten oppdrag",
"befaring->tilbud": "Tilbud sendt",
"befaring->avslatt": "Avslutt uten oppdrag",
"tilbud->avslatt": "Avslutt uten oppdrag",
"akseptert->i_arbeid": "Arbeidet er i gang",
"i_arbeid->levert": "Levert"
},
"list_title": "Prosjekteringer",
"list_note": "Hver rad er én henvendelse. Knappene fører opp det du nettopp har gjort; kunden får e-post ved befaring, tilbud og levering, og sier selv ja til tilbudet."
},
"soknader": {
"heading": "Byggesøknader",
"description": "Henvendelser om byggesøknad, fra mottatt til levert.",
"moves": {
"open->befaring": "Befaring avtalt",
"open->avslatt": "Avslutt uten oppdrag",
"befaring->tilbud": "Tilbud sendt",
"befaring->avslatt": "Avslutt uten oppdrag",
"tilbud->avslatt": "Avslutt uten oppdrag",
"akseptert->i_arbeid": "Arbeidet er i gang",
"i_arbeid->levert": "Levert"
},
"list_title": "Byggesøknader",
"list_note": "Hver rad er én henvendelse. Knappene fører opp det du nettopp har gjort; kunden får e-post ved befaring, tilbud og levering, og sier selv ja til tilbudet."
},
"leveranser": {
"heading": "Leverte dokumenter",
"description": "Rapporter, tegninger og vedtak som er sendt til kunder.",
"moves": {
"open->arkivert": "Arkiver"
},
"list_title": "Leveranser",
"list_note": "Hver rad er ett dokument en kunde har fått. Arkiver når saken er avsluttet."
},
"ansatte": {
"heading": "Ansatte på forsiden",
"description": "Menneskene slik besøkende ser dem. Hver retter sitt eget kort; herfra kan et kort tas ned.",
"moves": {
"open->sluttet": "Tatt av forsiden"
},
"list_title": "Ansatte",
"list_note": "Hver rad er én person på forsiden."
}
},
"links": {
"leveranse": {
"heading": "Lever et dokument til en kunde",
"description": "Rapporten, tegningene eller vedtaket. Kunden får e-post og henter det innlogget.",
"button": "Ny leveranse"
},
"ansatt": {
"heading": "Ditt kort på forsiden",
"description": "Rolle, erfaring og portrett, slik besøkende ser deg.",
"button": "Åpne"
}
},
"invites": {
"kontor": {
"heading": "Gi en kollega tilgang",
"description": "De får en konto og plass på kontoret, og ser de samme sakene som deg.",
"button": "Inviter",
"form_title": "Hvem",
"form_description": "Navnet deres, og adressen kontoen og engangslenken går til.",
"labels": {
"name": "Navn",
"phone": "Telefon",
"email": "E-post"
}
},
"kunder": {
"heading": "Gi en kunde tilgang",
"description": "For en kunde som ikke kom inn gjennom et tilbud. De får en konto og ser sine egne oppdrag.",
"button": "Inviter",
"form_title": "Hvem",
"form_description": "Navnet deres, og adressen kontoen og engangslenken går til.",
"labels": {
"name": "Navn",
"phone": "Telefon",
"email": "E-post"
}
}
},
"invited": {
"heading": "Sendte invitasjoner",
"description": "Hver invitasjon og hvor den står. En lenke som går ut ubrukt, kan sendes på nytt.",
"done": "Er inne",
"again": "Send på nytt",
"list_title": "Hvem som er invitert",
"list_note": "Hver rad er én invitasjon. Den blir ferdig av seg selv når personen logger inn, og står som utløpt når lenken gikk ut ubrukt."
},
"suggestions": {
"heading": "Forslag til endringer på siden",
"description": "Det de som står som ansvarlige for et spørsmål, har foreslått å endre.",
"list_title": "Forslag",
"list_note": "Hver rad er ett forslag, med siden det gjelder.",
"looking": "Vi ser på det",
"changed": "Endringen er gjort",
"declined": "Gjøres ikke"
}
},
"questions/kunder/index.yaml": {
"question": "Hvor står oppdraget ditt?",
"description": "Her følger du dine egne oppdrag hos Klingenberg Bygg og henter dokumentene vi har levert.",
"confirm": "Bekreft",
"buckets": {
"leveranser": {
"heading": "Dokumenter til deg",
"description": "Rapporter, tegninger og vedtak vi har levert. Trykk på filnavnet for å hente dokumentet.",
"moves": {},
"list_title": "Dokumenter",
"list_note": "Hver rad er ett dokument vi har levert til deg."
},
"tilstandsrapporter": {
"heading": "Tilstandsrapporter",
"description": "Dine oppdrag om tilstandsrapport, og hvor langt de har kommet.",
"moves": {},
"list_title": "Tilstandsrapporter",
"list_note": "Hver rad er ett av dine egne oppdrag og hvor langt det har kommet."
},
"prosjekteringer": {
"heading": "Prosjekteringer",
"description": "Dine oppdrag om prosjektering, og hvor langt de har kommet.",
"moves": {},
"list_title": "Prosjekteringer",
"list_note": "Hver rad er ett av dine egne oppdrag og hvor langt det har kommet."
},
"soknader": {
"heading": "Byggesøknader",
"description": "Dine oppdrag om byggesøknad, og hvor langt de har kommet.",
"moves": {},
"list_title": "Byggesøknader",
"list_note": "Hver rad er ett av dine egne oppdrag og hvor langt det har kommet."
}
}
},
"questions/kontor/leveranse.yaml": {
"heading": "Lever et dokument til en kunde",
"description": "Last opp rapporten, tegningene eller vedtaket. Kunden får e-post og henter dokumentet innlogget.",
"button": "Lever",
"encouragement": "Kunden får beskjed med en gang.",
"icon": "send",
"road_title": "Hva skjer",
"road_description": "Dokumentet legges på kundens side, og kunden får e-post om at det ligger der.",
"road_icon": "route",
"who_title": "Hvem ser dette",
"who_description": "Kunden med den e-postadressen du oppgir, og kontoret.",
"who_icon": "users",
"form_title": "Leveransen",
"form_description": "Bruk den e-postadressen kunden logger inn med.",
"labels": {
"email": "Kundens e-post",
"hva": "Hva er levert",
"dokument": "Dokument"
},
"hints": {
"email": "kunde@eksempel.no",
"hva": "Tilstandsrapport for Storgata 12",
"dokument": ""
},
"question": "Hvilket dokument er klart til kunden?",
"page_description": "Ferdige rapporter, tegninger og vedtak leveres her."
},
"questions/kontor/leveranse-sent.yaml": {
"question": "Hva skjer nå?",
"description": "Dokumentet er levert.",
"next_heading": "Kunden har fått beskjed",
"next_description": "Kunden har fått e-post og finner dokumentet på sin side. Leveransen ligger i listen på pulten til du arkiverer den."
},
"aggregates.yaml": {
"tilstandsrapporter": {
"open": {
"subject": "Vi har mottatt henvendelsen om {adresse}",
"body": "Hei {name},\n\nVi har mottatt henvendelsen din om tilstandsrapport for {adresse}. Fredrik tar kontakt for å avtale befaring.\n\nVil du trekke henvendelsen, gjør du det her:\n{site}/decide/tilstand?chain={chain}&email={email}\n\nKlingenberg Bygg"
},
"befaring": {
"subject": "Befaring avtalt for {adresse}",
"body": "Hei {name},\n\nVi har avtalt befaring for {adresse}. Etter befaringen sender vi deg et tilbud.\n\nVil du trekke henvendelsen, gjør du det her:\n{site}/decide/tilstand?chain={chain}&email={email}\n\nKlingenberg Bygg"
},
"tilbud": {
"subject": "Tilbud på tilstandsrapport for {adresse}",
"body": "Hei {name},\n\nTilbudet på tilstandsrapport for {adresse} er sendt deg i egen e-post. Si ja eller nei her:\n{site}/decide/tilstand?chain={chain}&email={email}\n\nMed et ja får du en innlogging der du følger oppdraget og henter dokumentene. Svar på denne e-posten om du lurer på noe.\n\nKlingenberg Bygg"
},
"akseptert": {
"subject": "Tilbudet for {adresse} er godtatt",
"body": "{name} ({email}) har godtatt tilbudet på tilstandsrapport for {adresse}.\n\nOppdraget ligger på pulten: {site}/kontor"
},
"levert": {
"subject": "Tilstandsrapport for {adresse} er levert",
"body": "Hei {name},\n\nTilstandsrapport for {adresse} er levert. Dokumentene henter du innlogget:\n{site}/kunder\n\nTakk for oppdraget.\n\nKlingenberg Bygg"
}
},
"prosjekteringer": {
"open": {
"subject": "Vi har mottatt henvendelsen om {adresse}",
"body": "Hei {name},\n\nVi har mottatt henvendelsen din om prosjektering for {adresse}. Fredrik tar kontakt for å avtale befaring.\n\nVil du trekke henvendelsen, gjør du det her:\n{site}/decide/prosjekt?chain={chain}&email={email}\n\nKlingenberg Bygg"
},
"befaring": {
"subject": "Befaring avtalt for {adresse}",
"body": "Hei {name},\n\nVi har avtalt befaring for {adresse}. Etter befaringen sender vi deg et tilbud.\n\nVil du trekke henvendelsen, gjør du det her:\n{site}/decide/prosjekt?chain={chain}&email={email}\n\nKlingenberg Bygg"
},
"tilbud": {
"subject": "Tilbud på prosjektering for {adresse}",
"body": "Hei {name},\n\nTilbudet på prosjektering for {adresse} er sendt deg i egen e-post. Si ja eller nei her:\n{site}/decide/prosjekt?chain={chain}&email={email}\n\nMed et ja får du en innlogging der du følger oppdraget og henter dokumentene. Svar på denne e-posten om du lurer på noe.\n\nKlingenberg Bygg"
},
"akseptert": {
"subject": "Tilbudet for {adresse} er godtatt",
"body": "{name} ({email}) har godtatt tilbudet på prosjektering for {adresse}.\n\nOppdraget ligger på pulten: {site}/kontor"
},
"levert": {
"subject": "Prosjektering for {adresse} er levert",
"body": "Hei {name},\n\nProsjektering for {adresse} er levert. Dokumentene henter du innlogget:\n{site}/kunder\n\nTakk for oppdraget.\n\nKlingenberg Bygg"
}
},
"soknader": {
"open": {
"subject": "Vi har mottatt henvendelsen om {adresse}",
"body": "Hei {name},\n\nVi har mottatt henvendelsen din om byggesøknad for {adresse}. Fredrik tar kontakt for å avtale befaring.\n\nVil du trekke henvendelsen, gjør du det her:\n{site}/decide/soknad?chain={chain}&email={email}\n\nKlingenberg Bygg"
},
"befaring": {
"subject": "Befaring avtalt for {adresse}",
"body": "Hei {name},\n\nVi har avtalt befaring for {adresse}. Etter befaringen sender vi deg et tilbud.\n\nVil du trekke henvendelsen, gjør du det her:\n{site}/decide/soknad?chain={chain}&email={email}\n\nKlingenberg Bygg"
},
"tilbud": {
"subject": "Tilbud på byggesøknad for {adresse}",
"body": "Hei {name},\n\nTilbudet på byggesøknad for {adresse} er sendt deg i egen e-post. Si ja eller nei her:\n{site}/decide/soknad?chain={chain}&email={email}\n\nMed et ja får du en innlogging der du følger oppdraget og henter dokumentene. Svar på denne e-posten om du lurer på noe.\n\nKlingenberg Bygg"
},
"akseptert": {
"subject": "Tilbudet for {adresse} er godtatt",
"body": "{name} ({email}) har godtatt tilbudet på byggesøknad for {adresse}.\n\nOppdraget ligger på pulten: {site}/kontor"
},
"levert": {
"subject": "Byggesøknad for {adresse} er levert",
"body": "Hei {name},\n\nByggesøknad for {adresse} er levert. Dokumentene henter du innlogget:\n{site}/kunder\n\nTakk for oppdraget.\n\nKlingenberg Bygg"
}
},
"leveranser": {
"open": {
"subject": "{hva} ligger klar til deg",
"body": "Hei,\n\n{hva} er levert fra Klingenberg Bygg. Logg inn og hent dokumentet her:\n{site}/kunder\n\nSvar på denne e-posten om noe mangler.\n\nKlingenberg Bygg"
}
}
},
"site.yaml": {
"invite": {
"subject": "Din innlogging hos {site_name}",
"body": "Hei {name},\n\nDu har fått en konto hos {site_name}, med plass blant {group}. Velg passord eller passnøkkel her, lenken virker fram til {expires}:\n\n{link}\n\nBrukernavnet ditt er {username}. Etterpå logger du inn på {site}."
}
},
"questions/kontor/ansatt-sent.yaml": {
"question": "Kortet ditt er lagret",
"description": "Slik står du nå på forsiden.",
"next_heading": "Vil du endre noe?",
"next_description": "Åpne «Ditt kort på forsiden» igjen: det er fylt ut med det du har, og det du lagrer erstatter det.",
"see_all": {
"heading": "Se alle ansatte",
"description": "",
"button": "Åpne"
}
},
"questions/kontor/ansatt.yaml": {
"heading": "Ditt kort på forsiden",
"description": "Slik står du blant menneskene på forsiden. Rett det du vil og lagre; du har ett kort, og det nye erstatter det gamle.",
"button": "Lagre kortet",
"encouragement": "",
"icon": "id-card",
"requires_title": "",
"requires_description": "",
"requires_icon": "",
"road_title": "Når du lagrer",
"road_description": "Kortet ditt på forsiden endres med en gang.",
"road_icon": "route",
"who_title": "Hvem ser det",
"who_description": "Alle som besøker siden. Navnet ditt er det du er logget inn med.",
"who_icon": "users",
"form_title": "Kortet ditt",
"form_description": "",
"labels": {
"name": "Navn",
"rolle": "Rolle",
"erfaring": "Erfaring",
"portrett": "Portrett"
},
"hints": {
"name": "",
"rolle": "For eksempel daglig leder, rådgivende ingeniør",
"erfaring": "Utdanning, fagområder, år i faget, bygg du er stolt av",
"portrett": "Et stående bilde, gjerne tatt i dagslys. Velger du ikke noe nytt, beholder du det du har."
},
"question": "Ditt kort på forsiden",
"page_description": "Det du skriver her, står under portrettet ditt på forsiden."
},
"questions/status/ansatte/index.yaml": {
"question": "Hvem består Klingenberg Bygg av?",
"description": "Menneskene som går befaringene, skriver rapportene og står for søknadene.",
"heading": "Menneskene",
"list_description": "",
"list_title": "Menneskene",
"list_note": "",
"empty": "Snart presenterer vi oss her.",
"answer": ""
}
}
+17
View File
@@ -0,0 +1,17 @@
# One onboarding per business. `open` is the intake as submitted; the
# generator (portal-trainer generate) turns it into a draft content
# repo; the business reviews the draft and either it goes live or it
# comes back for another pass.
aggregates:
- bucket: onboardings
initial: open
states:
open: { event: intake_received }
drafted: { event: draft_generated }
revising: { event: revision_requested }
live: { event: went_live }
declined: { event: declined }
transitions:
open: [drafted, declined]
drafted: [live, revising, declined]
revising: [drafted, declined]
+41
View File
@@ -0,0 +1,41 @@
# The onboarding site is a portal site, so it is held to a needs spec
# like any other.
needs:
- id: onboard-business
who: someone who runs a business where requests, approvals and handovers get lost
wants: a working site for their own roles, without commissioning software
via: Describe your business and get a first draft
lands_in: onboardings
handled_by: owners
done_when: [live, declined]
max_steps: 1
# The intake is the interview: two to reach them, four about the work.
max_fields: 6
personas:
- id: contractor-owner
need: onboard-business
text: >
I run a building firm. Enquiries come by phone, text and email
and we lose track of who promised what. I want one place where
they land and my project managers pick them up.
- id: clinic-manager
need: onboard-business
text: >
We are a physiotherapy clinic with six therapists. Referrals,
cancellations and insurance approvals all go through one inbox
that only our receptionist understands. I'd like that sorted.
- id: sports-club
need: onboard-business
text: >
I volunteer for a youth football club. Parents sign kids up,
coaches need to approve them, and the treasurer chases fees.
Right now it's a spreadsheet and a group chat.
- id: sceptical-founder
need: onboard-business
text: >
I've been burned by agencies before. If I can explain my
workflow and see something real before paying anyone, I'm in.
@@ -0,0 +1 @@
qualifies: owners
+25
View File
@@ -0,0 +1,25 @@
name: Which businesses are waiting on us?
responsible:
name: Bendik Aagaard Lynghaug
contact: bl@uhhm.no
alternatives:
- name: Onboardings
description: >
Run `portal-trainer generate` on an open intake, push the draft,
send the link, then mark it drafted. Revisions come back here.
action: /desk
consequence: [Confirm]
features:
- name: ""
description: ""
resource:
source: { kind: kv, bucket: onboardings }
requires_group: owners
transitions:
- { to: drafted, label: Draft sent }
- { to: declined, label: Decline }
- { from: drafted, to: live, label: Went live }
- { from: drafted, to: revising, label: Revision asked }
- { from: drafted, to: declined, label: Decline }
- { from: revising, to: drafted, label: Revised draft sent }
- { from: revising, to: declined, label: Decline }
+21
View File
@@ -0,0 +1,21 @@
name: How does an answer become a finished job?
description: >
Every page asks one question. Every answer lands with the person
whose job it is, and carries its own next steps.
alternatives:
- name: A visitor answers
description: >
They pick what they came for and fill in the few fields that
person needs. They are told who reads it and when.
- name: The right role sees it
description: >
Each role has a desk listing what is theirs, with one button per
step your process allows - quoted, approved, closed.
- name: Nothing waits unseen
description: >
Every case has a state and an owner, so what is open, and with
whom, is always one page away.
- name: Describe your business and get a first draft
description: Five answers in your own words.
action: /
consequence: [Start]
+49
View File
@@ -0,0 +1,49 @@
name: What does your business keep doing by hand?
description: >
Tell us who comes to you, what you keep track of, and who handles
what. You get a site that asks each of those people the right
question and moves every answer to the person who acts on it.
responsible:
name: Bendik Aagaard Lynghaug
contact: bl@uhhm.no
alternatives:
- name: Describe your business and get a first draft
description: >
Five answers in your own words. We turn them into pages, forms
and a desk for each role, and send you a link to try it.
action: /received
consequence: [Send it]
record_as: onboardings
encouragements:
- Write it the way you would explain it to a new colleague.
features:
- name: You
requirements:
- { name: business, label: Business name }
- { name: email, label: Your email, type: email }
- name: The work
description: Plain words are best. Stages, handovers and waiting are what we listen for.
requirements:
- name: what_we_do
label: What you do
type: textarea
- name: who_comes_to_us
label: Who comes to you, and what each of them wants
type: textarea
- name: what_we_keep_track_of
label: What you keep track of, and the stages it goes through
type: textarea
- name: who_is_involved
label: Who on your side handles what
type: textarea
- name: what_slows_us_down
label: Where things get lost or wait today
type: textarea
optional: true
- name: See how a question becomes a finished job
description: >
One enquiry followed from the visitor's answer to the desk that
closes it.
action: /how
consequence: [Show me]
+15
View File
@@ -0,0 +1,15 @@
followup: true
name: What happens with what you sent?
description: >
Bendik reads every intake. Within two working days you get a link to
a working draft built from your answers.
alternatives:
- name: You try the draft as each of your roles
description: >
Click through it as a customer, then as the colleague who handles
that customer. Tell us what reads wrong and the draft comes back
revised.
- name: Back to the start
description: ""
action: /
consequence: [Back]
+2
View File
@@ -0,0 +1,2 @@
title: Portal
lang: en
+144
View File
@@ -0,0 +1,144 @@
// Pages move the way their addresses do.
//
// Deeper in the address comes in from the right and going back up
// comes in from the left: /kontor/ansatt sits to the right of /kontor.
// A page at the same depth comes from below, or from above when it
// sorts first, so the index is on top. The cards on a page leave as
// islands of their own and the next page's cards arrive one after
// another.
//
// The router swaps the page after its data has arrived, and in between
// shows nothing at all. So the click is held here, before the router
// sees it: the browser takes its picture of the page as it is, the
// click is handed on, and the transition waits until the new page has
// replaced the old one. Only transforms and opacity are animated, on
// layers the browser composites itself. Without View Transitions, or
// with reduced motion asked for, nothing here does anything and the
// router navigates as it always did.
(() => {
if (!document.startViewTransition) return;
const still = matchMedia("(prefers-reduced-motion: reduce)");
const MAX_CARDS = 8;
const WAIT_MS = 2500;
const handed = new WeakSet();
const segments = (path) => path.split("/").filter(Boolean);
// forward, back, down or up: which way the new page comes from.
function direction(from, to) {
const a = segments(from);
const b = segments(to);
if (b.length > a.length) return "forward";
if (b.length < a.length) return "back";
return to < from ? "up" : "down";
}
// Only the cards on screen become islands: each is a picture the
// browser has to take and hold, and one nobody sees costs the same.
function inView(card) {
const r = card.getBoundingClientRect();
return r.bottom > 0 && r.top < innerHeight;
}
function name(cards, prefix) {
cards.filter(inView).slice(0, MAX_CARDS).forEach((card, i) => {
card.style.viewTransitionName = `${prefix}-${i + 1}`;
});
}
function unname() {
document.querySelectorAll(".alt-card").forEach((card) => {
card.style.viewTransitionName = "";
});
}
// Resolves once the page that was showing has been replaced by the
// one at `path`, or after WAIT_MS whatever happened.
function replaced(old, path) {
return new Promise((resolve) => {
const done = () => {
observer.disconnect();
clearTimeout(timer);
resolve();
};
const check = () => {
if (location.pathname !== path) return;
if (document.querySelector("main.loading")) return;
if (old && old.isConnected) return;
if (!document.querySelector(".alternatives, main.not-found")) return;
done();
};
const observer = new MutationObserver(check);
observer.observe(document.body, { childList: true, subtree: true });
const timer = setTimeout(done, WAIT_MS);
check();
});
}
function move(from, to, handOn) {
const root = document.documentElement;
const old = document.querySelector(".alternatives");
root.dataset.motion = direction(from, to);
name([...document.querySelectorAll(".alt-card")], "pm-out");
const transition = document.startViewTransition(async () => {
unname();
handOn();
await replaced(old, to);
name([...document.querySelectorAll(".alt-card")], "pm-in");
});
transition.finished.finally(() => {
unname();
delete root.dataset.motion;
});
}
document.addEventListener(
"click",
(ev) => {
if (still.matches || handed.has(ev) || ev.defaultPrevented) return;
if (ev.button !== 0 || ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
const a = ev.target.closest && ev.target.closest("a[href]");
if (!a || a.target || a.hasAttribute("download")) return;
if ((a.getAttribute("rel") || "").split(/\s+/).includes("external")) return;
const url = new URL(a.href, location.href);
if (url.origin !== location.origin || url.pathname === location.pathname) return;
ev.preventDefault();
ev.stopImmediatePropagation();
move(location.pathname, url.pathname, () => {
const again = new MouseEvent("click", { bubbles: true, cancelable: true, composed: true, button: 0 });
handed.add(again);
a.dispatchEvent(again);
});
},
true,
);
// Back and forward: the address has already changed when this runs,
// so the router is told a moment later, inside the transition.
let shown = location.pathname;
window.addEventListener(
"popstate",
(ev) => {
const to = location.pathname;
const from = shown;
shown = to;
if (still.matches || handed.has(ev) || from === to) return;
ev.stopImmediatePropagation();
move(from, to, () => {
const again = new PopStateEvent("popstate", { state: ev.state });
handed.add(again);
window.dispatchEvent(again);
});
},
true,
);
// Keep `shown` right after the router's own pushes.
for (const method of ["pushState", "replaceState"]) {
const original = history[method].bind(history);
history[method] = (...args) => {
const result = original(...args);
shown = location.pathname;
return result;
};
}
})();
+158
View File
@@ -0,0 +1,158 @@
# A building contractor's needs, as a portal needs spec: a small to
# mid-sized firm doing surveys, design and rehabilitation, run by a few
# project managers with its own crew and a ring of subcontractors.
#
# This file is a target, not a description: there are no pages behind
# it yet, so `question_lint` fails every need. The trainer's job is to
# write the pages, aggregates.yaml and desks that turn it green, then
# word them until the personas route right.
#
# Groups (Kanidm): project_managers, hse, crew, subcontractors.
# Everyone else arrives anonymous.
#
# What the sector demands of the flows, and why the budgets are what
# they are:
# - Winning work is a pipeline, not an inbox: a lead is surveyed, then
# quoted, then won or lost. "answered" is not an outcome.
# - A subcontractor must be vetted before they set foot on site
# (company registration, trade approval, insurance, tax standing,
# site ID cards for their people). Documents go missing; the state
# machine has to say so and let them come back.
# - Deviation and near-miss reporting only works when it costs the
# reporter seconds. Three required fields, one submission, from a
# phone, and the safety officer owns closing it.
# - People move between firms constantly; onboarding a worker is the
# same shape as onboarding a subcontractor, one size smaller.
needs:
- id: win-survey-work
who: a building owner or housing board with a problem in their building
wants: someone qualified to look at it and say what it takes
lands_in: leads
handled_by: project_managers
done_when: [won, lost]
max_steps: 2
max_fields: 5
- id: win-design-work
who: an owner who knows what they want built or changed
wants: drawings, a permit application, and a price
lands_in: leads
handled_by: project_managers
done_when: [won, lost]
max_steps: 2
max_fields: 6
- id: vet-subcontractor
who: a trade firm that wants to work for us
wants: to be approved once, and then be asked
lands_in: subcontractors
handled_by: project_managers
done_when: [approved, rejected]
max_steps: 2
max_fields: 7
- id: request-bids
who: a project manager with a job to staff
wants: approved subcontractors to see it and answer
enters: /jobs/post
enters_as: project_managers
lands_in: job_requests
handled_by: project_managers
done_when: [awarded, withdrawn]
max_steps: 1
max_fields: 5
- id: answer-bid
who: an approved subcontractor
wants: to say yes to a job, with a price and a start date
enters: /jobs
enters_as: subcontractors
lands_in: bids
handled_by: project_managers
done_when: [accepted, declined]
max_steps: 2
max_fields: 3
- id: hire-crew
who: a tradesperson looking for work
wants: to be considered, without writing a letter
lands_in: applicants
handled_by: project_managers
done_when: [hired, declined]
max_steps: 2
max_fields: 4
- id: report-deviation
who: anyone on site - crew or a subcontractor's people
wants: to report a hazard, a near miss or a defect before they forget
enters: /site
enters_as: crew
lands_in: deviations
handled_by: hse
done_when: [closed]
max_steps: 1
max_fields: 3
personas:
- id: housing-board-damp
need: win-survey-work
text: >
I chair the board of a housing cooperative from the seventies.
Two ground-floor flats have damp in the walls and we don't know
if it's drainage or the facade. We need someone to tell us.
- id: buyer-before-purchase
need: win-survey-work
text: >
We are about to buy an old timber house. Before we sign we want
a professional to go through it and tell us what is wrong with it.
- id: attic-conversion
need: win-design-work
text: >
We want to turn our attic into two bedrooms and a bathroom. We
need drawings and someone who handles the application to the
municipality.
- id: shop-to-flat
need: win-design-work
text: >
I own a former shop on the ground floor and want to make it a
flat. I have no idea what is allowed. Can you sort that out and
give me a price?
- id: electrician-firm
need: vet-subcontractor
text: >
We are a four-person electrical firm, fully certified. We would
like to get on your list so you call us when you need
electricians.
- id: scaffolder
need: vet-subcontractor
text: >
I run a scaffolding company. How do I get to do jobs for you?
- id: carpenter-jobseeker
need: hire-crew
text: >
I'm a certified carpenter with eight years on rehabilitation
jobs. Are you hiring?
- id: apprentice
need: hire-crew
text: >
I finish vocational school this spring and need an
apprenticeship as a bricklayer.
- id: loose-railing
need: report-deviation
text: >
The railing on the third level of the scaffold on the north
side is loose. Nobody got hurt but someone will.
- id: wrong-membrane
need: report-deviation
text: >
The bathroom membrane delivered today is not the one in the
specification. We stopped work on it.
+127
View File
@@ -0,0 +1,127 @@
# What UHHM, as a business, needs this site to do - stated apart from
# how the pages word it. `question_lint` checks every need against the
# pages and aggregates.yaml (portal `src/needs.rs`): a path of
# submissions gets the visitor's answer into `lands_in` within the
# effort budget, `handled_by` has a desk over that bucket, and every
# `done_when` state is reachable through the moves the desk offers.
#
# The personas are visitors in their own words - never the site's.
# `question_lint --needs-tasks` turns each page on their path into a
# typed choice for an answering engine; `--needs-score` grades its
# picks. A misroute means the page said one thing and they heard
# another. The runtime never reads this file.
needs:
- id: commission
who: someone with a problem software could solve, and a budget
wants: UHHM to take the work on
via: Good software begins with a clear argument
lands_in: projects
handled_by: owners
done_when: [accepted, declined]
max_steps: 1
# name, email, the build, the organization - the page argues for
# each of the four; a fifth would need the same argument.
max_fields: 4
- id: follow
who: someone curious who isn't ready to get involved
wants: to hear when something ships
via: Attention is earned
lands_in: subscribers
handled_by: owners
# Being on the list is the finished state; leaving is theirs to do.
done_when: [open, unsubscribed]
max_steps: 1
max_fields: 2
- id: collaborate
who: a developer, designer or researcher
wants: to work with UHHM
via: Work happens through dialogue, not tickets
lands_in: applicants
handled_by: owners
done_when: [active, declined]
max_steps: 1
max_fields: 3
- id: improve-site
who: anyone using this site
wants: the site itself to change
enters: /develop/proposal
# Announced, not open: the automation that turns a proposal into a
# pull request is still being built, so the alternative is disabled.
planned: true
lands_in: development_proposals
handled_by: owners
done_when: [approved, rejected]
max_steps: 1
max_fields: 3
- id: track-prospect
who: an owner who met an organization worth following up
wants: the relationship written down and walked to an outcome
enters: /review
enters_as: owners
via: Record a prospect
lands_in: organizations
handled_by: owners
done_when: [client, past_client]
max_steps: 1
max_fields: 2
personas:
- id: architecture-firm
need: commission
text: >
We run a small architecture firm and our project files are
scattered across three cloud drives. We want to pay someone to
set up proper storage and backups we control ourselves.
- id: climbing-gym-founder
need: commission
text: >
I have an idea for a booking app for climbing gyms and I'm
looking for a team that can build the first version with me.
- id: municipality-buyer
need: commission
text: >
Our municipality needs an internal tool for tracking building
permits. We are looking for a vendor who can scope it and
deliver it.
- id: exhibition-visitor
need: follow
text: >
I saw your drawing network at an exhibition and liked it. I don't
want to get involved, I'd just like to know when there is news.
- id: tech-journalist
need: follow
text: >
I write about Nordic technology. Keep me posted on what you
release so I can cover it.
- id: rust-developer
need: collaborate
text: >
I'm a Rust developer between jobs and I like that you build in
the open. I would love to contribute, and maybe join you.
- id: interaction-designer
need: collaborate
text: >
I'm an interaction designer. I want to work with you on the
drawing interface.
- id: student-intern
need: collaborate
text: >
I'm a computer science student looking for a summer internship
doing infrastructure work.
- id: site-critic
need: improve-site
text: >
Your contact form never says how long a reply takes. You should
add that.
+151
View File
@@ -0,0 +1,151 @@
---
name: portal-trainer
description: Onboard a business onto portal - interview them, write a plan, build the content repo (pages, aggregates.yaml, desks, mails) with the words written by a model, and score it until iris proves every need is met and a blind visitor routes the personas right. Use when someone wants a new portal site, a new flow on an existing one, a rebuild of a live one, or asks why visitors pick the wrong alternative.
---
# Portal trainer
You are onboarding a business onto [portal](https://project.uhhm.no/uhhm/portal):
a site that is one question per page, a few alternatives per question,
each alternative optionally a form whose answer is recorded into a
bucket with a state machine, worked from a group-gated desk, with a
mail to the person when their case moves.
You have a verifier. Use it instead of your judgment wherever it can
speak: `iris check --path <repo>/questions` (uhhm/iris, the release
matching the portal the site runs) exits non-zero until the structure
meets every need in `<repo>/needs.yaml`.
## The order of work
1. **Interview, then write the plan.** Never pages first. `plan`
reads a filled-in intake into `plan.yaml` (a model decides needs,
stages, forms and budgets; a person reads the result before
anything is built). By hand, the same questions: who comes to the
business and what each of them wants, who inside handles it, what
"handled" means (the states a case ends in), what it costs the
visitor to ask (`max_fields`, from the person, never from counting
the form you would like). Start from a `sectors/` file when there
is one.
2. **Say what the plan can say.** `does:` (one or two features, one
role each, the front door's opener that asks for nothing);
`shows:` (things to look at before asking); `doors:` only when the
offers are more than a page holds - measure it, a flat page with
ten offers scored worse than four doors; `mails:` per need (who
hears when a case enters a stage) with `mail: { from }` on the
plan; `moves_by: submitter` so the person has something to play
after sending; `invites_by` for onboarding; `events:` when
rebuilding a live site, so its records keep replaying.
3. **Write personas in the visitor's words, not the business's.** Two
or three per need, one who would not use the trade's vocabulary.
Never reuse a phrase you intend to put on a page. They are held
out from every model that writes words.
4. **Build.** `build --plan ... --lint iris` derives every file with
no model deciding structure; `--llm` lets a model write the words,
`--llm-for <path prefix>` only some of them (the mails alone);
`--words-from <live repo>` keeps a live site's hand-edited words
through a rebuild, following each card across pages; `--words
<json>` overrides slots. The builder refuses a reply in the wrong
language and puts back a submitter's link a model dropped.
5. **Score.** `iris check --needs-tasks` then `answer`, then
`--needs-score`, with and without descriptions; `rate --repo` for
readability and the four understanding questions, mails included.
A card with no button is context, never a choice. Trust the
descriptions score; the headings-only score swings by a third
between seeds. Before believing a change, `runs/spread.sh` it over
three seeds and require it to beat the spread. A change that does
not is rejected and kept as a run.
- A **misroute** is a wording defect until the same one survives
every rewording; then it is a seam in the plan.
- Change the page or the plan, never the persona.
6. **Keep the run.** `runs/<business>-<date>/` with the words as used
(`words.json`), tasks, answers, scores per seed, and a README with
what moved and why. Runs are the record of what worked.
## What a page is
Full reference: portal's `README.md`; a live example is
`uhhm/questions`. The tree under `questions/` is the router
(`index.yaml` is `/`, `_section.yaml` applies `qualifies` to a
directory, nested non-index files are followups).
```yaml
# questions/index.yaml
name: What brings you here? # the question - always a question
responsible: { name: ..., contact: ... }
alternatives:
- name: What we do # the opener: features, no button
features:
- { name: <a role's win>, description: <what we do for them> }
- name: <heading the visitor picks> # graded alone under --skim
description: <one or two sentences>
action: /received # where the submission lands them
consequence: [Send] # the button
record_as: leads # bucket - must exist in aggregates.yaml
features:
- name: <form section>
requirements:
- { name: email, label: Email, type: email }
- { name: problem, label: What's wrong, type: textarea }
```
```yaml
# aggregates.yaml
aggregates:
- bucket: leads
initial: open
states:
open: { event: received, mail: { to: submitter, subject: "We have it", body: "..." } }
quoted: { event: quoted }
won: { event: won, mail: { to: submitter, subject: "...", body: "..." } }
lost: { event: lost }
transitions:
open: [quoted, lost]
quoted: [won, lost]
```
```yaml
# site.yaml
mail: { from: "Nordvik <post@nordvik.example>", reply_to: ola@nordvik.example }
```
```yaml
# questions/desk/_section.yaml
qualifies: project_managers
# questions/desk/index.yaml
name: What came in?
alternatives:
- name: Leads
action: /desk
consequence: [Confirm]
features:
- name: ""
resource:
source: { kind: kv, bucket: leads }
requires_group: project_managers
transitions:
- { to: quoted, label: Quote sent } # from defaults to open
- { from: quoted, to: won, label: Won }
```
## House rules for the copy
- The page name is a question the visitor could ask themselves.
- The front door opens modestly: what the business does for one or
two roles, then what there is to look at, then the offers. No
second tier.
- Headings say what the visitor gets, in the visitor's words. Lead
with what a thing enables; never define it by what it isn't.
- Every required field must be one the business will use to answer.
- A followup page says who reads it, when they answer, and what the
visitor can do meanwhile. A mail says what happened and, where the
person has a move, the link to make it.
- Code in English; the site in the business's language.
## Engines
Any engine that reads a task's `state` (`body` is the persona,
`page` what the page says before its options) and `questions` and
returns `{"id","choice","confidence"}` per line works. The visitor
and the writer must be different models. See the repo README for what
has been measured about each, and for the noise floor.
+39
View File
@@ -51,6 +51,35 @@ pub struct AggregateSchema {
/// no answer in six weeks has to go on without one, and nothing in
/// a building is going to press that button.
pub after_for_state: HashMap<String, AfterSpec>,
/// How long a record stays in the list once it has entered a
/// state, when that is not for ever: a card taken off the front
/// page leaves the desk's list a little later, instead of standing
/// there greyed out. The event log keeps it.
pub leaves_for_state: HashMap<String, LeavesSpec>,
}
/// `leaves_after: { minutes: 10 }` on a state: how long a record that
/// has entered it stays in its bucket's list. Days, hours and minutes
/// add up; the sweep that takes it out runs every minute.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LeavesSpec {
#[serde(default, skip_serializing_if = "is_zero")]
pub days: u32,
#[serde(default, skip_serializing_if = "is_zero")]
pub hours: u32,
#[serde(default, skip_serializing_if = "is_zero")]
pub minutes: u32,
}
fn is_zero(n: &u32) -> bool {
*n == 0
}
impl LeavesSpec {
pub fn millis(&self) -> i64 {
((i64::from(self.days) * 24 + i64::from(self.hours)) * 60 + i64::from(self.minutes)) * 60 * 1000
}
}
/// A mail to send when a record enters a state. `to` is `submitter`
@@ -125,6 +154,8 @@ struct RawState {
grants: Option<String>,
#[serde(default)]
after: Option<AfterSpec>,
#[serde(default)]
leaves_after: Option<LeavesSpec>,
}
#[derive(Debug, serde::Deserialize)]
@@ -197,7 +228,14 @@ pub fn parse_aggregates_yaml(raw: &str) -> anyhow::Result<HashMap<String, Aggreg
let mut mail_for_state = HashMap::new();
let mut grants_for_state = HashMap::new();
let mut after_for_state = HashMap::new();
let mut leaves_for_state = HashMap::new();
for (state, raw_state) in raw_schema.states {
if let Some(leaves) = raw_state.leaves_after {
if leaves.millis() == 0 {
anyhow::bail!("aggregates.yaml: bucket {bucket:?}: state {state:?}: leaves_after needs some days, hours or minutes");
}
leaves_for_state.insert(state.clone(), leaves);
}
if let Some(group) = raw_state.grants {
if group.trim().is_empty() {
anyhow::bail!("aggregates.yaml: bucket {bucket:?}: state {state:?}: grants needs a group");
@@ -245,6 +283,7 @@ pub fn parse_aggregates_yaml(raw: &str) -> anyhow::Result<HashMap<String, Aggreg
mail_for_state,
grants_for_state,
after_for_state,
leaves_for_state,
},
);
}
+2
View File
@@ -84,6 +84,7 @@ pub async fn sweep(state: &AppState) -> anyhow::Result<()> {
EVENT_ALTERNATIVE,
&responses,
now_ms,
0,
)
.await?;
tracing::info!(question = %q.id, "event record created");
@@ -137,6 +138,7 @@ pub async fn sweep(state: &AppState) -> anyhow::Result<()> {
alternative: SUMMARY_DUE_LABEL.to_string(),
responses: payload,
timestamp_ms: now_ms,
storyline: 0,
},
)
.await?;
+81 -2
View File
@@ -24,6 +24,10 @@ pub struct Answer {
pub responses: serde_json::Value,
pub state: String,
pub submitted_ms: i64,
/// The storyline the record was sent from, so the mail it gets
/// tells the same one (see `content/variants.rs`).
#[serde(default)]
pub storyline: u32,
#[serde(default)]
pub decided_ms: Option<i64>,
#[serde(default)]
@@ -64,6 +68,7 @@ pub async fn store_answer(
alternative: &str,
responses: &serde_json::Value,
submitted_ms: i64,
storyline: u32,
) -> anyhow::Result<()> {
let store = match js.get_key_value(bucket).await {
Ok(store) => store,
@@ -89,6 +94,7 @@ pub async fn store_answer(
responses: responses.clone(),
state: initial_state,
submitted_ms,
storyline,
decided_ms: None,
notes: Vec::new(),
decided_by: None,
@@ -108,6 +114,73 @@ pub async fn store_answer(
Ok(())
}
/// Whose a record is, on an alternative that keeps one per person
/// (`one_per_person`): the signed-in person's username, written by the
/// server into the record's fields, never taken from the form.
pub const OWNER_FIELD: &str = "by";
/// Every record in `bucket` that belongs to `username`, newest first.
#[cfg(feature = "ssr")]
pub async fn own_records(js: &async_nats::jetstream::Context, bucket: &str, username: &str) -> Vec<Answer> {
use futures::TryStreamExt;
let Ok(store) = js.get_key_value(bucket).await else { return Vec::new() };
let keys: Vec<String> = match store.keys().await {
Ok(keys) => keys.try_collect().await.unwrap_or_default(),
Err(_) => return Vec::new(),
};
let mut own = Vec::new();
for key in keys {
let Ok(Some(bytes)) = store.get(&key).await else { continue };
let Ok(answer) = serde_json::from_slice::<Answer>(&bytes) else { continue };
if answer.responses.get(OWNER_FIELD).and_then(|v| v.as_str()) == Some(username) {
own.push(answer);
}
}
own.sort_by(|a, b| (b.submitted_ms, &b.id).cmp(&(a.submitted_ms, &a.id)));
own
}
/// A person keeps one card: of their records still in the bucket's
/// first state, only the newest stays in the list, and the rest leave
/// it (the event log keeps them). Run after every store, so two sends
/// racing each other - a double click - both settle on the same one.
#[cfg(feature = "ssr")]
pub async fn keep_newest_own(js: &async_nats::jetstream::Context, bucket: &str, initial: &str, username: &str) {
let own = own_records(js, bucket, username).await;
let Ok(store) = js.get_key_value(bucket).await else { return };
for older in own.iter().filter(|a| a.state == initial).skip(1) {
if let Err(e) = store.delete(&older.id).await {
tracing::error!(bucket, id = %older.id, error = %e, "could not retire an older own record");
}
}
}
/// Fills the form of every `one_per_person` alternative with what the
/// signed-in person's own newest record says, so sending it again is
/// editing their card. A file field shows the file already there, at
/// the address a list would open it from, and may be left empty to
/// keep it.
#[cfg(feature = "ssr")]
pub async fn fill_own(js: &async_nats::jetstream::Context, question: &mut crate::content::Question, user: Option<&crate::auth::User>) {
let Some(user) = user else { return };
for alt in &mut question.alternatives {
let (true, Some(bucket)) = (alt.one_per_person, alt.record_as.clone()) else { continue };
let Some(mine) = own_records(js, &bucket, &user.username).await.into_iter().next() else { continue };
for req in alt.features.iter_mut().flat_map(|f| f.requirements.iter_mut()) {
if req.kind == "hidden" {
continue;
}
let Some(value) = mine.responses.get(&req.name).and_then(|v| v.as_str()).filter(|v| !v.trim().is_empty()) else { continue };
if req.kind == "file" {
req.value = Some(format!("/attachment/{bucket}/{}/{}", mine.id, req.name));
req.optional = true;
} else {
req.value = Some(value.to_string());
}
}
}
}
/// One selected row's pending transition. `feature_name` is per-item
/// so a batch can span more than one resource feature on the same
/// alternative.
@@ -132,9 +205,11 @@ pub async fn transition_answers(
use crate::server::AppState;
let state = expect_context::<AppState>();
let storyline = crate::server::storyline::current().await;
let alt = state
.questions
.load()
.at(storyline)
.get(&question_id)
.and_then(|q| q.alternatives.iter().find(|a| a.name == alternative).cloned())
.ok_or_else(|| ServerFnError::new("unknown question or alternative"))?;
@@ -289,7 +364,7 @@ async fn apply_transition(
.put(&item.item_id, data.into())
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
crate::mail::on_state(state, bucket, &item.item_id, &item.to, &answer.responses).await;
crate::mail::on_state(state, bucket, &item.item_id, &item.to, &answer.responses, answer.storyline).await;
crate::people::on_state(state, bucket, &item.item_id, &item.to, &answer.responses).await;
// An expired invite sent again: the move back is the asking.
if bucket == crate::people::INVITES_BUCKET && item.to == OPEN_STATE {
@@ -307,6 +382,7 @@ async fn apply_transition(
alternative: transition.label,
responses: decision_payload_for_event,
timestamp_ms: decided_ms,
storyline: answer.storyline,
};
emit_answer_submitted(&state.nats, &event)
.await
@@ -417,7 +493,7 @@ pub async fn self_transition_answer(
.put(&item_id, data.into())
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
crate::mail::on_state(&state, &self_transition.bucket, &item_id, &self_transition.to, &answer.responses).await;
crate::mail::on_state(&state, &self_transition.bucket, &item_id, &self_transition.to, &answer.responses, answer.storyline).await;
crate::people::on_state(&state, &self_transition.bucket, &item_id, &self_transition.to, &answer.responses).await;
let parent_hashes = vec![item_id.clone()];
@@ -429,6 +505,7 @@ pub async fn self_transition_answer(
alternative: self_transition.label,
responses: decision_payload_for_event,
timestamp_ms: decided_ms,
storyline: answer.storyline,
};
emit_answer_submitted(&state.nats, &event)
.await
@@ -456,6 +533,7 @@ mod tests {
responses: serde_json::json!({"name": "Ada"}),
state: OPEN_STATE.to_string(),
submitted_ms: 1_700_000_000_000,
storyline: 0,
decided_ms: None,
decided_by: None,
notes: Vec::new(),
@@ -467,6 +545,7 @@ mod tests {
responses: serde_json::json!({"name": "Grace"}),
state: "invited".to_string(),
submitted_ms: 1_700_000_001_000,
storyline: 0,
decided_ms: Some(1_700_000_002_000),
decided_by: Some("bl".to_string()),
notes: Vec::new(),
+364 -15
View File
@@ -57,6 +57,8 @@ pub fn shell(options: LeptosOptions) -> impl IntoView {
// Server-side, so it can read hash.txt and link the
// content-hashed stylesheet (hash-files = true).
<HashedStylesheet id="leptos" options=options.clone()/>
// Before the router, so it sees a link's click first.
<script src="/page-motion.js" defer=true></script>
<AutoReload options=options.clone()/>
<HydrationScripts options/>
<MetaTags/>
@@ -369,7 +371,7 @@ fn QuestionView(
// Swiper Element only registers its custom elements when its
// (vendored, ~180KB) script runs - loaded once per page, and only
// on pages where some alternative actually declares a deck.
let needs_swiper = question.alternatives.iter().any(|a| a.images.len() > 1);
let needs_swiper = question.slideshow.is_some() || question.alternatives.iter().any(|a| a.images.len() > 1);
// MapLibre is vendored and large, so it loads only where a field
// actually asks for a place, and only where this instance can
// serve tiles at all.
@@ -396,6 +398,8 @@ fn QuestionView(
landing=question_id == "/"
site=site.clone()
current_id=question_id.clone()
user=user.clone()
slideshow=question.slideshow.clone()
/>
// A page that is about somewhere says where, under the
// question: a still from this origin, and the place in words
@@ -841,7 +845,15 @@ mod gesture {
}
#[component]
fn Hero(title: String, description: String, landing: bool, site: SiteConfig, current_id: String) -> impl IntoView {
fn Hero(
title: String,
description: String,
landing: bool,
site: SiteConfig,
current_id: String,
#[prop(optional_no_strip)] user: Option<User>,
#[prop(optional_no_strip)] slideshow: Option<crate::content::Slideshow>,
) -> impl IntoView {
// Only the landing page gets a piece - it's the one page a hero is
// actually "the" hero for; every other page gets the plain header.
// WHAT the piece is belongs to the content repo: site.yaml's
@@ -940,9 +952,37 @@ fn Hero(title: String, description: String, landing: bool, site: SiteConfig, cur
)
});
// Who is here, and the way in or out, at the top of every page of
// a site that has sign-in at all.
let session = site.sign_in.then(|| {
let redirect = current_id.clone();
match user {
Some(user) => view! {
<nav class="session">
<span class="session-name">{user.display_name}</span>
<a href="/auth/logout" rel="external">{move || t(&lang().get(), "sign_out")}</a>
</nav>
}
.into_any(),
None => view! {
<nav class="session">
<a href=format!("/auth/login?redirect={redirect}") rel="external">{move || t(&lang().get(), "sign_in")}</a>
</nav>
}
.into_any(),
}
});
let has_slides = slideshow.is_some();
let mark = move || view! {
<a class="wordmark" class:wordmark-house=house_wordmark href="/">
<img src=wordmark.clone() alt=site_title.clone() style=wordmark_style.clone()/>
</a>
};
view! {
<header class="hero" class:hero-module=has_module>
<header class="hero" class:hero-module=has_module class:hero-slides=has_slides>
<Announcements current_id=current_id/>
{session}
{has_module
.then(|| {
view! {
@@ -950,10 +990,13 @@ fn Hero(title: String, description: String, landing: bool, site: SiteConfig, cur
<script type="module" inner_html=early_script.unwrap_or_default()></script>
}
})}
// With pictures, the wordmark is a bar of its own above
// them and the question comes under; without, the wordmark
// heads the copy as it always has.
{has_slides.then(|| view! { <div class="hero-bar">{mark()}</div> })}
{slideshow.map(|show| view! { <SlideStrip show=show/> })}
<div class="hero-copy">
<a class="wordmark" class:wordmark-house=house_wordmark href="/">
<img src=wordmark alt=site_title style=wordmark_style/>
</a>
{(!has_slides).then(|| mark())}
<h1>{title}</h1>
<p inner_html=render_inline_markdown(&description)></p>
</div>
@@ -961,6 +1004,59 @@ fn Hero(title: String, description: String, landing: bool, site: SiteConfig, cur
}
}
/// Pictures across the page (`slideshow`): the full width of the
/// screen, each picture as wide as its own shape at the strip's height,
/// the caption laid over its foot. Inert until the Swiper bundle
/// upgrades the elements; without it, a row that scrolls sideways.
#[component]
fn SlideStrip(show: crate::content::Slideshow) -> impl IntoView {
let height = format!("--slideshow-height: {}svh", show.max_height);
view! {
// In the page itself, so the strip works from the
// server's HTML alone; the head's copy above covers
// arriving here by a link within the site.
<script src="/swiper-element-bundle.min.js" defer=true></script>
<swiper-container
class="slideshow"
style=height
slides-per-view="auto"
space-between="6"
grab-cursor="true"
free-mode="true"
mousewheel-force-to-axis="true"
keyboard="true"
navigation="true"
>
<For
each={move || show.slides.clone().into_iter().enumerate().collect::<Vec<_>>()}
key=|(_, slide)| slide.image.clone()
children=|(n, slide): (usize, crate::content::Slide)| {
let caption = slide.caption.clone();
// The first screenful loads with the
// page; the rest when swiped to.
let loading = if n < 4 { "eager" } else { "lazy" };
view! {
<swiper-slide>
<figure class="slide">
<img
src=slide.src()
alt=slide.caption.clone()
width=slide.width.map(|w| w.to_string())
height=slide.height.map(|h| h.to_string())
loading=loading
decoding="async"
/>
{(!caption.trim().is_empty()).then(|| view! { <figcaption>{caption}</figcaption> })}
</figure>
</swiper-slide>
}
.into_any()
}
/>
</swiper-container>
}
}
/// An alternative's banner imagery: nothing, a plain image, or - for
/// several urls - a Swiper Element card deck. The `swiper-container`/
/// `swiper-slide` custom elements render inert server-side and upgrade
@@ -1102,9 +1198,11 @@ fn AlternativeCard(
if req.kind == "file" {
file_refs.entry(req.name.clone()).or_default();
} else if req.kind == "select" {
// Preset by a card of one's own (`answers::fill_own`).
let preset: Vec<String> = req.value.clone().filter(|v| !v.is_empty()).into_iter().collect();
select_field_map
.entry(req.name.clone())
.or_insert_with(|| RwSignal::new(Vec::new()));
.or_insert_with(|| RwSignal::new(preset));
select_multi.insert(req.name.clone(), req.multiple);
} else {
// Widget-owned fields hold JSON objects, not strings.
@@ -1142,6 +1240,11 @@ fn AlternativeCard(
let gesture_fields_for_submit = gesture_fields.clone();
let question_id_for_transition = question_id.clone();
let alt_name_for_transition = alternative.name.clone();
// From the moment Send is pressed until the server has answered:
// files upload first, and a second press in that time used to send
// the form twice.
let sending = RwSignal::new(false);
let send_error: RwSignal<Option<String>> = RwSignal::new(None);
let on_submit = move |ev: leptos::ev::SubmitEvent| {
ev.prevent_default();
@@ -1170,6 +1273,8 @@ fn AlternativeCard(
let question_id_for_submit = question_id_for_submit.clone();
let alt_name_for_submit = alt_name_for_submit.clone();
let parent_hash_for_submit = parent_hash_for_submit.clone();
sending.set(true);
send_error.set(None);
leptos::task::spawn_local(async move {
let mut map = serde_json::Map::new();
for (name, sig) in field_map_for_submit.iter() {
@@ -1205,12 +1310,25 @@ fn AlternativeCard(
};
let Some(files) = input.files() else { continue };
let Some(file) = files.get(0) else { continue };
// Too big is known before a byte is sent.
if file.size() > MAX_UPLOAD_BYTES as f64 {
send_error.set(Some(t(&lang().get_untracked(), "upload_too_large").to_string()));
sending.set(false);
return;
}
match upload_file(&file, &question_id_for_submit, &alt_name_for_submit).await {
Ok(key) => {
map.insert(name.clone(), serde_json::Value::String(key));
}
// A form sent without the file it asked for is a
// record that looks complete and is not: stop, and
// say so.
Err(e) => {
leptos::logging::error!("upload of {name} failed: {e:?}");
let status = e.as_string().and_then(|m| m.rsplit(' ').next().and_then(|n| n.parse().ok()));
send_error.set(Some(t(&lang().get_untracked(), upload_refusal(status)).to_string()));
sending.set(false);
return;
}
}
}
@@ -1223,6 +1341,7 @@ fn AlternativeCard(
parent_hash: parent_hash_for_submit,
responses_json,
});
sending.set(false);
});
};
@@ -1306,6 +1425,7 @@ fn AlternativeCard(
feature_name=feature_name.clone()
transitions=spec.transitions.clone()
link=spec.link.clone()
bucket=spec.bucket().map(str::to_string)
empty=spec.empty.clone()
pending_transitions=pending_transitions
transition_batch=transition_batch
@@ -1415,9 +1535,26 @@ fn AlternativeCard(
if req.kind == "file" {
let file_ref = file_refs.get(&req.name).copied().unwrap_or_else(NodeRef::new);
// On a card of one's own, the file already
// there (see `answers::fill_own`).
let current = req.value.clone().filter(|v| v.starts_with("/attachment/")).map(|href| {
let picture = req.accept.as_deref().is_some_and(|a| a.contains("image/"));
view! {
<span class="field-current">
<span>{move || t(&lang().get(), "current_file")}</span>
{if picture {
view! { <img class="answer-thumb" src=href.clone() alt="" /> }.into_any()
} else {
view! { <a href=href.clone() rel="external">{href.rsplit('/').next().unwrap_or_default().to_string()}</a> }.into_any()
}}
<span class="field-hint">{move || t(&lang().get(), "keep_file")}</span>
</span>
}
});
return view! {
<label class="field" for=label_for>
{label_text}
{current}
<input
id=field_id
type="file"
@@ -1729,12 +1866,24 @@ fn AlternativeCard(
class="alt-submit"
disabled=move || {
(!has_requirements && pending_transitions.get().is_empty())
|| sending.get()
|| submit.pending().get()
|| transition_batch.pending().get()
}
>
{button_label.clone()}
</button>
// Why nothing happened, when something
// was refused: it used to say nothing.
{move || {
send_error
.get()
.or_else(|| match submit.value().get() {
Some(Err(e)) => Some(server_message(&e)),
_ => None,
})
.map(|m| view! { <p class="alt-error" role="alert">{m}</p> })
}}
</form>
}
.into_any()
@@ -1759,6 +1908,7 @@ fn ResourceFeature(
feature_name: String,
transitions: Vec<Transition>,
link: Option<RowLink>,
bucket: Option<String>,
empty: Option<String>,
pending_transitions: RwSignal<std::collections::HashMap<(String, String), String>>,
transition_batch: ServerAction<TransitionAnswers>,
@@ -1794,6 +1944,7 @@ fn ResourceFeature(
let feature_name = feature_name.clone();
let transitions = transitions.clone();
let link = link.clone();
let bucket = bucket.clone();
let empty = empty.clone().unwrap_or_else(|| t(&lang().get(), "nothing_here_yet").to_string());
data.get()
.map(|res| match res {
@@ -1803,6 +1954,7 @@ fn ResourceFeature(
feature_name=feature_name
transitions=transitions
link=link
bucket=bucket
empty=empty
value=value
pending_transitions=pending_transitions
@@ -1831,6 +1983,7 @@ fn ResourceValue(
feature_name: String,
transitions: Vec<Transition>,
link: Option<RowLink>,
bucket: Option<String>,
empty: String,
value: serde_json::Value,
pending_transitions: RwSignal<std::collections::HashMap<(String, String), String>>,
@@ -1850,12 +2003,16 @@ fn ResourceValue(
}
if let Ok(answers) = serde_json::from_value::<Vec<Answer>>(value.clone()) {
let mut answers = answers;
// Cards are shown in the order they were put up, the way a
// team or a gallery is read; a list of cases, newest first.
let cards = transitions.is_empty() && answers.iter().all(|a| picture_of(a, bucket.as_deref()).is_some());
answers.sort_by(|a, b| {
let open = |s: &str| s != crate::answers::OPEN_STATE;
open(&a.state).cmp(&open(&b.state)).then(b.submitted_ms.cmp(&a.submitted_ms))
let when = if cards { a.submitted_ms.cmp(&b.submitted_ms) } else { b.submitted_ms.cmp(&a.submitted_ms) };
open(&a.state).cmp(&open(&b.state)).then(when)
});
return view! {
<div class="answer-list">
<div class="answer-list" class:answer-cards=cards>
<For
each=move || answers.clone()
key=|a| a.id.clone()
@@ -1863,12 +2020,14 @@ fn ResourceValue(
let feature_name = feature_name.clone();
let transitions = transitions.clone();
let link = link.clone();
let bucket = bucket.clone();
move |answer: Answer| {
view! {
<AnswerRow
feature_name=feature_name.clone()
transitions=transitions.clone()
link=link.clone()
bucket=bucket.clone()
answer=answer
pending_transitions=pending_transitions
transition_batch=transition_batch
@@ -2123,11 +2282,62 @@ fn SelectField(
}
}
/// The file's own name, if a field's value is an upload's key: a
/// uuid, a dash, and the name it was sent with (`upload.rs`).
pub fn uploaded_filename(value: &str) -> Option<&str> {
let (id, rest) = value.split_at_checked(36)?;
let shaped = id.char_indices().all(|(i, c)| if matches!(i, 8 | 13 | 18 | 23) { c == '-' } else { c.is_ascii_hexdigit() });
rest.strip_prefix('-').filter(|name| shaped && !name.is_empty())
}
/// The largest file one upload may carry. Here, not in `upload.rs`,
/// so the browser checks the same number before it sends anything.
pub const MAX_UPLOAD_BYTES: usize = 20 * 1024 * 1024;
/// Why an upload did not arrive, in words a person can act on, from
/// the status `POST /upload` answered with (see `upload.rs`): too big,
/// a site that takes no files, a page they may not send from, or
/// anything else.
#[cfg_attr(not(feature = "hydrate"), allow(dead_code))]
fn upload_refusal(status: Option<u16>) -> &'static str {
match status {
Some(413) => "upload_too_large",
Some(503) => "upload_unavailable",
Some(403) => "upload_forbidden",
_ => "upload_failed",
}
}
/// What a refused server call says, without the wrapping a person
/// has no use for.
fn server_message(e: &ServerFnError) -> String {
let text = e.to_string();
text.rsplit_once(": ").map(|(_, m)| m.to_string()).filter(|m| !m.is_empty()).unwrap_or(text)
}
/// Whether an uploaded file is a picture a browser shows as it is.
pub fn is_picture(filename: &str) -> bool {
let lower = filename.to_ascii_lowercase();
[".jpg", ".jpeg", ".png", ".webp", ".avif", ".gif"].iter().any(|ext| lower.ends_with(ext))
}
/// A record that carries a picture, in a list nobody works from, is
/// shown rather than read: the picture, then what it says, first field
/// as its heading. A team, a gallery of what has been built.
fn picture_of(answer: &Answer, bucket: Option<&str>) -> Option<String> {
let bucket = bucket?;
answer.responses.as_object()?.iter().find_map(|(key, value)| {
let name = uploaded_filename(value.as_str()?)?;
is_picture(name).then(|| format!("/attachment/{bucket}/{}/{key}", answer.id))
})
}
#[component]
fn AnswerRow(
feature_name: String,
transitions: Vec<Transition>,
link: Option<RowLink>,
bucket: Option<String>,
answer: Answer,
pending_transitions: RwSignal<std::collections::HashMap<(String, String), String>>,
transition_batch: ServerAction<TransitionAnswers>,
@@ -2150,6 +2360,11 @@ fn AnswerRow(
} else {
available.is_empty()
};
if transitions.is_empty() {
if let Some(picture) = picture_of(&answer, bucket.as_deref()) {
return AnswerCard(answer, picture, link).into_any();
}
}
let responses = answer
.responses
.as_object()
@@ -2161,6 +2376,9 @@ fn AnswerRow(
let item_id = answer.id.clone();
let key = (feature_name.clone(), item_id.clone());
let link = link.map(|l| (l.href(&answer.id, &answer.responses), l.label));
// Where a stored file on this record is fetched from: the record
// names it, never the key (see `upload::attachment`).
let attachment_base = bucket.map(|b| format!("/attachment/{b}/{}", answer.id));
view! {
<article class="answer-row" class:decided=move || decided>
@@ -2194,6 +2412,28 @@ fn AnswerRow(
.into_any();
}
let text = value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string());
// A stored file shows as its name, and opens.
if let (Some(base), Some(filename)) = (attachment_base.clone(), uploaded_filename(&text)) {
let href = format!("{base}/{key}");
if is_picture(filename) {
return view! {
<div class="answer-field">
<span class="answer-field-key">{key}</span>
<a class="answer-field-value" href=href.clone() rel="external">
<img class="answer-thumb" src=href.clone() alt=filename.to_string() loading="lazy" />
</a>
</div>
}
.into_any();
}
return view! {
<div class="answer-field">
<span class="answer-field-key">{key}</span>
<a class="answer-field-value answer-file" href=href rel="external">{filename.to_string()}</a>
</div>
}
.into_any();
}
view! {
<div class="answer-field">
<span class="answer-field-key">{key}</span>
@@ -2288,6 +2528,36 @@ fn AnswerRow(
</Show>
</article>
}
.into_any()
}
/// A record shown as a card: its picture, its first field as the
/// heading and the others under it, and nothing a reader has no use
/// for - no field names, no state, no time.
#[allow(non_snake_case)]
fn AnswerCard(answer: Answer, picture: String, link: Option<RowLink>) -> impl IntoView {
let link = link.map(|l| (l.href(&answer.id, &answer.responses), l.label));
let texts: Vec<String> = answer
.responses
.as_object()
.into_iter()
.flatten()
.filter_map(|(_, v)| v.as_str())
.filter(|v| uploaded_filename(v).is_none() && !v.trim().is_empty())
.map(str::to_string)
.collect();
let heading = texts.first().cloned().unwrap_or_default();
let rest: Vec<String> = texts.into_iter().skip(1).collect();
view! {
<article class="answer-row answer-card">
<img class="answer-picture" src=picture alt=heading.clone() loading="lazy" />
<div class="answer-card-text">
<h4 class="answer-card-heading">{heading}</h4>
{rest.into_iter().map(|t| view! { <p>{t}</p> }).collect_view()}
</div>
{link.map(|(href, label)| view! { <a class="answer-link" href=href>{label}</a> })}
</article>
}
}
/// Iconify names are `{prefix}:{name}`, both lowercase-alphanumeric-
@@ -2358,13 +2628,15 @@ pub async fn get_question(
use crate::content::{fill_from_user, path_matches, resolve_question};
use crate::server::AppState;
let state = expect_context::<AppState>();
let questions = state.questions.load();
let Some(mut question) = resolve_question(&questions, &path) else {
let storylines = state.questions.load();
let questions = storylines.at(crate::server::storyline::current().await);
let Some(mut question) = resolve_question(questions, &path) else {
return Ok(None);
};
let session: tower_sessions::Session = leptos_axum::extract().await?;
let user = session.get::<User>(SESSION_USER_KEY).await.map_err(|e| ServerFnError::new(e.to_string()))?;
fill_from_user(&mut question, user.as_ref());
crate::answers::fill_own(&state.jetstream, &mut question, user.as_ref()).await;
let mut chain_gate = None;
if let Some(target) = &question.requires_chain {
// The claimed lineage must verifiably end at the required
@@ -2401,11 +2673,12 @@ pub async fn get_question(
pub async fn get_site() -> Result<SiteConfig, ServerFnError> {
use crate::server::AppState;
let state = expect_context::<AppState>();
let mut site = state.site.load().as_ref().clone();
let mut site = state.site.load().at(crate::server::storyline::current().await).clone();
// Not content: whether this instance can serve tiles at all is its
// own configuration, and the browser has to know before it decides
// whether to draw a map or ask for two numbers.
site.maps = crate::maps::enabled();
site.sign_in = state.oidc.enabled();
Ok(site)
}
@@ -2435,7 +2708,8 @@ pub async fn list_qualifying_questions(
.map_err(|e| ServerFnError::new(e.to_string()))?;
let now_ms = chrono::Utc::now().timestamp_millis();
let questions = state.questions.load();
let storylines = state.questions.load();
let questions = storylines.at(crate::server::storyline::current().await);
// What the chain verifiably answered - the same lookup a
// `requires_chain` gate does, so a forged or foreign hash resolves
// to nothing - and therefore where it sent the visitor.
@@ -2583,6 +2857,7 @@ pub async fn suggest_page_edit(question_id: String, text: String) -> Result<(),
SUGGESTION_ALTERNATIVE,
&responses,
now_ms,
0,
)
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
@@ -2593,6 +2868,7 @@ pub async fn suggest_page_edit(question_id: String, text: String) -> Result<(),
alternative: SUGGESTION_ALTERNATIVE.to_string(),
responses: responses.clone(),
timestamp_ms: now_ms,
storyline: 0,
};
if let Err(e) = emit_answer_submitted(&state.nats, &event).await {
tracing::warn!(question_id, "the suggestion is on file but was not announced: {e}");
@@ -2679,7 +2955,8 @@ pub async fn submit_answer(
// resolve_question, not a plain map get: a dynamic page's concrete
// path (what the client holds as its question id) resolves to the
// pattern page it came from.
let question = crate::content::resolve_question(&state.questions.load(), &question_id)
let storyline = crate::server::storyline::current().await;
let question = crate::content::resolve_question(state.questions.load().at(storyline), &question_id)
.ok_or_else(|| ServerFnError::new("unknown question"))?;
let session: tower_sessions::Session = leptos_axum::extract().await?;
@@ -2713,6 +2990,26 @@ pub async fn submit_answer(
let mut responses: serde_json::Value = serde_json::from_str(&responses_json)
.map_err(|e| ServerFnError::new(format!("invalid responses: {e}")))?;
// One card each: whose it is comes from the session, and a file the
// person did not choose again is the one already on their card.
let owner = if alt.one_per_person {
let user = user.as_ref().ok_or_else(|| ServerFnError::new("sign in to keep a card of your own"))?;
let bucket = record_as.clone().ok_or_else(|| ServerFnError::new("this alternative keeps nothing"))?;
let previous = crate::answers::own_records(&state.jetstream, &bucket, &user.username).await.into_iter().next();
if let Some(map) = responses.as_object_mut() {
for req in alt.features.iter().flat_map(|f| &f.requirements).filter(|r| r.kind == "file") {
let chosen = map.get(&req.name).and_then(|v| v.as_str()).is_some_and(|v| !v.is_empty());
if let (false, Some(kept)) = (chosen, previous.as_ref().and_then(|p| p.responses.get(&req.name))) {
map.insert(req.name.clone(), kept.clone());
}
}
map.insert(crate::answers::OWNER_FIELD.to_string(), serde_json::Value::String(user.username.clone()));
}
Some((bucket, user.username.clone()))
} else {
None
};
// A record that belongs to another record: check the other one is
// there before this one is written, so a reference in a stored
// record is one that resolved at least once. An optional field
@@ -2796,6 +3093,7 @@ pub async fn submit_answer(
alternative: alternative.clone(),
responses: responses.clone(),
timestamp_ms,
storyline: storyline as u32,
},
)
.await
@@ -2821,15 +3119,25 @@ pub async fn submit_answer(
&alternative,
&responses,
timestamp_ms,
storyline as u32,
)
.await
{
tracing::error!("failed to store answer in {bucket}: {e}");
}
if let Some((own_bucket, username)) = &owner {
let initial = state
.aggregates
.load()
.get(own_bucket)
.map(|s| s.initial.clone())
.unwrap_or_else(|| crate::answers::OPEN_STATE.to_string());
crate::answers::keep_newest_own(&state.jetstream, own_bucket, &initial, username).await;
}
// Arrival is a state too: what the schema says the first
// state sends, it sends now.
if let Some(initial) = state.aggregates.load().get(bucket).map(|s| s.initial.clone()) {
crate::mail::on_state(&state, bucket, &chain_hash, &initial, &responses).await;
crate::mail::on_state(&state, bucket, &chain_hash, &initial, &responses, storyline as u32).await;
crate::people::on_state(&state, bucket, &chain_hash, &initial, &responses).await;
}
}
@@ -2926,6 +3234,14 @@ mod responsible_tests {
Responsible { name: "R".into(), contact: contact.into(), group: group.map(String::from) }
}
#[test]
fn an_uploads_key_shows_as_the_name_it_was_sent_with() {
assert_eq!(super::uploaded_filename("3f2b8c1e-9a4d-4e7b-8c21-0a1b2c3d4e5f-rapport 2026.pdf"), Some("rapport 2026.pdf"));
assert_eq!(super::uploaded_filename("rapport.pdf"), None);
assert_eq!(super::uploaded_filename("3f2b8c1e-9a4d-4e7b-8c21-0a1b2c3d4e5f-"), None);
assert_eq!(super::uploaded_filename("Storgata 1, 1850 Mysen - se vedlegg i e-post fra oss"), None);
}
#[test]
fn only_the_person_a_page_names_may_suggest_a_change_to_it() {
assert!(is_responsible(Some(&user(Some("kari@vel.no"), &[])), &named("mailto:Kari@Vel.no", None)));
@@ -2945,3 +3261,36 @@ mod responsible_tests {
assert!(!is_responsible(None, &board));
}
}
#[cfg(test)]
mod picture_tests {
use super::*;
#[test]
fn an_upload_refusal_says_which_it_was() {
assert_eq!(upload_refusal(Some(413)), "upload_too_large");
assert_eq!(upload_refusal(Some(503)), "upload_unavailable");
assert_eq!(upload_refusal(Some(403)), "upload_forbidden");
assert_eq!(upload_refusal(Some(502)), "upload_failed");
assert_eq!(upload_refusal(None), "upload_failed");
for lang in ["en", "no"] {
for status in [Some(413), Some(503), Some(403), None] {
let key = upload_refusal(status);
assert_ne!(crate::i18n::t(lang, key), key, "{lang} has words for {key}");
}
}
}
#[test]
fn a_record_with_a_picture_is_shown_by_it() {
assert!(is_picture("Portrett.JPG") && is_picture("a.webp") && !is_picture("rapport.pdf"));
let answer: Answer = serde_json::from_value(serde_json::json!({
"id": "r1", "question_id": "kontor/ansatt", "alternative": "a", "state": "open", "submitted_ms": 1,
"responses": { "name": "Kari", "portrett": "0f8fad5b-d9cb-469f-a165-70867728950e-kari.jpg", "cv": "0f8fad5b-d9cb-469f-a165-70867728950e-cv.pdf" }
}))
.unwrap();
assert_eq!(picture_of(&answer, Some("ansatte")).as_deref(), Some("/attachment/ansatte/r1/portrett"));
// Without a bucket there is nowhere to fetch it from.
assert_eq!(picture_of(&answer, None), None);
}
}
+42 -15
View File
@@ -9,20 +9,27 @@ use super::*;
/// config; a file that exists but doesn't parse or validate is a real
/// error, surfaced at boot rather than papered over.
#[cfg(feature = "ssr")]
pub async fn load_site_from_gitea(repo_url: &str, branch: &str) -> anyhow::Result<SiteConfig> {
pub async fn load_site_from_gitea(repo_url: &str, branch: &str) -> anyhow::Result<Storylines<SiteConfig>> {
let (owner, repo) = parse_owner_repo(repo_url)?;
let api_base = gitea_api_base(repo_url)?;
let raw = match fetch_gitea_file(&api_base, &owner, &repo, branch, "site.yaml").await {
Ok(raw) => raw,
Err(e) => {
tracing::info!("no site.yaml in content repo ({e}), using default branding");
return Ok(SiteConfig::default());
return Ok(Storylines::one(SiteConfig::default()));
}
};
let site: SiteConfig =
serde_yaml::from_str(&raw).map_err(|e| anyhow::anyhow!("parsing site.yaml: {e}"))?;
site.validate()?;
Ok(site)
// The invite mail's words may be several (see `variants.rs`).
let files = vec![("site.yaml".to_string(), raw)];
let arity = super::variants::arity(&files)?;
let mut each = Vec::with_capacity(arity);
for n in 0..arity {
let site: SiteConfig =
serde_yaml::from_str(&super::variants::storyline(&files, n)[0].1).map_err(|e| anyhow::anyhow!("parsing site.yaml: {e}"))?;
site.validate()?;
each.push(site);
}
Ok(Storylines { each })
}
/// Extracts `scheme://host` from a repo's normal browser URL - the
@@ -107,11 +114,18 @@ pub(crate) async fn fetch_gitea_file(
pub async fn load_aggregates_from_gitea(
repo_url: &str,
branch: &str,
) -> anyhow::Result<std::collections::HashMap<String, crate::aggregates::AggregateSchema>> {
) -> anyhow::Result<Storylines<std::collections::HashMap<String, crate::aggregates::AggregateSchema>>> {
let (owner, repo) = parse_owner_repo(repo_url)?;
let api_base = gitea_api_base(repo_url)?;
let raw = fetch_gitea_file(&api_base, &owner, &repo, branch, "aggregates.yaml").await?;
crate::aggregates::parse_aggregates_yaml(&raw)
// A mail's subject and body may be several (see `variants.rs`);
// the runtime's own buckets are added to every storyline.
let files = vec![("aggregates.yaml".to_string(), raw)];
let arity = super::variants::arity(&files)?;
let each = (0..arity)
.map(|n| crate::aggregates::parse_aggregates_yaml(&super::variants::storyline(&files, n)[0].1).map(with_builtin_aggregates))
.collect::<anyhow::Result<Vec<_>>>()?;
Ok(Storylines { each })
}
#[cfg(feature = "ssr")]
@@ -119,7 +133,7 @@ pub async fn load_questions_from_gitea(
repo_url: &str,
branch: &str,
subdir: &str,
) -> anyhow::Result<std::collections::HashMap<String, Question>> {
) -> anyhow::Result<Storylines<std::collections::HashMap<String, Question>>> {
let (owner, repo) = parse_owner_repo(repo_url)?;
let api_base = gitea_api_base(repo_url)?;
@@ -161,7 +175,20 @@ pub async fn load_questions_from_gitea(
.map_err(|e| anyhow::anyhow!("fetching {path}: {e}"))?;
files.push((path[prefix.len()..].to_string(), raw));
}
build_questions(&files)
build_storylines(&files)
}
/// Every storyline's arity is the site's or one: a mail told in two
/// voices on a site whose pages are told in three has a hole in it.
#[cfg(feature = "ssr")]
pub fn same_arity(questions: usize, aggregates: usize, site: usize) -> anyhow::Result<usize> {
let arity = questions.max(aggregates).max(site);
for (what, n) in [("questions", questions), ("aggregates.yaml", aggregates), ("site.yaml", site)] {
if n != 1 && n != arity {
anyhow::bail!("{what} tells {n} storyline(s), but the site tells {arity}; every list of texts has the same length");
}
}
Ok(arity)
}
/// Published by the content repo's own CI (after it lints a push) to
@@ -192,11 +219,11 @@ pub async fn watch_for_reload(
repo_url: String,
branch: String,
subdir: String,
questions: std::sync::Arc<arc_swap::ArcSwap<std::collections::HashMap<String, Question>>>,
questions: std::sync::Arc<arc_swap::ArcSwap<Storylines<std::collections::HashMap<String, Question>>>>,
aggregates: std::sync::Arc<
arc_swap::ArcSwap<std::collections::HashMap<String, crate::aggregates::AggregateSchema>>,
arc_swap::ArcSwap<Storylines<std::collections::HashMap<String, crate::aggregates::AggregateSchema>>>,
>,
site: std::sync::Arc<arc_swap::ArcSwap<SiteConfig>>,
site: std::sync::Arc<arc_swap::ArcSwap<Storylines<SiteConfig>>>,
access: std::sync::Arc<arc_swap::ArcSwap<crate::access::Policy>>,
) {
let mut sub = match nats.subscribe(CONTENT_RELOAD_SUBJECT).await {
@@ -209,7 +236,7 @@ pub async fn watch_for_reload(
use futures::StreamExt;
while sub.next().await.is_some() {
let loaded_aggregates = match load_aggregates_from_gitea(&repo_url, &branch).await {
Ok(loaded) => with_builtin_aggregates(loaded),
Ok(loaded) => loaded,
Err(e) => {
tracing::error!(error = %e, "aggregates.yaml reload failed, keeping last-good content");
continue;
@@ -228,7 +255,7 @@ pub async fn watch_for_reload(
};
match load_questions_from_gitea(&repo_url, &branch, &subdir).await {
Ok(loaded) => {
if let Err(e) = validate_questions(&loaded, &loaded_aggregates) {
if let Err(e) = validate_questions(&loaded, &loaded_aggregates).and_then(|_| same_arity(loaded.arity(), loaded_aggregates.arity(), loaded_site.arity())) {
tracing::error!(error = %e, "content reload failed validation, keeping last-good content");
continue;
}
+6 -1
View File
@@ -74,14 +74,19 @@ pub async fn site_asset_handler(
Some("svg") => "image/svg+xml",
Some("json") => "application/json",
Some("png") => "image/png",
Some("jpg") | Some("jpeg") => "image/jpeg",
Some("webp") => "image/webp",
Some("avif") => "image/avif",
Some("ico") => "image/x-icon",
Some("woff2") => "font/woff2",
_ => "application/octet-stream",
};
// Photographs are large and do not change under a name, so a
// browser may keep them for an hour; everything else revalidates,
// so a content push shows on reload.
let cache = if matches!(mime, "image/webp" | "image/avif" | "image/jpeg") { "public, max-age=3600" } else { "no-cache" };
(
[(header::CONTENT_TYPE, mime), (header::CACHE_CONTROL, "no-cache")],
[(header::CONTENT_TYPE, mime), (header::CACHE_CONTROL, cache)],
bytes,
)
.into_response()
+98 -1
View File
@@ -13,12 +13,16 @@ use serde::{Deserialize, Serialize};
// Loading is server-only; the rest is shared with the browser build.
#[cfg(feature = "ssr")]
mod gitea;
#[cfg(feature = "ssr")]
mod variants;
mod handlers;
mod markdown;
mod validate;
#[cfg(feature = "ssr")]
pub use gitea::*;
#[cfg(feature = "ssr")]
pub use variants::*;
pub use handlers::*;
pub use markdown::*;
pub use validate::*;
@@ -91,6 +95,12 @@ pub struct Question {
/// rather than on the whole world.
#[serde(default)]
pub place: Option<Place>,
/// Pictures across the page, under the question: a strip the full
/// width of the screen that a visitor swipes through, each picture
/// with its caption laid over it. What the business has built,
/// shown rather than described.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slideshow: Option<Slideshow>,
}
/// A point a page is about. `zoom` is a map zoom level, 0 (the globe)
@@ -333,6 +343,14 @@ pub struct Alternative {
/// works (lysbue had the same flag).
#[serde(default)]
pub disabled: bool,
/// Each signed-in person keeps one record here: their own, which
/// sending again replaces. The form opens with what their record
/// says, a file left empty keeps the one already there, and the
/// older record leaves the list. For what a person says about
/// themselves - a card on the front page, a profile. Needs
/// `record_as`, and someone signed in.
#[serde(default)]
pub one_per_person: bool,
#[serde(default)]
pub consequence: Vec<String>,
#[serde(default)]
@@ -621,6 +639,50 @@ pub struct Requirement {
/// listing may ask about a record's own contents: one field, one
/// value, compared as strings. Anything more is a query language, and
/// a jq filter is already there for shaping what comes back.
/// A strip of pictures across a page (`Question.slideshow`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Slideshow {
/// How tall the strip may be, in hundredths of the small viewport
/// height (`svh`): 60 is six tenths of the screen. Every picture is
/// that tall and as wide as its own shape makes it.
#[serde(default = "default_slideshow_height")]
pub max_height: u8,
pub slides: Vec<Slide>,
}
fn default_slideshow_height() -> u8 {
60
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Slide {
/// A path in the content repo (`images/built/01.webp`, served from
/// this origin under `/site/`) or an `https://` address.
pub image: String,
/// Laid over the foot of the picture, and its alternative text.
#[serde(default)]
pub caption: String,
/// The picture's own size in pixels, when known: the browser then
/// holds its place in the strip before it has loaded, so pictures
/// further along can wait until they are swiped to.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub width: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub height: Option<u32>,
}
impl Slide {
/// Where the browser fetches the picture: https as given, anything
/// else as a content-repo path under `/site/`.
pub fn src(&self) -> String {
if self.image.starts_with("https://") || self.image.starts_with("/site/") {
self.image.clone()
} else {
format!("/site/{}", self.image.trim_start_matches('/'))
}
}
}
/// A link from every listed record to a page about it (`ResourceSpec.link`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RowLink {
@@ -725,8 +787,13 @@ pub struct SiteConfig {
/// the way to the browser (see `get_site`), never from content, so
/// a `type: location` field knows whether to offer a map or two
/// number inputs.
#[serde(skip)]
#[serde(default)]
pub maps: bool,
/// Whether this instance has sign-in at all (a provider is
/// configured): set on the way to the browser like `maps`, so the
/// header knows whether to offer it.
#[serde(default)]
pub sign_in: bool,
/// Who this site's mail comes from. Absent means the site sends
/// nothing: a state's `mail:` and the invite mail are logged and
/// skipped, never half-sent (see `mail.rs`).
@@ -1073,6 +1140,25 @@ pub fn resolve_question(
#[cfg(feature = "ssr")]
pub fn build_questions(
files: &[(String, String)],
) -> anyhow::Result<std::collections::HashMap<String, Question>> {
// The first storyline, once every list of texts has been held to
// the site's arity (see `variants.rs`); the machinery reads this
// one, and `build_storylines` builds the rest for the visitors.
variants::arity(files)?;
build_one_storyline(&variants::storyline(files, 0))
}
/// Every storyline of the content, each a full map of questions.
#[cfg(feature = "ssr")]
pub fn build_storylines(files: &[(String, String)]) -> anyhow::Result<variants::Storylines<std::collections::HashMap<String, Question>>> {
let arity = variants::arity(files)?;
let each = (0..arity).map(|n| build_one_storyline(&variants::storyline(files, n))).collect::<anyhow::Result<Vec<_>>>()?;
Ok(variants::Storylines { each })
}
#[cfg(feature = "ssr")]
fn build_one_storyline(
files: &[(String, String)],
) -> anyhow::Result<std::collections::HashMap<String, Question>> {
// Sections first: (directory prefix, config), shallowest first so a
// later (deeper) section overrides an outer one field-by-field.
@@ -1881,6 +1967,17 @@ alternatives:
assert_eq!((reqs[1].kind.as_str(), reqs[1].value.as_deref()), ("text", None));
}
#[test]
fn a_slide_is_fetched_from_this_origin_unless_it_is_https() {
let q: Question = serde_yaml::from_str("name: Q?\nslideshow:\n slides:\n - { image: images/built/01.webp, caption: The canteen, width: 3207, height: 1400 }\n - { image: \"https://cdn.example/a.jpg\" }\n").unwrap();
let show = q.slideshow.unwrap();
assert_eq!(show.max_height, 60);
assert_eq!(show.slides[0].src(), "/site/images/built/01.webp");
assert_eq!(show.slides[0].width, Some(3207));
assert_eq!(show.slides[1].src(), "https://cdn.example/a.jpg");
assert_eq!(show.slides[1].caption, "");
}
#[test]
fn markdown_drops_html_and_unsafe_links() {
assert_eq!(render_inline_markdown("x <script>y</script> z"), "x y z");
+26
View File
@@ -146,6 +146,25 @@ pub fn validate_questions(
}
}
// A slideshow shows something, at a height that leaves the page
// its question: between a fifth and the whole of the screen.
for question in questions.values() {
if let Some(show) = &question.slideshow {
if show.slides.is_empty() {
anyhow::bail!("question {:?}: slideshow has no slides", question.id);
}
if !(20..=100).contains(&show.max_height) {
anyhow::bail!("question {:?}: slideshow max_height is {} svh; between 20 and 100", question.id, show.max_height);
}
for slide in &show.slides {
let ok = slide.image.starts_with("https://") || crate::content::is_safe_site_path(slide.image.trim_start_matches("/site/").trim_start_matches('/'));
if !ok {
anyhow::bail!("question {:?}: slideshow image {:?} is neither an https address nor a path in the content repo", question.id, slide.image);
}
}
}
}
// A mail to the record this one belongs to goes through a field of
// the form: `{notice.email}` needs a `type: record` field called
// `notice` on every form that records into the bucket, or the mail
@@ -493,6 +512,13 @@ pub fn validate_questions(
}
for question in questions.values() {
for alternative in &question.alternatives {
if alternative.one_per_person && alternative.record_as.is_none() {
anyhow::bail!(
"question {:?} alternative {:?}: one_per_person keeps each person's own record, and there is no record_as to keep it in",
question.id,
alternative.name
);
}
if let Some(bucket) = &alternative.record_as {
let attended = read_buckets.contains(bucket)
|| aggregates
+224
View File
@@ -0,0 +1,224 @@
//! Storylines: a text may be several, and `[n]` runs through the site.
//!
//! Anywhere content says something to a person - a page's `name` and
//! `description`, an alternative's, a feature's, a `label`, a
//! `placeholder`, a mail's `subject` and `body`, a list's `empty` line,
//! the `consequence` buttons and `encouragements` - it may give a list
//! instead of one string:
//!
//! ```yaml
//! description:
//! - Dugnad, 17. mai og komiteene trenger flere hender. Si hva du kan.
//! - Naboene gjør det meste selv. Her melder du deg til det du har lyst på.
//! ```
//!
//! Every such list has the same length, the site's *arity*, and a
//! visitor is given one index for the whole site (a cookie, see
//! `main.rs`), so they read one storyline from the front door to the
//! mail they get. A single string is every storyline. What a visitor
//! did is recorded with the index (`AnswerSubmitted.variant`), so the
//! storylines can be compared on what people actually did, and nothing
//! else about them.
//!
//! This is done to the YAML before the structs see it: the files are
//! expanded once per storyline, and everything downstream keeps its one
//! string per field. Keys that name things to the machine - a field's
//! `name`, a select's `options`, states, groups, paths - never vary.
//!
//! The lint holds every list to the arity, so a storyline cannot have
//! a hole in it.
use serde_yaml::Value;
/// Keys whose value is one string to a person.
const TEXT: &[&str] = &["name", "description", "label", "placeholder", "subject", "body", "empty", "title"];
/// Keys whose value is a list of strings to a person; their storylines
/// are a list of lists.
const TEXT_LIST: &[&str] = &["consequence", "encouragements"];
/// Where in a document a key is not text but an identifier: a
/// requirement's `name` is the stored field, never varied.
fn is_identifier(path: &[String], key: &str) -> bool {
// `path` ends with the key itself, then the item's index, then the
// list it is in.
key == "name" && path.iter().rev().nth(2).is_some_and(|p| p == "requirements")
}
fn is_strings(seq: &[Value]) -> bool {
!seq.is_empty() && seq.iter().all(|v| v.is_string())
}
fn is_lists_of_strings(seq: &[Value]) -> bool {
!seq.is_empty() && seq.iter().all(|v| v.as_sequence().is_some_and(|s| s.iter().all(|x| x.is_string())))
}
/// The storyline counts found in a document, with where each was.
fn counts(value: &Value, path: &mut Vec<String>, out: &mut Vec<(String, usize)>) {
match value {
Value::Mapping(map) => {
for (k, v) in map {
let key = k.as_str().unwrap_or_default().to_string();
path.push(key.clone());
let variants = match v {
Value::Sequence(seq) if TEXT.contains(&key.as_str()) && !is_identifier(path, &key) && is_strings(seq) => Some(seq.len()),
Value::Sequence(seq) if TEXT_LIST.contains(&key.as_str()) && is_lists_of_strings(seq) => Some(seq.len()),
_ => None,
};
match variants {
Some(n) => out.push((path.join("."), n)),
None => counts(v, path, out),
}
path.pop();
}
}
Value::Sequence(seq) => {
for (i, v) in seq.iter().enumerate() {
path.push(i.to_string());
counts(v, path, out);
path.pop();
}
}
_ => {}
}
}
/// One storyline of a document: every list of texts becomes its `n`th.
fn pick(value: &mut Value, path: &mut Vec<String>, n: usize) {
match value {
Value::Mapping(map) => {
for (k, v) in map.iter_mut() {
let key = k.as_str().unwrap_or_default().to_string();
path.push(key.clone());
let chosen = match v {
Value::Sequence(seq) if TEXT.contains(&key.as_str()) && !is_identifier(path, &key) && is_strings(seq) => Some(seq[n.min(seq.len() - 1)].clone()),
Value::Sequence(seq) if TEXT_LIST.contains(&key.as_str()) && is_lists_of_strings(seq) => Some(seq[n.min(seq.len() - 1)].clone()),
_ => None,
};
match chosen {
Some(c) => *v = c,
None => pick(v, path, n),
}
path.pop();
}
}
Value::Sequence(seq) => {
for (i, v) in seq.iter_mut().enumerate() {
path.push(i.to_string());
pick(v, path, n);
path.pop();
}
}
_ => {}
}
}
/// How many storylines these files tell: the length every list of
/// texts has, or 1 when there is none. A list of another length is an
/// error that names it.
pub fn arity(files: &[(String, String)]) -> anyhow::Result<usize> {
let mut found: Vec<(String, String, usize)> = Vec::new();
for (rel, raw) in files {
let Ok(value) = serde_yaml::from_str::<Value>(raw) else { continue };
let mut out = Vec::new();
counts(&value, &mut Vec::new(), &mut out);
found.extend(out.into_iter().map(|(p, n)| (rel.clone(), p, n)));
}
let arity = found.iter().map(|(_, _, n)| *n).max().unwrap_or(1);
if let Some((rel, p, n)) = found.iter().find(|(_, _, n)| *n != arity) {
anyhow::bail!("{rel}: {p} tells {n} storyline(s), but the site tells {arity}; every list of texts has the same length");
}
Ok(arity.max(1))
}
/// The files as storyline `n` tells them.
pub fn storyline(files: &[(String, String)], n: usize) -> Vec<(String, String)> {
files
.iter()
.map(|(rel, raw)| {
let Ok(mut value) = serde_yaml::from_str::<Value>(raw) else { return (rel.clone(), raw.clone()) };
let mut out = Vec::new();
counts(&value, &mut Vec::new(), &mut out);
if out.is_empty() {
return (rel.clone(), raw.clone());
}
pick(&mut value, &mut Vec::new(), n);
(rel.clone(), serde_yaml::to_string(&value).unwrap_or_else(|_| raw.clone()))
})
.collect()
}
/// One thing per storyline, and the first as what the machinery reads
/// when nobody in particular is asking: a seed, a lint, a desk sweep.
#[derive(Clone, Debug)]
pub struct Storylines<T> {
pub each: Vec<T>,
}
impl<T> Storylines<T> {
pub fn one(item: T) -> Self {
Storylines { each: vec![item] }
}
pub fn arity(&self) -> usize {
self.each.len().max(1)
}
/// Storyline `n`, or the last for an index from a site that told
/// more storylines than this one does.
pub fn at(&self, n: usize) -> &T {
&self.each[n.min(self.each.len() - 1)]
}
}
impl<T> std::ops::Deref for Storylines<T> {
type Target = T;
fn deref(&self) -> &T {
&self.each[0]
}
}
#[cfg(test)]
mod tests {
use super::*;
const PAGE: &str = "name: [Vil du hjelpe til?, Trenger naboene deg?]\ndescription: Alle trenger flere hender.\nalternatives:\n - name: [Bli med, Meld deg]\n description: [Si hva du kan., Si hva du har lyst på.]\n consequence: [[Send], [Meld meg]]\n features:\n - name: Skjema\n requirements:\n - name: [navn]\n label: [Navn, Hva heter du?]\n - name: hva\n type: select\n options: [Dugnad, Komité]\n";
#[test]
fn every_list_of_texts_is_a_storyline_and_identifiers_are_not() {
let files = vec![("index.yaml".to_string(), PAGE.to_string())];
assert_eq!(arity(&files).unwrap(), 2);
let second = storyline(&files, 1);
let v: Value = serde_yaml::from_str(&second[0].1).unwrap();
assert_eq!(v["name"], "Trenger naboene deg?");
assert_eq!(v["description"], "Alle trenger flere hender.");
assert_eq!(v["alternatives"][0]["name"], "Meld deg");
assert_eq!(v["alternatives"][0]["consequence"], serde_yaml::to_value(vec!["Meld meg"]).unwrap());
// A requirement's name is the stored field: left as written.
assert_eq!(v["alternatives"][0]["features"][0]["requirements"][0]["name"], serde_yaml::to_value(vec!["navn"]).unwrap());
assert_eq!(v["alternatives"][0]["features"][0]["requirements"][0]["label"], "Hva heter du?");
// Options are values people choose from and are stored: untouched.
assert_eq!(v["alternatives"][0]["features"][0]["requirements"][1]["options"], serde_yaml::to_value(vec!["Dugnad", "Komité"]).unwrap());
}
#[test]
fn a_site_with_no_lists_tells_one_storyline_and_a_short_list_is_refused() {
let plain = vec![("index.yaml".to_string(), "name: Hva?\nalternatives:\n - name: A\n consequence: [Send]\n".to_string())];
assert_eq!(arity(&plain).unwrap(), 1);
assert_eq!(storyline(&plain, 0)[0].1, plain[0].1);
let uneven = vec![
("index.yaml".to_string(), PAGE.to_string()),
("b.yaml".to_string(), "name: [En, To, Tre]\n".to_string()),
];
let err = arity(&uneven).unwrap_err().to_string();
assert!(err.contains("b.yaml: name tells 3") && err.contains("tells 2") || err.contains("tells 3"), "{err}");
}
#[test]
fn the_first_storyline_is_what_the_machinery_reads() {
let s = Storylines { each: vec!["a", "b"] };
assert_eq!(*s, "a");
assert_eq!(*s.at(1), "b");
assert_eq!(*s.at(7), "b");
assert_eq!(s.arity(), 2);
}
}
+67 -1
View File
@@ -37,6 +37,55 @@ pub async fn run(state: AppState) {
}
}
/// Records leaving their list: once a record has been in a state with
/// `leaves_after` for that long, it is taken out of the bucket. Not a
/// move - nothing is decided, no mail goes - and the event log keeps
/// the record. Every minute, over the buckets that use it and no
/// others.
pub async fn run_leaving(state: AppState) {
let mut tick = tokio::time::interval(std::time::Duration::from_secs(60));
loop {
tick.tick().await;
if let Err(e) = sweep_leaving(&state).await {
tracing::warn!(error = %e, "leaving sweep failed");
}
}
}
/// Whether a record has stayed out its time in the state it is in.
pub fn has_left(schema: &crate::aggregates::AggregateSchema, answer: &Answer, now_ms: i64) -> bool {
schema
.leaves_for_state
.get(&answer.state)
.is_some_and(|leaves| now_ms >= waiting_since(answer) + leaves.millis())
}
pub async fn sweep_leaving(state: &AppState) -> anyhow::Result<()> {
let now_ms = chrono::Utc::now().timestamp_millis();
let aggregates = state.aggregates.load();
for schema in aggregates.values().filter(|s| !s.leaves_for_state.is_empty()) {
let Ok(store) = state.jetstream.get_key_value(&schema.bucket).await else { continue };
let keys: Vec<String> = {
use futures::TryStreamExt;
match store.keys().await {
Ok(keys) => keys.try_collect().await.unwrap_or_default(),
Err(_) => continue,
}
};
for id in keys {
let Ok(Some(bytes)) = store.get(&id).await else { continue };
let Ok(answer) = serde_json::from_slice::<Answer>(&bytes) else { continue };
if has_left(schema, &answer, now_ms) {
match store.delete(&id).await {
Ok(()) => tracing::info!(bucket = %schema.bucket, id, state = %answer.state, "a record left its list"),
Err(e) => tracing::warn!(bucket = %schema.bucket, id, "a record could not leave its list: {e}"),
}
}
}
}
Ok(())
}
/// When a record entered the state it is in now. A record nobody has
/// moved has been waiting since it was sent.
fn waiting_since(answer: &Answer) -> i64 {
@@ -94,7 +143,7 @@ pub async fn sweep(state: &AppState) -> anyhow::Result<()> {
if let Ok(data) = serde_json::to_vec(&answer) {
let _ = store.put(&id, data.into()).await;
}
crate::mail::on_state(state, &schema.bucket, &id, &target, &answer.responses).await;
crate::mail::on_state(state, &schema.bucket, &id, &target, &answer.responses, answer.storyline).await;
crate::people::on_state(state, &schema.bucket, &id, &target, &answer.responses).await;
let parent_hashes = vec![id.clone()];
@@ -108,6 +157,7 @@ pub async fn sweep(state: &AppState) -> anyhow::Result<()> {
alternative: target.clone(),
responses: payload,
timestamp_ms: now_ms,
storyline: answer.storyline,
},
)
.await
@@ -145,9 +195,25 @@ aggregates:
id: "r".into(), question_id: "/q".into(), alternative: "a".into(),
responses: serde_json::json!({}), state: state.into(),
submitted_ms: since_ms, decided_ms: None, decided_by: None, notes: vec![],
storyline: 0,
}
}
#[test]
fn a_record_leaves_its_list_when_its_time_in_the_state_is_up() {
let s = schema(
"aggregates:\n - bucket: people\n initial: open\n states:\n open: { event: shown }\n gone: { event: gone, leaves_after: { minutes: 10 } }\n transitions:\n open: [gone]\n",
);
let t = 1_000_000_000_000;
let mut answer = waiting("gone", t - 60 * 60 * 1000);
answer.decided_ms = Some(t);
assert!(!has_left(&s, &answer, t + 9 * 60 * 1000), "measured from entering the state, not from sending");
assert!(has_left(&s, &answer, t + 10 * 60 * 1000));
// A state without it keeps its records.
assert!(!has_left(&s, &waiting("open", 0), t));
assert!(crate::aggregates::parse_aggregates_yaml("aggregates:\n - bucket: p\n initial: open\n states:\n open: { event: o, leaves_after: {} }\n transitions: {}\n").is_err());
}
#[test]
fn a_deadline_comes_due_the_day_it_says_and_not_before() {
let s = schema(HEARINGS);
+4
View File
@@ -15,6 +15,10 @@ pub struct AnswerSubmitted {
pub alternative: String,
pub responses: serde_json::Value,
pub timestamp_ms: i64,
/// The storyline the person read (see `content/variants.rs`): what
/// the storylines are compared on, and nothing else about them.
#[serde(default)]
pub storyline: u32,
}
pub const ANSWERS_SUBJECT: &str = "portal.answers.submitted";
+21
View File
@@ -22,7 +22,14 @@ fn lookup(lang: &str, key: &str) -> Option<&'static str> {
("en", "if_stuck") => " if you get stuck.",
("en", "send") => "Send",
("en", "sign_in") => "Sign in",
("en", "sign_out") => "Sign out",
("en", "nothing_here_yet") => "Nothing here yet.",
("en", "upload_failed") => "The file did not arrive, so nothing was sent. Try again.",
("en", "upload_too_large") => "The file is larger than 20 MB, so nothing was sent. Choose a smaller one, or a picture taken at a lower resolution.",
("en", "upload_unavailable") => "This site cannot take files at the moment, so nothing was sent. Let whoever runs the site know.",
("en", "upload_forbidden") => "Files cannot be sent from here by you, so nothing was sent. Are you signed in?",
("en", "current_file") => "Now:",
("en", "keep_file") => "Choose a new one to replace it, or leave it as it is.",
("en", "nothing_here") => "Nothing here",
("en", "back_to_start") => "back to the start",
("en", "done") => "Done.",
@@ -51,7 +58,14 @@ fn lookup(lang: &str, key: &str) -> Option<&'static str> {
("no", "if_stuck") => " om du står fast.",
("no", "send") => "Send",
("no", "sign_in") => "Logg inn",
("no", "sign_out") => "Logg ut",
("no", "nothing_here_yet") => "Ingenting her ennå.",
("no", "upload_failed") => "Filen kom ikke fram, så ingenting ble sendt. Prøv igjen.",
("no", "upload_too_large") => "Filen er større enn 20 MB, så ingenting ble sendt. Velg en mindre fil, eller et bilde med lavere oppløsning.",
("no", "upload_unavailable") => "Siden kan ikke ta imot filer akkurat nå, så ingenting ble sendt. Si fra til den som har siden.",
("no", "upload_forbidden") => "Du kan ikke sende filer herfra, så ingenting ble sendt. Er du logget inn?",
("no", "current_file") => "Nå:",
("no", "keep_file") => "Velg en ny for å bytte, eller la den være.",
("no", "nothing_here") => "Ingenting her",
("no", "back_to_start") => "tilbake til start",
("no", "done") => "Ferdig.",
@@ -98,7 +112,14 @@ mod tests {
"if_stuck",
"send",
"sign_in",
"sign_out",
"nothing_here_yet",
"upload_failed",
"upload_too_large",
"upload_unavailable",
"upload_forbidden",
"current_file",
"keep_file",
"nothing_here",
"back_to_start",
"done",
+9
View File
@@ -35,6 +35,15 @@ pub mod mail;
pub mod seed;
#[cfg(feature = "ssr")]
pub mod memberships;
#[cfg(feature = "ssr")]
pub mod report;
/// The lint: `portal lint`, what a content repo's CI runs (once uhhm/iris).
#[cfg(feature = "ssr")]
pub mod lint;
/// The trainer: `portal plan`, `portal build`, `portal report` and the
/// rest (once uhhm/portal-trainer).
#[cfg(feature = "ssr")]
pub mod trainer;
pub mod maps;
+250
View File
@@ -0,0 +1,250 @@
//! Headless schema-check binary - loads content and `aggregates.yaml`
//! (from a Gitea repo URL or a local directory) and validates them
//! exactly the way `content::watch_for_reload`/`main.rs`'s boot path
//! do, with no NATS, OIDC, web server, or JetStream connection
//! involved. Built once by portal's own deploy workflow and run
//! directly by `questions`' own CI (same bare-metal runner/host,
//! published to a stable path - no artifact download needed), rather
//! than compiled there - keeps that repo's CI coupling to "run a
//! static binary," not "build a Rust workspace."
use crate::lint::local::{load_aggregates_from_dir, load_from_dir, load_needs_from_dir, load_site_from_dir};
use crate::lint::needs;
use crate::{aggregates, content};
pub async fn run(argv: Vec<String>) -> anyhow::Result<()> {
let mut args = argv.into_iter();
let mut repo: Option<String> = None;
let mut branch = "main".to_string();
let mut subdir = "questions".to_string();
let mut path: Option<String> = None;
let mut tasks_out: Option<String> = None;
let mut answers_in: Option<String> = None;
let mut min_accuracy: f64 = 0.0;
let mut skim = false;
let mut sim_out: Option<String> = None;
let mut show_access = false;
while let Some(arg) = args.next() {
match arg.as_str() {
"--repo" => repo = args.next(),
"--branch" => branch = args.next().unwrap_or(branch),
"--subdir" => subdir = args.next().unwrap_or(subdir),
"--path" => path = args.next(),
"--needs-tasks" => tasks_out = args.next(),
"--skim" => skim = true,
"--needs-sim" => sim_out = args.next(),
"--access" => show_access = true,
"--needs-score" => answers_in = args.next(),
"--min-accuracy" => {
min_accuracy = args.next().and_then(|v| v.parse().ok()).unwrap_or(min_accuracy)
}
other => {
eprintln!("unknown argument: {other}");
std::process::exit(2);
}
}
}
let (questions, aggregates_map, site, needs_raw) = if let Some(dir) = path {
(
load_from_dir(&dir)?,
load_aggregates_from_dir(&dir)?,
load_site_from_dir(&dir)?,
load_needs_from_dir(&dir)?,
)
} else if let Some(repo_url) = repo {
// The first storyline of each, as the checks read it; the
// loaders have held every list of texts to the site's arity.
let questions = content::load_questions_from_gitea(&repo_url, &branch, &subdir).await?.at(0).clone();
let aggregates_map = content::load_aggregates_from_gitea(&repo_url, &branch).await?.at(0).clone();
// load_site_from_gitea already validates; a missing file is
// the default config, same as at portal boot.
let site = content::load_site_from_gitea(&repo_url, &branch).await?.at(0).clone();
// Optional: a fetch failure means the repo declares no needs.
let needs_raw = crate::http::get_text(&format!("{}/needs.yaml?ref={branch}", content::gitea_raw_base(&repo_url)?), crate::http::GITEA_CAP).await.ok();
(questions, aggregates_map, site, needs_raw)
} else {
eprintln!(
"usage: iris check (--repo <gitea-url> [--branch main] [--subdir questions] | --path <local-dir>) [--needs-tasks <out.jsonl> [--skim]] [--needs-sim <model.json>] [--access] [--needs-score <answers.jsonl> [--min-accuracy 0.8]]"
);
std::process::exit(2);
};
if let Err(e) = site.validate() {
eprintln!("FAIL: {e}");
std::process::exit(1);
}
let aggregates_map = content::with_builtin_aggregates(aggregates_map);
match content::validate_questions(&questions, &aggregates_map) {
Ok(()) => {
// The runtime's own event desk: a repo announcing pages
// (Question.event) should read portal_events somewhere, or
// "post what happened" tasks pile up unseen. Warn, don't
// fail - the runtime creates the records either way.
if questions.values().any(|q| q.event.is_some())
&& !content::bucket_is_read(&questions, content::EVENTS_BUCKET)
{
eprintln!(
"WARN: pages carry `event:` but no kv resource reads bucket {:?} - add a desk so summaries get posted",
content::EVENTS_BUCKET
);
}
println!(
"OK: {} question(s), {} aggregate(s) valid",
questions.len(),
aggregates_map.len()
);
// The access policy the site will compile from this content.
// It must type-check against portal's schema: a rule the
// schema cannot express would grant nothing at runtime.
let policy = crate::access::Policy::from_content(&questions, &aggregates_map);
if let Err(e) = policy.validate() {
eprintln!("FAIL: access policy does not validate: {e}");
std::process::exit(1);
}
println!("OK: access policy, {} rule(s), validates", policy.rules.len());
if show_access {
println!("\n{:<16} {:<44} {:<40} {}", "ACTION", "RESOURCE", "WHO", "WHEN");
let mut rows = policy.rules.clone();
rows.sort_by(|a, b| (&a.resource, &a.action, &a.who).cmp(&(&b.resource, &b.action, &b.who)));
for r in rows {
println!("{:<16} {:<44} {:<40} {}", r.action, r.resource, r.who, r.when);
}
println!();
}
check_needs(
needs_raw.as_deref(),
&questions,
&aggregates_map,
tasks_out.as_deref(),
skim,
sim_out.as_deref(),
answers_in.as_deref(),
min_accuracy,
)
}
Err(e) => {
eprintln!("FAIL: {e}");
std::process::exit(1);
}
}
}
/// The business-needs pass (see `crate::lint::needs`): structure always,
/// then the wording tasks written out and/or an engine's answers
/// scored, when asked. A repo without `needs.yaml` skips all of it.
fn check_needs(
raw: Option<&str>,
questions: &std::collections::HashMap<String, content::Question>,
aggregates_map: &std::collections::HashMap<String, aggregates::AggregateSchema>,
tasks_out: Option<&str>,
skim: bool,
sim_out: Option<&str>,
answers_in: Option<&str>,
min_accuracy: f64,
) -> anyhow::Result<()> {
let Some(raw) = raw else {
if tasks_out.is_some() || answers_in.is_some() {
eprintln!("FAIL: --needs-tasks/--needs-score given, but the repo has no needs.yaml");
std::process::exit(1);
}
return Ok(());
};
let file = match needs::parse(raw) {
Ok(file) => file,
Err(e) => {
eprintln!("FAIL: {e}");
std::process::exit(1);
}
};
let findings = needs::check(&file, questions, aggregates_map);
let mut failed = 0;
for finding in &findings {
let level = match finding.level {
needs::Level::Fail => {
failed += 1;
"FAIL"
}
needs::Level::Warn => "WARN",
};
eprintln!("{level}: need {:?}: {}", finding.need, finding.message);
}
for need in &file.needs {
if let Some(path) = needs::path_for(questions, need) {
let steps: Vec<String> = path
.iter()
.map(|s| format!("{} [{}]", s.page, s.alternative))
.collect();
println!("need {:?}: {} -> {:?}", need.id, steps.join(" -> "), need.lands_in);
}
}
if failed == 0 {
let planned = file.needs.iter().filter(|n| n.planned && !n.paused).count();
let paused = file.needs.iter().filter(|n| n.paused).count();
println!(
"OK: {} need(s) structurally met, {} planned, {} paused, {} persona(s)",
file.needs.len() - planned - paused,
planned,
paused,
file.personas.len()
);
}
// The wording pass still runs for the needs that do have a path -
// a closed flow elsewhere is no reason to stop grading the rest.
if let Some(out) = sim_out {
let model = needs::sim_model(&file, questions, aggregates_map);
std::fs::write(out, serde_json::to_string_pretty(&model)?)
.map_err(|e| anyhow::anyhow!("writing {out}: {e}"))?;
println!("wrote the simulation model to {out}");
}
let tasks = needs::tasks(&file, questions, skim);
if let Some(out) = tasks_out {
let mut lines = String::new();
for task in &tasks {
lines.push_str(&serde_json::to_string(task)?);
lines.push('\n');
}
std::fs::write(out, lines).map_err(|e| anyhow::anyhow!("writing {out}: {e}"))?;
println!("wrote {} wording task(s) to {out}", tasks.len());
}
if let Some(path) = answers_in {
let raw = std::fs::read_to_string(path).map_err(|e| anyhow::anyhow!("reading {path}: {e}"))?;
let mut answers = Vec::new();
for (n, line) in raw.lines().enumerate().filter(|(_, l)| !l.trim().is_empty()) {
answers.push(
serde_json::from_str::<needs::Answer>(line)
.map_err(|e| anyhow::anyhow!("{path}:{}: {e}", n + 1))?,
);
}
let score = needs::score(&tasks, &answers, 0.6);
for (id, picked, expected, confidence) in &score.misroutes {
eprintln!(
"MISROUTE: {id}: picked {picked:?}{}, the need is met by {expected:?}",
confidence.map(|c| format!(" ({c:.2})")).unwrap_or_default()
);
}
for (id, confidence) in &score.hesitant {
eprintln!("HESITANT: {id}: right, at {confidence:.2}");
}
for id in &score.unanswered {
eprintln!("UNANSWERED: {id}");
}
println!(
"wording: {}/{} routed right ({:.0}%)",
score.correct,
score.total,
score.accuracy() * 100.0
);
if score.accuracy() < min_accuracy {
eprintln!("FAIL: below --min-accuracy {min_accuracy}");
std::process::exit(1);
}
}
if failed > 0 {
eprintln!("FAIL: {failed} unmet business need finding(s)");
std::process::exit(1);
}
Ok(())
}
+105
View File
@@ -0,0 +1,105 @@
//! Loading a content repo from a local checkout - the offline
//! counterparts to the Gitea loaders in `content`, for tools that lint
//! or replay a branch that has not been pushed (question_lint,
//! needs_replay). `dir` is always the pages directory (`questions/`);
//! `site.yaml`, `aggregates.yaml` and `needs.yaml` sit one level up.
use crate::{aggregates, content};
/// The offline counterpart to `content::load_site_from_gitea` -
/// `site.yaml` lives at the repo root like `aggregates.yaml`, and is
/// just as optional locally: missing means default branding.
pub fn load_site_from_dir(dir: &str) -> anyhow::Result<content::SiteConfig> {
let site_path = std::path::Path::new(dir)
.parent()
.unwrap_or_else(|| std::path::Path::new("."))
.join("site.yaml");
if !site_path.exists() {
return Ok(content::SiteConfig::default());
}
let raw = std::fs::read_to_string(&site_path)
.map_err(|e| anyhow::anyhow!("reading {}: {e}", site_path.display()))?;
// The first storyline, held to the arity (content::variants).
let files = vec![("site.yaml".to_string(), raw)];
content::arity(&files)?;
serde_yaml::from_str(&content::storyline(&files, 0)[0].1).map_err(|e| anyhow::anyhow!("parsing {}: {e}", site_path.display()))
}
/// The offline counterpart to `content::load_aggregates_from_gitea` -
/// `aggregates.yaml` lives at the repo root, one level up from the
/// pages directory `--path` names, so `dir`'s parent is where it's
/// looked for. Missing entirely is not an error here (unlike
/// `--repo` mode, where `aggregates.yaml` is required) - a local
/// checkout being linted may not have one, and every declared
/// transition still gets checked against whatever *is* found; an
/// empty map just means nothing is checked.
pub fn load_aggregates_from_dir(
dir: &str,
) -> anyhow::Result<std::collections::HashMap<String, aggregates::AggregateSchema>> {
let aggregates_path = std::path::Path::new(dir)
.parent()
.unwrap_or_else(|| std::path::Path::new("."))
.join("aggregates.yaml");
if !aggregates_path.exists() {
return Ok(std::collections::HashMap::new());
}
let raw = std::fs::read_to_string(&aggregates_path)
.map_err(|e| anyhow::anyhow!("reading {}: {e}", aggregates_path.display()))?;
// The first storyline, held to the arity (content::variants).
let files = vec![("aggregates.yaml".to_string(), raw)];
content::arity(&files)?;
aggregates::parse_aggregates_yaml(&content::storyline(&files, 0)[0].1)
}
/// The offline counterpart to `content::load_questions_from_gitea` -
/// the same recursive tree walk and `content::build_questions`
/// pipeline (derived ids, relative refs, sections, followup
/// inference), just reading a local checkout instead of Gitea's API,
/// for linting a branch that hasn't been pushed yet.
pub fn load_from_dir(
dir: &str,
) -> anyhow::Result<std::collections::HashMap<String, content::Question>> {
let base = std::path::Path::new(dir);
let mut files = Vec::new();
collect_yaml(base, base, &mut files)?;
content::build_questions(&files)
}
fn collect_yaml(
base: &std::path::Path,
dir: &std::path::Path,
out: &mut Vec<(String, String)>,
) -> anyhow::Result<()> {
for entry in std::fs::read_dir(dir)? {
let path = entry?.path();
if path.is_dir() {
collect_yaml(base, &path, out)?;
} else if path.extension().and_then(|e| e.to_str()) == Some("yaml") {
let rel = path
.strip_prefix(base)
.expect("walked paths sit under their base")
.to_string_lossy()
.replace('\\', "/");
let raw = std::fs::read_to_string(&path)
.map_err(|e| anyhow::anyhow!("reading {}: {e}", path.display()))?;
out.push((rel, raw));
}
}
Ok(())
}
/// The offline counterpart to `check`'s needs.yaml fetch -
/// `needs.yaml` sits at the repo root beside `aggregates.yaml`.
pub fn load_needs_from_dir(dir: &str) -> anyhow::Result<Option<String>> {
let needs_path = std::path::Path::new(dir)
.parent()
.unwrap_or_else(|| std::path::Path::new("."))
.join("needs.yaml");
if !needs_path.exists() {
return Ok(None);
}
std::fs::read_to_string(&needs_path)
.map(Some)
.map_err(|e| anyhow::anyhow!("reading {}: {e}", needs_path.display()))
}
+53
View File
@@ -0,0 +1,53 @@
//! iris - the shield over a portal site. A content push is an incoming
//! wormhole; nothing comes through until it checks out.
//!
//! `iris check` loads a content repo (a Gitea URL or a local checkout)
//! exactly the way the running site does, validates it, and holds it to
//! the business needs it declares in `needs.yaml` - a path within
//! budget for every kind of visitor, a desk for every handling group,
//! every finished state reachable, no record stranding. It also exports
//! what a trainer needs to grade the wording: personas as typed choice
//! tasks, and a resolved simulation model.
//!
//! `iris replay` runs simulated cases through the site's real aggregate
//! engine on a JetStream and reports every bucket by state; with
//! `--report-only` it takes the same scorecard from a live site's
//! buckets.
//!
//! Every type iris reads is portal's own, pinned to the portal release
//! it matches, so the lint and the site never disagree about what a
//! page is.
mod check;
mod local;
mod needs;
mod replay;
/// The lint, as `portal lint ...`: `argv` is everything after `portal`.
pub async fn run(mut argv: Vec<String>) -> anyhow::Result<()> {
// `iris --path questions` reads as `iris check --path questions`,
// so the content repos' one-line CI keeps working as it was.
match argv.first().map(String::as_str) {
Some("check") => {
argv.remove(0);
check::run(argv).await
}
Some("replay") => {
argv.remove(0);
replay::run(argv).await
}
Some("--version") | Some("-V") => {
println!("portal lint v{}", env!("CARGO_PKG_VERSION"));
Ok(())
}
Some(flag) if flag.starts_with("--") => check::run(argv).await,
_ => {
eprintln!(
"iris {v} - matches portal v{v}\n\nusage:\n iris check (--repo <gitea-url> [--branch main] [--subdir questions] | --path <dir>) [--needs-tasks <out.jsonl> [--skim]] [--needs-sim <model.json>] [--access] [--needs-score <answers.jsonl> [--min-accuracy 0.8]]\n iris replay --path <dir> --nats <url> (--cases <cases.jsonl> | --report-only)",
v = env!("CARGO_PKG_VERSION")
);
std::process::exit(2)
}
}
}
+1040
View File
File diff suppressed because it is too large Load Diff
+105
View File
@@ -0,0 +1,105 @@
//! Makes a simulation's cases real: every case becomes an aggregate in
//! its bucket, created and moved by the same code the running site
//! uses - `answers::store_answer` for the submission,
//! `aggregates::transition` for each desk move, against a real
//! JetStream with its event log and its refusal of undeclared moves.
//! Then the buckets are read back by replaying each record's events,
//! and reported per need against `done_when` and `success`.
//!
//! The report half runs on its own (`--report-only`) against any
//! JetStream, which is how the same scorecard is taken from a live
//! site's buckets.
//!
//! Point it at a throwaway NATS, never a site's own: it writes.
use std::collections::{BTreeMap, HashMap};
use futures::StreamExt;
use crate::events::store::{ensure_stream, load_events};
use crate::lint::local::{load_aggregates_from_dir, load_from_dir, load_needs_from_dir};
use crate::lint::needs;
use crate::{aggregates, answers, content};
pub async fn run(argv: Vec<String>) -> anyhow::Result<()> {
let value = |flag: &str| argv.iter().position(|a| a == flag).and_then(|i| argv.get(i + 1)).cloned();
let usage = "usage: iris replay --path <questions dir> --nats <url> (--cases <cases.jsonl> | --report-only)";
let dir = value("--path").ok_or_else(|| anyhow::anyhow!(usage))?;
let nats_url = value("--nats").ok_or_else(|| anyhow::anyhow!(usage))?;
let cases_path = value("--cases");
if cases_path.is_none() && !argv.iter().any(|a| a == "--report-only") {
anyhow::bail!(usage);
}
let questions = load_from_dir(&dir)?;
let schemas = content::with_builtin_aggregates(load_aggregates_from_dir(&dir)?);
let file = needs::parse(&load_needs_from_dir(&dir)?.ok_or_else(|| anyhow::anyhow!("the repo has no needs.yaml"))?)?;
let js = async_nats::jetstream::new(async_nats::connect(&nats_url).await?);
// The same call the site makes at boot.
ensure_stream(&js).await?;
if let Some(path) = cases_path {
let raw = std::fs::read_to_string(&path).map_err(|e| anyhow::anyhow!("reading {path}: {e}"))?;
let (mut created, mut moved, mut refused) = (0, 0, 0);
for (n, line) in raw.lines().filter(|l| !l.trim().is_empty()).enumerate() {
let case: serde_json::Value = serde_json::from_str(line)?;
let Some(need) = file.needs.iter().find(|need| case["need"] == need.id.as_str()) else { continue };
let Some(schema) = schemas.get(&need.lands_in) else { continue };
// Only a case that got as far as submitting leaves a record.
let states: Vec<&str> = case["states"].as_array().into_iter().flatten().filter_map(|s| s.as_str()).collect();
if states.is_empty() {
continue;
}
let step = needs::path_for(&questions, need).and_then(|p| p.last().cloned());
let (page, alternative) = step.map(|s| (s.page, s.alternative)).unwrap_or_default();
let id = format!("sim-{}-{}-{n}", case["persona"].as_str().unwrap_or("x"), case["run"]);
let now = chrono::Utc::now().timestamp_millis();
answers::store_answer(&js, &schemas, &need.lands_in, id.clone(), &page, &alternative, &case["record"], now, 0).await?;
created += 1;
for target in &states[1..] {
match aggregates::transition(&js, schema, &id, target, serde_json::json!({"by": "simulation"}), now).await {
Ok(_) => moved += 1,
Err(e) => {
refused += 1;
eprintln!("REFUSED by the engine: {id} -> {target}: {e:?}");
break;
}
}
}
}
println!("{created} aggregate(s) created, {moved} transition(s) accepted, {refused} refused by the engine\n");
}
// Read every bucket back the way the engine knows it: by replaying
// each record's own event log.
let mut by_bucket: HashMap<String, BTreeMap<String, usize>> = HashMap::new();
for bucket in file.needs.iter().map(|n| n.lands_in.clone()).collect::<std::collections::BTreeSet<_>>() {
let (Some(schema), Ok(store)) = (schemas.get(&bucket), js.get_key_value(&bucket).await) else { continue };
let mut keys = store.keys().await?;
while let Some(Ok(id)) = keys.next().await {
let events = load_events(&js, &bucket, &id).await?;
if let Some(record) = aggregates::replay(schema, &id, &events) {
*by_bucket.entry(bucket.clone()).or_default().entry(record.state).or_default() += 1;
}
}
}
println!("{:<18} {:>8} {:>9} {:>9} {}", "bucket", "records", "finished", "success", "by state");
let mut buckets: Vec<_> = by_bucket.iter().collect();
buckets.sort();
for (bucket, states) in buckets {
let needs_here: Vec<&needs::Need> = file.needs.iter().filter(|n| &n.lands_in == bucket).collect();
let is = |pick: fn(&needs::Need) -> &Vec<String>, state: &String| needs_here.iter().any(|n| pick(n).contains(state));
let total: usize = states.values().sum();
let finished: usize = states.iter().filter(|(s, _)| is(|n| &n.done_when, s)).map(|(_, c)| c).sum();
let success: usize = states.iter().filter(|(s, _)| is(|n| &n.success, s)).map(|(_, c)| c).sum();
let pct = |n: usize| if total == 0 { "-".to_string() } else { format!("{:.0}%", n as f64 * 100.0 / total as f64) };
println!(
"{:<18} {:>8} {:>9} {:>9} {}",
bucket,
total,
pct(finished),
pct(success),
states.iter().map(|(s, c)| format!("{s} {c}")).collect::<Vec<_>>().join(", ")
);
}
Ok(())
}
+7 -3
View File
@@ -306,8 +306,10 @@ async fn publish(js: &async_nats::jetstream::Context, mail: &Outgoing) -> anyhow
/// if anything. Best-effort by design - the transition is already
/// committed, and a mail that cannot be rendered is logged, never a
/// failed request.
pub async fn on_state(state: &crate::server::AppState, bucket: &str, id: &str, to_state: &str, responses: &serde_json::Value) {
let Some(spec) = state.aggregates.load().get(bucket).and_then(|s| s.mail_for(to_state)).cloned() else {
pub async fn on_state(state: &crate::server::AppState, bucket: &str, id: &str, to_state: &str, responses: &serde_json::Value, storyline: u32) {
// The mail tells the storyline the person read.
let storyline = storyline as usize;
let Some(spec) = state.aggregates.load().at(storyline).get(bucket).and_then(|s| s.mail_for(to_state)).cloned() else {
// A suggestion has its own words for this unless the content
// gave the state a mail, which then is the one sent.
if bucket == crate::content::EDIT_SUGGESTIONS_BUCKET {
@@ -315,7 +317,8 @@ pub async fn on_state(state: &crate::server::AppState, bucket: &str, id: &str, t
}
return;
};
let site = state.site.load();
let site_storylines = state.site.load();
let site = site_storylines.at(storyline);
let Some(cfg) = &site.mail else {
tracing::warn!(bucket, to_state, "a mail is declared for this state, but site.yaml has no `mail.from` - not sent");
return;
@@ -702,6 +705,7 @@ mod tests {
responses: serde_json::json!({ "email": email, "where": "The bend" }),
state: "open".into(),
submitted_ms: 1,
storyline: 0,
decided_ms: None,
decided_by: None,
notes: Vec::new(),
+97 -47
View File
@@ -1,6 +1,31 @@
/// One binary, three jobs: `portal` (or `portal serve`) runs a site;
/// `portal lint` checks a content repo the way the site reads it;
/// `portal plan`, `build`, `report` and the rest train one. The lint
/// and the trainer are the same code as the server, at the same
/// version, so they never disagree about what content means.
#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let argv: Vec<String> = std::env::args().skip(1).collect();
match argv.first().map(String::as_str) {
Some("lint") => return portal::lint::run(argv[1..].to_vec()).await,
Some("plan" | "build" | "answer" | "rate" | "prefer" | "score" | "simulate" | "compare" | "report" | "generate") => {
// The trainer runs models through shell commands and waits
// on them; off the runtime's threads, as a CLI should.
return tokio::task::spawn_blocking(move || portal::trainer::run(argv)).await?;
}
Some("--version" | "-V") => {
println!("portal v{}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
Some("serve") | None => {}
Some(other) => anyhow::bail!("portal: unknown command {other:?}; one of serve, lint, plan, build, answer, rate, prefer, score, simulate, compare, report, generate"),
}
serve().await
}
#[cfg(feature = "ssr")]
async fn serve() -> anyhow::Result<()> {
use axum::{body::Body, extract::State, http::Request, response::IntoResponse, routing::{any, get, post}, Router};
use leptos::prelude::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
@@ -30,13 +55,12 @@ async fn main() -> anyhow::Result<()> {
let content_branch = std::env::var("CONTENT_BRANCH").unwrap_or_else(|_| "main".to_string());
let gitea_base = content::gitea_api_base(&content_repo)?;
let content_raw_base = content::gitea_raw_base(&content_repo)?;
let aggregates = content::with_builtin_aggregates(
content::load_aggregates_from_gitea(&content_repo, &content_branch).await?,
);
let aggregates = content::load_aggregates_from_gitea(&content_repo, &content_branch).await?;
let questions = content::load_questions_from_gitea(&content_repo, &content_branch, "questions").await?;
content::validate_questions(&questions, &aggregates)?;
let site = content::load_site_from_gitea(&content_repo, &content_branch).await?;
tracing::info!(count = questions.len(), repo = %content_repo, branch = %content_branch, "loaded content");
let storylines = content::same_arity(questions.arity(), aggregates.arity(), site.arity())?;
tracing::info!(count = questions.len(), storylines, repo = %content_repo, branch = %content_branch, "loaded content");
let access = Arc::new(arc_swap::ArcSwap::from_pointee(portal::access::Policy::from_content(&questions, &aggregates)));
let questions = Arc::new(arc_swap::ArcSwap::from_pointee(questions));
let aggregates = Arc::new(arc_swap::ArcSwap::from_pointee(aggregates));
@@ -108,6 +132,7 @@ async fn main() -> anyhow::Result<()> {
// windows (see announce.rs).
tokio::spawn(portal::announce::run(state.clone()));
tokio::spawn(portal::deadlines::run(state.clone()));
tokio::spawn(portal::deadlines::run_leaving(state.clone()));
// The accounts the content mandates: the first person in, and
// everyone a page names as responsible, at start and whenever the
// content changes (seed.rs).
@@ -142,30 +167,32 @@ async fn main() -> anyhow::Result<()> {
.with_name("portal_session");
// What a person does costs a little; what a script does costs a
// lot. A burst of 30 with one refilled every two seconds is well
// above anything a visitor filling in a form will reach - a page
// load fetches several resources at once - and well below what it
// takes to be a nuisance. Per caller IP, in memory, no store: this
// is a fence, not an accounting system, and the fence that matters
// for uploads is the policy check on the route itself.
// lot. More than a hundred requests in ten seconds is a script: a
// burst of 100, refilled at ten a second. Someone reloading a page
// again and again stays well inside it, the more so since the
// files a page is made of (stylesheet, scripts, fonts, pictures)
// are not counted at all - see `assets` below. Per caller IP, in
// memory, no store: this is a fence, not an accounting system, and
// the fence that matters for uploads is the policy check on the
// route itself.
//
// PORTAL_RATE_PER_SECOND / PORTAL_RATE_BURST retune it per site;
// 0 for either turns it off, for an instance behind something that
// already does this.
let rate_seconds: u64 = std::env::var("PORTAL_RATE_SECONDS")
let rate_per_second: u64 = std::env::var("PORTAL_RATE_PER_SECOND")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(2);
.unwrap_or(10);
let rate_burst: u32 = std::env::var("PORTAL_RATE_BURST")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(30);
let governor = (rate_seconds > 0 && rate_burst > 0).then(|| {
.unwrap_or(100);
let governor = (rate_per_second > 0 && rate_burst > 0).then(|| {
// SmartIpKeyExtractor reads X-Forwarded-For/X-Real-IP, which is
// what every one of these instances is behind; it falls back to
// the socket address when neither is set.
let conf = tower_governor::governor::GovernorConfigBuilder::default()
.per_second(rate_seconds)
.per_millisecond((1000 / rate_per_second).max(1))
.burst_size(rate_burst)
.key_extractor(tower_governor::key_extractor::SmartIpKeyExtractor)
.finish()
@@ -173,8 +200,8 @@ async fn main() -> anyhow::Result<()> {
std::sync::Arc::new(conf)
});
match &governor {
Some(_) => tracing::info!(rate_seconds, rate_burst, "rate limiting per caller IP"),
None => tracing::warn!("rate limiting is off (PORTAL_RATE_SECONDS or PORTAL_RATE_BURST is 0)"),
Some(_) => tracing::info!(rate_per_second, rate_burst, "rate limiting per caller IP"),
None => tracing::warn!("rate limiting is off (PORTAL_RATE_PER_SECOND or PORTAL_RATE_BURST is 0)"),
}
async fn server_fn_handler(
@@ -207,33 +234,15 @@ async fn main() -> anyhow::Result<()> {
let maplibre_js = format!("{}/maplibre-gl.js", leptos_options.site_root);
let maplibre_css = format!("{}/maplibre-gl.css", leptos_options.site_root);
let fonts_dir = format!("{}/fonts", leptos_options.site_root);
let page_motion = format!("{}/page-motion.js", leptos_options.site_root);
let app = Router::new()
.route("/auth/login", get(oidc::login))
.route("/auth/callback", get(oidc::callback))
.route("/auth/logout", get(oidc::logout))
.route("/api/{*fn_name}", any(server_fn_handler))
// axum caps request bodies at 2 MB by default, which had made the
// 20 MB upload limit unreachable; raise the fence on this route only,
// with room for the multipart framing.
.route(
"/upload",
post(upload::upload).layer(axum::extract::DefaultBodyLimit::max(upload::MAX_UPLOAD_BYTES + 64 * 1024)),
)
.route(
"/attachment/{bucket}/{record}/{field}",
get(upload::attachment),
)
.route("/gitea-repo", get(content::gitea_repo_handler))
// Content-shipped assets (hero module etc.), same-origin.
.route("/site/{*path}", get(content::site_asset_handler))
.route("/automation/kv/{bucket}", get(content::automation_kv_handler))
// Maps, proxied: the browser asks this origin for every tile
// and every still, so nothing third-party loads in a page and
// the token stays here (see maps.rs).
.route("/map/style.json", get(portal::maps::style))
.route("/map/tiles/{z}/{x}/{y}", get(portal::maps::tile))
.route("/map/still/{place}/{size}", get(portal::maps::still))
// The files a page is made of, from this disk: the stylesheet, the
// scripts, the fonts. Not counted by the rate limit - they cost
// next to nothing, and refusing one is what turns a reloaded page
// into an unstyled mess - and no session is loaded for them.
// Anything that makes portal ask someone else (content pictures
// from Gitea, map tiles) stays below, counted.
let assets: Router<AppState> = Router::new()
// no-cache = "revalidate before reuse", not "don't cache":
// pkg files keep the same names across releases (portal.js,
// portal.wasm), and without this browsers heuristically cache
@@ -258,8 +267,47 @@ async fn main() -> anyhow::Result<()> {
"/swiper-element-bundle.min.js",
ServeFile::new(swiper_path),
)
// Same name every release, so revalidated like /pkg.
.route_service(
"/page-motion.js",
tower::ServiceBuilder::new()
.layer(tower_http::set_header::SetResponseHeaderLayer::overriding(
axum::http::header::CACHE_CONTROL,
axum::http::HeaderValue::from_static("no-cache"),
))
.service(ServeFile::new(page_motion)),
)
.route_service("/maplibre-gl.js", ServeFile::new(maplibre_js))
.route_service("/maplibre-gl.css", ServeFile::new(maplibre_css))
.route_service("/maplibre-gl.css", ServeFile::new(maplibre_css));
let app = Router::new()
.route("/auth/login", get(oidc::login))
.route("/auth/callback", get(oidc::callback))
.route("/auth/logout", get(oidc::logout))
.route("/api/{*fn_name}", any(server_fn_handler))
// axum caps request bodies at 2 MB by default, which had made the
// 20 MB upload limit unreachable; raise the fence on this route only,
// with room for the multipart framing.
.route(
"/upload",
post(upload::upload).layer(axum::extract::DefaultBodyLimit::max(upload::MAX_UPLOAD_BYTES + 64 * 1024)),
)
.route(
"/attachment/{bucket}/{record}/{field}",
get(upload::attachment),
)
.route("/gitea-repo", get(content::gitea_repo_handler))
// What the storylines did, as counts (report.rs).
.route("/report", get(portal::report::handler))
// Content-shipped assets (hero module etc.), same-origin.
.route("/site/{*path}", get(content::site_asset_handler))
.route("/automation/kv/{bucket}", get(content::automation_kv_handler))
// Maps, proxied: the browser asks this origin for every tile
// and every still, so nothing third-party loads in a page and
// the token stays here (see maps.rs).
.route("/map/style.json", get(portal::maps::style))
.route("/map/tiles/{z}/{x}/{y}", get(portal::maps::tile))
.route("/map/still/{place}/{size}", get(portal::maps::still))
.leptos_routes_with_context(
&state,
routes,
@@ -273,14 +321,16 @@ async fn main() -> anyhow::Result<()> {
},
)
.fallback(leptos_axum::file_and_error_handler::<AppState, _>(shell))
.layer(session_layer);
.layer(session_layer)
// Which storyline this visitor reads, before anything renders.
.layer(axum::middleware::from_fn_with_state(state.clone(), portal::server::storyline::assign));
// Outermost, so a caller who is over the limit is turned away
// before a session is loaded or a handler is entered.
let app = match governor {
Some(conf) => app.layer(tower_governor::GovernorLayer::new(conf)),
None => app,
}
.with_state(state);
};
let app = assets.merge(app).with_state(state);
tracing::info!("listening on http://{addr}");
let listener = tokio::net::TcpListener::bind(&addr).await?;
+3 -1
View File
@@ -226,6 +226,7 @@ async fn move_to(state: &crate::server::AppState, store: &async_nats::jetstream:
alternative: target.to_string(),
responses: payload,
timestamp_ms: now_ms,
storyline: answer.storyline,
};
let _ = crate::events::emit_answer_submitted(&state.nats, &event).await;
Ok(answer)
@@ -266,7 +267,7 @@ pub async fn grant(state: &crate::server::AppState, group: &str, name: &str, who
"name": name, "group": group, "by": by,
"phone": who.phone, "email": who.email, "sub": who.sub,
});
crate::answers::store_answer(&state.jetstream, &state.aggregates.load(), BUCKET, id, "/", "Membership", &responses, now_ms).await?;
crate::answers::store_answer(&state.jetstream, &state.aggregates.load(), BUCKET, id, "/", "Membership", &responses, now_ms, 0).await?;
Ok(invited(true))
}
}
@@ -346,6 +347,7 @@ mod tests {
responses: serde_json::json!({ "group": group, "phone": phone, "email": email, "sub": sub, "name": "X" }),
state: state.into(),
submitted_ms: 0,
storyline: 0,
decided_ms: None,
decided_by: None,
notes: Vec::new(),
+14 -5
View File
@@ -184,6 +184,12 @@ fn name_from_search(body: &str) -> Option<String> {
pub struct Kanidm {
base: String,
token: String,
/// What this site's groups are called in a Kanidm it shares with
/// other sites: `KANIDM_GROUP_PREFIX=klingenberg_` makes the
/// content's `kunder` the group `klingenberg_kunder` there. The
/// OAuth2 client's claim map takes the prefix off again, so content
/// and policy never see it. Empty for a Kanidm of the site's own.
group_prefix: String,
}
impl Kanidm {
@@ -192,7 +198,8 @@ impl Kanidm {
pub fn from_env() -> Option<Self> {
let base = std::env::var("KANIDM_URL").ok()?.trim_end_matches('/').to_string();
let token = std::env::var("KANIDM_API_TOKEN").ok().filter(|t| !t.is_empty())?;
Some(Kanidm { base, token })
let group_prefix = std::env::var("KANIDM_GROUP_PREFIX").unwrap_or_default().trim().to_string();
Some(Kanidm { base, token, group_prefix })
}
async fn call(&self, method: openidconnect::reqwest::Method, path: &str, body: Option<serde_json::Value>) -> anyhow::Result<(u16, String)> {
@@ -262,7 +269,7 @@ impl Kanidm {
/// Who is in a group, by account name.
pub async fn members(&self, group: &str) -> anyhow::Result<Vec<String>> {
let (status, text) = self.call(openidconnect::reqwest::Method::GET, &format!("/v1/group/{group}/_attr/member"), None).await?;
let (status, text) = self.call(openidconnect::reqwest::Method::GET, &format!("/v1/group/{}{group}/_attr/member", self.group_prefix), None).await?;
if !(200..300).contains(&status) {
anyhow::bail!("kanidm: reading the members of {group}: http {status}: {text}");
}
@@ -273,7 +280,7 @@ impl Kanidm {
/// service account manages, like adding them was.
pub async fn remove_member(&self, group: &str, username: &str) -> anyhow::Result<()> {
let (status, text) = self
.call(openidconnect::reqwest::Method::DELETE, &format!("/v1/group/{group}/_attr/member"), Some(serde_json::json!([username])))
.call(openidconnect::reqwest::Method::DELETE, &format!("/v1/group/{}{group}/_attr/member", self.group_prefix), Some(serde_json::json!([username])))
.await?;
if !(200..300).contains(&status) {
anyhow::bail!("kanidm: removing {username} from {group}: http {status}: {text}");
@@ -340,7 +347,7 @@ impl Kanidm {
// tidying up after itself.
already_member = !created && self.members(group).await.is_ok_and(|m| m.contains(&username));
let (status, text) = self
.call(openidconnect::reqwest::Method::POST, &format!("/v1/group/{group}/_attr/member"), Some(serde_json::json!([username])))
.call(openidconnect::reqwest::Method::POST, &format!("/v1/group/{}{group}/_attr/member", self.group_prefix), Some(serde_json::json!([username])))
.await?;
if !(200..300).contains(&status) {
anyhow::bail!("kanidm: adding {username} to {group}: http {status}: {text}");
@@ -414,7 +421,7 @@ pub async fn record(state: &crate::server::AppState, invited: &Invited, responsi
responses["responsible_for"] = serde_json::json!(responsible_for);
}
let id = crate::chain::hash_node("/", &[], &responses, now_ms);
if let Err(e) = crate::answers::store_answer(&state.jetstream, &state.aggregates.load(), INVITES_BUCKET, id, "/", SEED_ALTERNATIVE, &responses, now_ms).await {
if let Err(e) = crate::answers::store_answer(&state.jetstream, &state.aggregates.load(), INVITES_BUCKET, id, "/", SEED_ALTERNATIVE, &responses, now_ms, 0).await {
tracing::warn!(user = %invited.username, "the invite is sent, but could not be put on file for a desk: {e}");
}
}
@@ -454,6 +461,7 @@ async fn move_invite(state: &crate::server::AppState, store: &async_nats::jetstr
alternative: target.to_string(),
responses: payload,
timestamp_ms: now_ms,
storyline: answer.storyline,
};
if let Err(e) = crate::events::emit_answer_submitted(&state.nats, &event).await {
tracing::warn!(id = %answer.id, target, "the invite was moved but not published: {e}");
@@ -702,6 +710,7 @@ mod tests {
}}),
state: state.into(),
submitted_ms: 1_000,
storyline: 0,
decided_ms: None,
decided_by: None,
notes: Vec::new(),
+53
View File
@@ -0,0 +1,53 @@
//! What the storylines did, as numbers and nothing else.
//!
//! `GET /report` answers with a count per bucket, per storyline, per
//! state: how many cases each storyline brought in and where they got
//! to. That is the whole of what the storylines are compared on. No
//! record, no field, no address, no time leaves the site: a storyline
//! is assigned evenly, so the counts are the comparison, and the
//! trainer (`portal-trainer report`) reads them to say which words
//! worked. Public, since a count is what a public list already shows.
#![cfg(feature = "ssr")]
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
/// The report: the site's storylines, and per bucket the count of
/// records by storyline and state.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Report {
pub storylines: usize,
/// bucket -> storyline (as a string, JSON's way) -> state -> count
pub buckets: BTreeMap<String, BTreeMap<String, BTreeMap<String, u64>>>,
}
pub async fn gather(state: &crate::server::AppState) -> Report {
let mut report = Report { storylines: state.questions.load().arity(), buckets: BTreeMap::new() };
let aggregates = state.aggregates.load();
for bucket in aggregates.keys() {
// The runtime's own buckets are not the site's offers.
if bucket.starts_with("portal_") {
continue;
}
let Ok(store) = state.jetstream.get_key_value(bucket).await else { continue };
let keys: Vec<String> = {
use futures::TryStreamExt;
match store.keys().await {
Ok(keys) => keys.try_collect().await.unwrap_or_default(),
Err(_) => continue,
}
};
let counts = report.buckets.entry(bucket.clone()).or_default();
for key in keys {
let Ok(Some(bytes)) = store.get(&key).await else { continue };
let Ok(answer) = serde_json::from_slice::<crate::answers::Answer>(&bytes) else { continue };
*counts.entry(answer.storyline.to_string()).or_default().entry(answer.state).or_default() += 1;
}
}
report
}
pub async fn handler(axum::extract::State(state): axum::extract::State<crate::server::AppState>) -> axum::Json<Report> {
axum::Json(gather(&state).await)
}
+64 -12
View File
@@ -33,13 +33,13 @@ pub async fn get_resource(
use crate::server::AppState;
let state = expect_context::<AppState>();
let feature = find_feature(&state, &question_id, &alternative, &feature_name)?;
let feature = find_feature(&state, crate::server::storyline::current().await, &question_id, &alternative, &feature_name)?;
let resource = feature
.resource
.as_ref()
.ok_or_else(|| ServerFnError::new("feature has no resource"))?;
authorize_resource(&state, &question_id, &alternative, &feature_name).await?;
fetch_resource_value(&state, resource, &params).await
fetch_resource_value(&state, resource, &as_the_person_asking(params).await).await
}
/// The `Requirement.resource`-backed counterpart to `get_resource` -
@@ -62,7 +62,7 @@ pub async fn get_requirement_options(
use crate::server::AppState;
let state = expect_context::<AppState>();
let feature = find_feature(&state, &question_id, &alternative, &feature_name)?;
let feature = find_feature(&state, crate::server::storyline::current().await, &question_id, &alternative, &feature_name)?;
let requirement = feature
.requirements
.iter()
@@ -83,7 +83,7 @@ pub async fn get_requirement_options(
.as_ref()
.ok_or_else(|| ServerFnError::new("requirement has no resource"))?;
authorize_resource(&state, &question_id, &alternative, &format!("{feature_name}|{requirement_name}")).await?;
fetch_resource_value(&state, resource, &params).await
fetch_resource_value(&state, resource, &as_the_person_asking(params).await).await
}
/// The `Requirement.bind`-backed counterpart to
@@ -103,7 +103,7 @@ pub async fn get_requirement_binding(
use crate::server::AppState;
let state = expect_context::<AppState>();
let feature = find_feature(&state, &question_id, &alternative, &feature_name)?;
let feature = find_feature(&state, crate::server::storyline::current().await, &question_id, &alternative, &feature_name)?;
let requirement = feature
.requirements
.iter()
@@ -114,7 +114,7 @@ pub async fn get_requirement_binding(
.as_ref()
.ok_or_else(|| ServerFnError::new("requirement has no binding"))?;
authorize_resource(&state, &question_id, &alternative, &format!("{feature_name}|{requirement_name}|bind")).await?;
fetch_resource_value(&state, &bind.resource, &params).await
fetch_resource_value(&state, &bind.resource, &as_the_person_asking(params).await).await
}
/// Scoped to the named alternative first, not flattened across all of
@@ -128,6 +128,7 @@ pub async fn get_requirement_binding(
#[cfg(feature = "ssr")]
fn find_feature(
state: &crate::server::AppState,
storyline: usize,
question_id: &str,
alternative: &str,
feature_name: &str,
@@ -137,7 +138,7 @@ fn find_feature(
// also what substitutes the URL segment into the page's resource
// keys - so this lookup is where a `/review/<record>` page's
// feature acquires its record-specific key.
let question = crate::content::resolve_question(&state.questions.load(), question_id)
let question = crate::content::resolve_question(state.questions.load().at(storyline), question_id)
.ok_or_else(|| ServerFnError::new("unknown question"))?;
question
.alternatives
@@ -210,8 +211,12 @@ fn shows_state(resource: &crate::content::ResourceSpec, value: &serde_json::Valu
/// stamped on it. A missing field never matches: "everything that did
/// not say" is not something a page should be able to ask for by
/// accident.
///
/// `equals: "{user.email}"` is the signed-in person's own address: a
/// list of "my cases". It is filled from the session, never from the
/// caller, and with nobody signed in it matches nothing.
#[cfg(feature = "ssr")]
fn matches_filter(
pub(crate) fn matches_filter(
resource: &crate::content::ResourceSpec,
value: &serde_json::Value,
params: &std::collections::HashMap<String, String>,
@@ -219,19 +224,54 @@ fn matches_filter(
let Some(filter) = &resource.filter else {
return true;
};
let wanted = crate::content::template_action(&filter.equals, &serde_json::json!(params))
.unwrap_or_else(|| filter.equals.clone());
let equals = if filter.equals.contains("{user.email}") {
match params.get(USER_EMAIL).filter(|e| !e.is_empty()) {
Some(email) => filter.equals.replace("{user.email}", email),
None => return false,
}
} else {
filter.equals.clone()
};
let wanted = crate::content::template_action(&equals, &serde_json::json!(params)).unwrap_or(equals);
// Addresses compare without case; everything else as written.
let same = |found: &str| if filter.equals.contains("{user.email}") { found.trim().eq_ignore_ascii_case(&wanted) } else { found == wanted };
let found = value
.get("responses")
.and_then(|r| r.get(&filter.field))
.or_else(|| value.get(&filter.field));
match found {
Some(serde_json::Value::String(s)) => s == &wanted,
Some(other) => other.to_string() == wanted,
Some(serde_json::Value::String(s)) => same(s),
Some(other) => same(&other.to_string()),
None => false,
}
}
/// The parameter a `where` reads the signed-in person's address from.
/// Set by the server from the session; a caller's own is thrown away.
#[cfg(feature = "ssr")]
pub(crate) const USER_EMAIL: &str = "__user_email";
/// The caller's parameters with the session's person put in and
/// anything pretending to be them taken out.
#[cfg(feature = "ssr")]
pub(crate) fn with_person(mut params: std::collections::HashMap<String, String>, user: Option<&crate::auth::User>) -> std::collections::HashMap<String, String> {
params.retain(|k, _| !k.starts_with("__"));
if let Some(email) = user.and_then(|u| u.email.as_deref()).filter(|e| !e.trim().is_empty()) {
params.insert(USER_EMAIL.to_string(), email.trim().to_lowercase());
}
params
}
#[cfg(feature = "ssr")]
async fn as_the_person_asking(params: std::collections::HashMap<String, String>) -> std::collections::HashMap<String, String> {
use crate::auth::{User, SESSION_USER_KEY};
let user = match leptos_axum::extract::<tower_sessions::Session>().await {
Ok(session) => session.get::<User>(SESSION_USER_KEY).await.ok().flatten(),
Err(_) => None,
};
with_person(params, user.as_ref())
}
#[cfg(feature = "ssr")]
async fn fetch_resource_value(
state: &crate::server::AppState,
@@ -558,6 +598,18 @@ mod tests {
assert!(!matches_filter(&children, &theirs, &params));
// A record that did not say is not everyone's child.
assert!(!matches_filter(&children, &neither, &params));
// "My cases": the session's address, never the caller's.
let own = spec("source: { kind: kv, bucket: cases }\nrequires_group: customers\nwhere: { field: email, equals: \"{user.email}\" }\n");
let hers = serde_json::json!({ "responses": { "email": "Kari@Vel.no" } });
let his = serde_json::json!({ "responses": { "email": "ola@vel.no" } });
let kari = crate::auth::User { sub: "s".into(), username: "kari".into(), display_name: "Kari".into(), groups: vec![], phone: None, email: Some("kari@vel.no".into()) };
let forged: std::collections::HashMap<String, String> = [(USER_EMAIL.to_string(), "ola@vel.no".to_string())].into_iter().collect();
let asked = with_person(forged.clone(), Some(&kari));
assert!(matches_filter(&own, &hers, &asked) && !matches_filter(&own, &his, &asked));
// Nobody signed in: the forged parameter is dropped, and nothing matches.
let anonymous = with_person(forged, None);
assert!(!matches_filter(&own, &hers, &anonymous) && !matches_filter(&own, &his, &anonymous));
// No filter, no narrowing: every resource written before this
// existed still lists its whole bucket.
let plain = spec("source: { kind: kv, bucket: objections }\npublic: true\n");
+4 -3
View File
@@ -1,6 +1,7 @@
#![cfg(feature = "ssr")]
pub mod oidc;
pub mod storyline;
use arc_swap::ArcSwap;
use axum::extract::FromRef;
@@ -21,18 +22,18 @@ pub struct AppState {
/// message (see `content::watch_for_reload`) - readers never hold
/// a lock, just an atomic pointer load, so a reload never blocks or
/// is blocked by an in-flight request.
pub questions: Arc<ArcSwap<HashMap<String, Question>>>,
pub questions: Arc<ArcSwap<crate::content::Storylines<HashMap<String, Question>>>>,
/// Every bucket's event-sourced state graph, loaded from
/// `aggregates.yaml` (see `content::load_aggregates_from_gitea`) and
/// hot-swapped alongside `questions` on the same reload. A bucket
/// with no entry here isn't event-sourced - plain KV mutate-in-place
/// still works (see `answers.rs`).
pub aggregates: Arc<ArcSwap<HashMap<String, crate::aggregates::AggregateSchema>>>,
pub aggregates: Arc<ArcSwap<crate::content::Storylines<HashMap<String, crate::aggregates::AggregateSchema>>>>,
/// Site branding from the content repo's optional `site.yaml`
/// (title, wordmark, hero kind) - hot-swapped with `questions`/
/// `aggregates` on the same reload. Default = the historical uhhm
/// look.
pub site: Arc<ArcSwap<crate::content::SiteConfig>>,
pub site: Arc<ArcSwap<crate::content::Storylines<crate::content::SiteConfig>>>,
/// The access policy compiled from the content above (see
/// `access.rs`), swapped with it on every reload. Every server entry
/// point decides through this and nothing else.
+5
View File
@@ -50,6 +50,11 @@ const NONCE_KEY: &str = "oidc_nonce";
const REDIRECT_KEY: &str = "oidc_post_login_redirect";
impl Oidc {
/// Whether a provider is configured.
pub fn enabled(&self) -> bool {
self.inner.is_some()
}
/// Sign-in disabled: what a content-only instance has, and what a
/// test builds an `AppState` with.
pub fn disabled() -> Self {
+70
View File
@@ -0,0 +1,70 @@
//! Which storyline a visitor reads (see `content/variants.rs`): one
//! index for the whole site, chosen at their first request and kept in
//! a cookie for a year, so every page and every mail they get tells
//! the same story. A site that tells one story sets no cookie.
#![cfg(feature = "ssr")]
use axum::{
extract::{Request, State},
http::header::{COOKIE, SET_COOKIE},
middleware::Next,
response::Response,
};
pub const COOKIE_NAME: &str = "portal_storyline";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Storyline(pub usize);
/// The index in a request's cookies, if it names one this site tells.
fn from_cookies(header: Option<&str>, arity: usize) -> Option<usize> {
header?
.split(';')
.map(str::trim)
.find_map(|kv| kv.strip_prefix(COOKIE_NAME).and_then(|rest| rest.strip_prefix('=')))
.and_then(|v| v.trim().parse::<usize>().ok())
.filter(|n| *n < arity)
}
/// Evenly, from nothing about the person.
fn pick(arity: usize) -> usize {
(uuid::Uuid::new_v4().as_u128() % arity.max(1) as u128) as usize
}
pub async fn assign(State(state): State<super::AppState>, mut req: Request, next: Next) -> Response {
let arity = state.questions.load().arity();
let held = from_cookies(req.headers().get(COOKIE).and_then(|v| v.to_str().ok()), arity);
let n = held.unwrap_or_else(|| pick(arity));
req.extensions_mut().insert(Storyline(n));
let mut res = next.run(req).await;
if held.is_none() && arity > 1 {
if let Ok(value) = format!("{COOKIE_NAME}={n}; Path=/; Max-Age=31536000; SameSite=Lax").parse() {
res.headers_mut().append(SET_COOKIE, value);
}
}
res
}
/// The storyline of the request a server function is answering, or
/// the first when there is none to ask (a call outside a request).
pub async fn current() -> usize {
leptos_axum::extract::<axum::Extension<Storyline>>()
.await
.map(|axum::Extension(Storyline(n))| n)
.unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_cookie_names_a_storyline_the_site_tells() {
assert_eq!(from_cookies(Some("a=b; portal_storyline=1; c=d"), 3), Some(1));
assert_eq!(from_cookies(Some("portal_storyline=7"), 3), None);
assert_eq!(from_cookies(Some("portal_storylines=1"), 3), None);
assert_eq!(from_cookies(None, 3), None);
assert!(pick(1) == 0);
assert!((0..50).all(|_| pick(3) < 3));
}
}
+3804
View File
File diff suppressed because it is too large Load Diff
+101
View File
@@ -0,0 +1,101 @@
//! An alternative as the visitor meets it, in text.
//!
//! Portal renders a card: the heading, the description, a button, one
//! or two encouragements, and for each section an icon, a title, a
//! line of guidance and the fields with their labels and placeholders.
//! A visitor is oriented by all of it, not the heading alone. The
//! answering visitor and `rate` both read this rendering, so the
//! scored page is the served page; the gutted twin keeps the card's
//! shape and none of its words.
use serde_json::Value;
pub fn s(v: &Value) -> &str {
v.as_str().unwrap_or_default()
}
/// One option on a page. `full` is the card as rendered; otherwise the
/// heading alone, which is what a visitor who reads nothing else sees.
pub fn alternative(alt: &Value, full: bool) -> String {
let mut out = format!("- {}", s(&alt["name"]));
if !full {
out.push('\n');
return out;
}
let d = s(&alt["description"]).trim();
if !d.is_empty() {
out.push_str(&format!(": {d}"));
}
out.push('\n');
if let Some(button) = alt["consequence"].as_array().and_then(|c| c.first()).and_then(Value::as_str) {
out.push_str(&format!(" Button: {button}\n"));
}
for e in alt["encouragements"].as_array().into_iter().flatten().filter_map(Value::as_str) {
out.push_str(&format!(" {e}\n"));
}
for f in alt["features"].as_array().into_iter().flatten() {
let (name, desc, icon) = (s(&f["name"]).trim(), s(&f["description"]).trim(), s(&f["icon"]).trim());
let mut line = String::from(" ");
if !icon.is_empty() {
line.push_str(&format!("[icon {}] ", icon.rsplit(':').next().unwrap_or(icon)));
}
if !name.is_empty() {
line.push_str(name);
}
if !desc.is_empty() {
line.push_str(&format!("{}{desc}", if name.is_empty() { "" } else { ": " }));
}
if !line.trim().is_empty() {
out.push_str(line.trim_end());
out.push('\n');
}
let fields: Vec<String> = f["requirements"]
.as_array()
.into_iter()
.flatten()
.map(|r| {
let label = r["label"].as_str().unwrap_or_else(|| s(&r["name"]));
let hint = s(&r["placeholder"]).trim();
let opt = if r["optional"] == true { " (optional)" } else { "" };
if hint.is_empty() { format!("{label}{opt}") } else { format!("{label}{opt} e.g. {hint}") }
})
.collect();
if !fields.is_empty() {
out.push_str(&format!(" Asks for: {}\n", fields.join("; ")));
}
}
out
}
/// The page around its options: what it asks and says of itself.
pub fn page_head(page: &Value) -> String {
let mut out = format!("{}\n", s(&page["name"]));
let d = s(&page["description"]).trim();
if !d.is_empty() {
out.push_str(&format!("{d}\n"));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_card_reads_as_the_visitor_sees_it_and_a_heading_alone_is_a_heading_alone() {
let alt = json!({
"name": "Get a price", "description": "For owners.",
"consequence": ["Send it"], "encouragements": ["We answer within two days."],
"features": [{"name": "Your brief", "icon": "lucide:file-text", "description": "A few lines are enough.",
"requirements": [{"name": "email", "label": "Email", "placeholder": "you@example.no"},
{"name": "address", "label": "Address", "optional": true}]}]
});
let full = alternative(&alt, true);
assert!(full.starts_with("- Get a price: For owners.\n"));
assert!(full.contains("Button: Send it") && full.contains("We answer within two days."));
assert!(full.contains("[icon file-text] Your brief: A few lines are enough."));
assert!(full.contains("Asks for: Email e.g. you@example.no; Address (optional)"));
assert_eq!(alternative(&alt, false), "- Get a price\n");
}
}
+593
View File
@@ -0,0 +1,593 @@
//! Generates a portal content repo from a business intake.
//!
//! Three phases, each held to portal's `question_lint`:
//!
//! 1. **Needs.** The intake (what the business does, who comes to it,
//! what it keeps track of and through which stages, who handles
//! what) becomes `needs.yaml`. After this phase the file is frozen:
//! it is the spec, and the generator may not weaken it to pass.
//! 2. **Structure.** Pages, `aggregates.yaml` and desks are generated
//! and revised against the lint's findings until it exits zero.
//! 3. **Wording.** The personas are answered blind (headings only,
//! then with descriptions) and misroutes are fed back as wording
//! defects. Only pages may change.
//!
//! The LLM is an external command: prompt on stdin, text on stdout.
//! `claude -p` works; so does anything else with that shape.
use std::collections::BTreeMap;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use anyhow::{anyhow, bail, Context};
pub mod build;
mod card;
pub mod plan;
mod rate;
mod report;
mod score;
mod simulate;
pub const REFERENCE: &str = include_str!("reference.md");
struct Opts {
intake: PathBuf,
out: PathBuf,
lint: String,
llm: String,
rounds: usize,
wording_rounds: usize,
/// The model that plays the visitor. A generator grading its own
/// wording agrees with itself, so this should be a different one.
visitor: Option<String>,
}
/// The trainer, as `portal <command> ...`: `argv` is everything after
/// `portal`. `answer --tasks <file> [--llm <cmd>]` is the blind
/// answerer alone, for grading an existing site with any backend;
/// answers go to stdout, ready for `portal lint --needs-score`.
pub fn run(argv: Vec<String>) -> anyhow::Result<()> {
match argv.first().map(String::as_str) {
Some("simulate") => return simulate::run(&argv),
Some("compare") => return simulate::compare(&argv),
Some("plan") => return plan::run(&argv),
Some("build") => return build::run(&argv),
Some("rate") => return rate::rate(&argv),
Some("report") => return report::run(&argv),
Some("prefer") => return rate::prefer(&argv),
Some("score") => return score::run(&argv),
_ => {}
}
if argv.first().map(String::as_str) == Some("answer") {
let value = |flag: &str| {
argv.iter()
.position(|a| a == flag)
.and_then(|i| argv.get(i + 1))
.cloned()
};
let tasks = value("--tasks").ok_or_else(|| anyhow!("usage: portal-trainer answer --tasks <tasks.jsonl> [--repo <content dir>] [--llm 'cmd'] [--seed <n>]"))?;
let cmd = value("--llm").unwrap_or_else(|| "claude -p".to_string());
let repo = value("--repo").map(PathBuf::from);
// --seed: the same tasks answered again with other shuffles and
// sampling, so a score comes with its spread. 0 is the run
// every earlier score used.
let seed: u64 = value("--seed").and_then(|s| s.parse().ok()).unwrap_or(0);
print!("{}", answer_blind(&cmd, &std::fs::read_to_string(&tasks).with_context(|| format!("reading {tasks}"))?, repo.as_deref(), seed)?);
return Ok(());
}
let opts = parse_args()?;
let intake = std::fs::read_to_string(&opts.intake)
.with_context(|| format!("reading {}", opts.intake.display()))?;
std::fs::create_dir_all(opts.out.join("questions"))?;
std::fs::create_dir_all(opts.out.join("llm"))?;
LLM_LOG.set(opts.out.join("llm")).ok();
let mut log = Vec::new();
// Phase 1: the spec.
let mut feedback = String::new();
for round in 1..=opts.rounds {
let prompt = format!(
"{REFERENCE}\n\n# Task\n\nA business filled in this intake. Write ONLY `needs.yaml` for it: every need the intake implies, for the public and for each role inside the business, with states taken from how the business says things progress, and personas.\n\n## Intake\n\n{intake}\n{feedback}\n{FORMAT}"
);
let Ok(files) = parse_files(&llm(&opts.llm, &prompt)?) else {
eprintln!("needs round {round}: the reply had no file blocks, asking again");
feedback = "\n## Your last attempt\n\nIt contained no <<<FILE ...>>> blocks at all. Return needs.yaml in exactly that format.\n".to_string();
continue;
};
let Some(needs) = files.get("needs.yaml") else {
feedback = "\n## Your last attempt\n\nIt contained no needs.yaml.\n".to_string();
continue;
};
std::fs::write(opts.out.join("needs.yaml"), needs)?;
// A placeholder front door, so the lint gets as far as parsing
// the spec; every need fails, a parse error is what we look for.
std::fs::write(opts.out.join("questions/index.yaml"), "name: Placeholder?\n")?;
let (_, report) = lint(&opts, &[])?;
if let Some(line) = report.lines().find(|l| l.contains("parsing needs.yaml")) {
eprintln!("needs round {round}: {line}");
feedback = format!("\n## Your last attempt failed to parse\n\n{line}\n\n```yaml\n{needs}\n```\n");
continue;
}
eprintln!("needs round {round}: needs.yaml parses, frozen");
log.push(format!("needs: parsed in round {round}"));
feedback.clear();
break;
}
if !feedback.is_empty() {
bail!("needs.yaml never parsed in {} round(s); the replies are in {}/llm/", opts.rounds, opts.out.display());
}
let needs = std::fs::read_to_string(opts.out.join("needs.yaml")).context("no needs.yaml was produced")?;
// Phase 2: structure. The page-writing model sees the needs and
// never the personas: pages written with the test in view route
// their own personas perfectly and strangers badly (measured:
// 10/10 on its own personas, 8/10 headings-only on held-out ones).
let needs_full = needs;
let needs = needs_full
.split("\npersonas:")
.next()
.unwrap_or(&needs_full)
.to_string();
let mut green = false;
let mut report = String::new();
for round in 1..=opts.rounds {
let prompt = if round == 1 {
format!(
"{REFERENCE}\n\n# Task\n\nWrite the content repo that meets this frozen `needs.yaml`: `aggregates.yaml`, `site.yaml`, and every page under `questions/` - the front door, followup pages, role-gated pages, one desk per handling group. Do not return needs.yaml.\n\n## Intake\n\n{intake}\n\n## needs.yaml (frozen)\n\n```yaml\n{needs}\n```\n\n{FORMAT}"
)
} else {
format!(
"{REFERENCE}\n\n# Task\n\nThe verifier rejected the repo below. Fix it. Return only the files you change, each complete. To remove a file, return it with the single line DELETE. needs.yaml is frozen; do not return it.\n\n## Verifier output\n\n```\n{report}\n```\n\n## needs.yaml (frozen)\n\n```yaml\n{needs}\n```\n\n## Current files\n\n{}\n\n{FORMAT}",
dump(&opts.out)?
)
};
match parse_files(&llm(&opts.llm, &prompt)?) {
Ok(files) => apply(&opts.out, files)?,
Err(_) => eprintln!("structure round {round}: the reply had no file blocks"),
}
let (ok, r) = lint(&opts, &[])?;
report = r;
let fails = report.lines().filter(|l| l.starts_with("FAIL")).count();
eprintln!("structure round {round}: {}", if ok { "green".to_string() } else { format!("{fails} FAIL line(s)") });
log.push(format!("structure round {round}: ok={ok} fails={fails}"));
if ok {
green = true;
break;
}
}
if !green {
std::fs::write(opts.out.join("run.log"), format!("{}\n\n{report}", log.join("\n")))?;
bail!("structure never went green in {} round(s); last verifier output is in run.log", opts.rounds);
}
// Phase 3: wording.
for round in 0..=opts.wording_rounds {
let mut defects = String::new();
let mut summary = Vec::new();
for skim in [true, false] {
let tasks_path = opts.out.join(if skim { "tasks-skim.jsonl" } else { "tasks.jsonl" });
let mut args = vec!["--needs-tasks".to_string(), tasks_path.display().to_string()];
if skim {
args.push("--skim".to_string());
}
lint(&opts, &args)?;
let answers = answer_blind(opts.visitor.as_deref().unwrap_or(&opts.llm), &std::fs::read_to_string(&tasks_path)?, Some(&opts.out), 0)?;
let answers_path = opts.out.join(if skim { "answers-skim.jsonl" } else { "answers.jsonl" });
std::fs::write(&answers_path, answers)?;
let mut args = vec!["--needs-score".to_string(), answers_path.display().to_string()];
if skim {
args.push("--skim".to_string());
}
let (_, scored) = lint(&opts, &args)?;
let mode = if skim { "headings only" } else { "headings and descriptions" };
for line in scored.lines().filter(|l| l.starts_with("MISROUTE") || l.starts_with("HESITANT")) {
defects.push_str(&format!("[{mode}] {line}\n"));
}
if let Some(line) = scored.lines().find(|l| l.starts_with("wording:")) {
summary.push(format!("{mode}: {line}"));
}
}
eprintln!("wording round {round}: {}", summary.join(" | "));
log.push(format!("wording round {round}: {}", summary.join(" | ")));
if defects.is_empty() || round == opts.wording_rounds {
break;
}
let personas = needs_full.split("\npersonas:").nth(1).unwrap_or_default();
let prompt = format!(
"{REFERENCE}\n\n# Task\n\nThe structure is correct. Visitors are picking the wrong alternative. Each MISROUTE below is a persona who, reading the page, chose an alternative that does not meet their need; HESITANT means they chose right and nearly did not. Rewrite alternative headings first (a heading that needs its description has failed), descriptions second. Keep every `record_as`, `action`, field and state as it is. If you rename an alternative that needs.yaml names in `via`, you may not: keep that one. Return only the pages you change, each complete.\n\n## Defects\n\n```\n{defects}```\n\n## The personas\n\n```yaml\npersonas:{personas}\n```\n\n## Current files\n\n{}\n\n{FORMAT}",
dump(&opts.out)?
);
let before = snapshot(&opts.out)?;
apply(&opts.out, parse_files(&llm(&opts.llm, &prompt)?)?)?;
let (ok, r) = lint(&opts, &[])?;
if !ok {
eprintln!("wording round {round}: the rewrite broke structure, reverted");
log.push(format!("wording round {round}: rewrite reverted\n{r}"));
restore(&opts.out, before)?;
break;
}
}
std::fs::write(opts.out.join("run.log"), log.join("\n") + "\n")?;
println!("content repo written to {}", opts.out.display());
Ok(())
}
const FORMAT: &str = "# Output format\n\nReturn files and nothing else, each as:\n\n<<<FILE relative/path.yaml>>>\n...complete file content...\n<<<END>>>\n\nNo prose, no code fences.";
fn parse_args() -> anyhow::Result<Opts> {
let mut args = std::env::args().skip(1);
if args.next().as_deref() != Some("generate") {
bail!("usage: portal-trainer generate --intake <file> --out <dir> [--lint question_lint] [--llm 'claude -p'] [--rounds 4] [--wording-rounds 2]");
}
let mut opts = Opts {
intake: PathBuf::new(),
out: PathBuf::new(),
lint: "question_lint".to_string(),
llm: "claude -p".to_string(),
rounds: 4,
wording_rounds: 2,
visitor: None,
};
while let Some(arg) = args.next() {
let mut value = || args.next().ok_or_else(|| anyhow!("{arg} needs a value"));
match arg.as_str() {
"--intake" => opts.intake = value()?.into(),
"--out" => opts.out = value()?.into(),
"--lint" => opts.lint = value()?,
"--llm" => opts.llm = value()?,
"--rounds" => opts.rounds = value()?.parse()?,
"--wording-rounds" => opts.wording_rounds = value()?.parse()?,
"--visitor-llm" => opts.visitor = Some(value()?),
other => bail!("unknown argument {other}"),
}
}
if opts.intake.as_os_str().is_empty() || opts.out.as_os_str().is_empty() {
bail!("--intake and --out are required");
}
Ok(opts)
}
/// Prompt on stdin, text on stdout.
/// Where `generate` keeps every prompt and reply (`<out>/llm/`). A
/// model that returns nothing usable has to be read, not guessed at.
static LLM_LOG: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
static LLM_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn llm(cmd: &str, prompt: &str) -> anyhow::Result<String> {
llm_env(cmd, prompt, &[])
}
/// As `llm`, with hints for the backend in its environment.
fn llm_env(cmd: &str, prompt: &str, env: &[(&str, &str)]) -> anyhow::Result<String> {
let reply = llm_with(cmd, prompt, env);
if let Some(dir) = LLM_LOG.get() {
let n = LLM_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
std::fs::write(dir.join(format!("{n:02}-prompt.md")), prompt).ok();
let text = match &reply {
Ok(text) => text.clone(),
Err(e) => format!("ERROR: {e}"),
};
std::fs::write(dir.join(format!("{n:02}-reply.md")), text).ok();
}
reply
}
/// As `llm`, with hints for the backend in its environment (`SEED`,
/// `FORMAT=json`, `TEMPERATURE`). A backend is free to ignore them.
pub(crate) fn llm_with(cmd: &str, prompt: &str, env: &[(&str, &str)]) -> anyhow::Result<String> {
let mut child = Command::new("sh")
.arg("-c")
.arg(cmd)
.envs(env.iter().copied())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.with_context(|| format!("starting {cmd:?}"))?;
let mut stdin = child.stdin.take().expect("piped");
let prompt = prompt.to_string();
// Written from a thread: a large prompt would otherwise deadlock
// against a child that starts writing before it finishes reading.
let writer = std::thread::spawn(move || stdin.write_all(prompt.as_bytes()));
let output = child.wait_with_output()?;
writer.join().ok();
if !output.status.success() {
bail!("{cmd:?} exited with {}", output.status);
}
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
fn lint(opts: &Opts, extra: &[String]) -> anyhow::Result<(bool, String)> {
let output = Command::new(&opts.lint)
.arg("--path")
.arg(opts.out.join("questions"))
.args(extra)
.output()
.with_context(|| format!("running {}", opts.lint))?;
let mut report = String::from_utf8_lossy(&output.stdout).into_owned();
report.push_str(&String::from_utf8_lossy(&output.stderr));
Ok((output.status.success(), report))
}
/// `<<<FILE path>>> ... <<<END>>>` blocks. Anything outside a block is
/// ignored, so a model that adds a sentence does no harm.
fn parse_files(text: &str) -> anyhow::Result<BTreeMap<String, String>> {
// Small models mangle the markers: `<<<END>>` with a bracket short,
// a stray `</think>`, the next `<<<FILE` glued onto the same line.
// So markers are found anywhere in a line, an END needs only its
// opening, and a new FILE closes whatever was open.
let mut files = BTreeMap::new();
let mut current: Option<(String, String)> = None;
let close = |current: &mut Option<(String, String)>, files: &mut BTreeMap<String, String>| {
if let Some((path, body)) = current.take() {
files.insert(path, body);
}
};
for line in text.lines() {
let mut rest = line;
loop {
let (file_at, end_at) = (rest.find("<<<FILE "), rest.find("<<<END"));
match (file_at, end_at) {
(Some(f), e) if e.is_none_or(|e| f < e) => {
close(&mut current, &mut files);
let after = &rest[f + "<<<FILE ".len()..];
let stop = after.find(">>>").unwrap_or(after.len());
current = Some((after[..stop].trim().to_string(), String::new()));
rest = after.get(stop + 3..).unwrap_or("");
}
(_, Some(e)) => {
close(&mut current, &mut files);
rest = &rest[e + "<<<END".len()..];
}
_ => break,
}
}
// A line that carried a marker carries no content.
if std::ptr::eq(rest, line) {
if let Some((_, body)) = current.as_mut() {
body.push_str(line);
body.push('\n');
}
}
}
close(&mut current, &mut files);
if files.is_empty() {
bail!("the model returned no <<<FILE ...>>> blocks");
}
Ok(files)
}
/// Model output is written to disk, so the path is checked, not
/// trusted: repo-relative, yaml, and only where content lives.
fn allowed(path: &str) -> bool {
let p = Path::new(path);
let plain = p.components().all(|c| matches!(c, std::path::Component::Normal(_)));
plain
&& p.extension().and_then(|e| e.to_str()) == Some("yaml")
&& (matches!(path, "aggregates.yaml" | "site.yaml") || path.starts_with("questions/"))
}
fn apply(out: &Path, files: BTreeMap<String, String>) -> anyhow::Result<()> {
for (path, body) in files {
if !allowed(&path) {
eprintln!("ignored {path:?}: outside what the generator may write");
continue;
}
let target = out.join(&path);
if body.trim() == "DELETE" {
std::fs::remove_file(&target).ok();
continue;
}
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(target, body)?;
}
Ok(())
}
fn content_files(out: &Path) -> anyhow::Result<Vec<PathBuf>> {
fn walk(dir: &Path, found: &mut Vec<PathBuf>) -> anyhow::Result<()> {
for entry in std::fs::read_dir(dir)? {
let path = entry?.path();
if path.is_dir() {
walk(&path, found)?;
} else if path.extension().and_then(|e| e.to_str()) == Some("yaml") {
found.push(path);
}
}
Ok(())
}
let mut found = Vec::new();
for name in ["aggregates.yaml", "site.yaml"] {
if out.join(name).exists() {
found.push(out.join(name));
}
}
walk(&out.join("questions"), &mut found)?;
found.sort();
Ok(found)
}
fn snapshot(out: &Path) -> anyhow::Result<Vec<(PathBuf, String)>> {
content_files(out)?
.into_iter()
.map(|p| Ok((p.clone(), std::fs::read_to_string(p)?)))
.collect()
}
fn restore(out: &Path, before: Vec<(PathBuf, String)>) -> anyhow::Result<()> {
for path in content_files(out)? {
std::fs::remove_file(path)?;
}
for (path, body) in before {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(path, body)?;
}
Ok(())
}
fn dump(out: &Path) -> anyhow::Result<String> {
let mut text = String::new();
for path in content_files(out)? {
let rel = path.strip_prefix(out).unwrap_or(&path).display().to_string();
text.push_str(&format!("<<<FILE {rel}>>>\n{}<<<END>>>\n\n", std::fs::read_to_string(&path)?));
}
Ok(text)
}
/// The answering side never sees `expect` or which need a persona has.
///
/// One call per task, so no visitor sees another visitor's situation
/// (a batch of eight personas over four headings is nearly a matching
/// puzzle, and a model solves it as one). The options are shuffled per
/// task, so a heading's place on the page cannot carry the answer, and
/// the call is seeded from the task id, so a rerun on the same site is
/// the same experiment.
///
/// With a content repo to read, the visitor sees each option as the
/// card portal renders: button, encouragement, sections with icon and
/// guidance, fields with placeholders. Headings-only tasks (`--skim`,
/// where the task's text is the heading itself) stay headings only.
pub(crate) fn answer_blind(cmd: &str, tasks: &str, repo: Option<&Path>, seed_offset: u64) -> anyhow::Result<String> {
let mut answers = String::new();
for line in tasks.lines().filter(|l| !l.trim().is_empty()) {
let task: serde_json::Value = serde_json::from_str(line)?;
let id = task["id"].as_str().unwrap_or_default();
let body = task["state"]["body"].as_str().unwrap_or_default();
let pick = &task["questions"]["pick"];
let instructions = pick["instructions"].as_str().unwrap_or_default();
let mut options: Vec<(&str, &str)> = pick["criteria"]
.as_object()
.into_iter()
.flatten()
.map(|(k, v)| (k.as_str(), v.as_str().unwrap_or_default()))
.collect();
let skim = options.iter().all(|(name, text)| text.is_empty() || text == name);
let page = if skim { None } else { repo.and_then(|r| rate::load_page(r, task["page"].as_str().unwrap_or("/"))) };
let seed = fnv(id).wrapping_add(seed_offset.wrapping_mul(0x9E37_79B9_7F4A_7C15) as _);
shuffle(&mut options, seed);
// Options are numbered and the answer is the number: with a
// whole card in view, a small model asked to copy a heading
// copied the page's description instead (measured: six of
// fourteen misroutes on one run were that), and no heading
// matched. A number cannot be a description.
let listed: Vec<String> = options
.iter()
.enumerate()
.map(|(i, (name, text))| {
let card = page
.as_ref()
.and_then(|p| p["alternatives"].as_array())
.and_then(|alts| alts.iter().find(|a| a["name"] == *name))
.map(|a| card::alternative(a, true));
let body = match card {
Some(card) => card.trim_end().trim_start_matches("- ").to_string(),
None if skim => name.to_string(),
None => format!("{name}: {text}"),
};
format!("{}. {body}", i + 1)
})
.collect();
let mut head = page.as_ref().map(card::page_head).unwrap_or_default();
// What the page says before it offers anything (the opener, the
// look around): read, not picked.
if let Some(context) = task["state"]["page"].as_str().filter(|c| !c.trim().is_empty()) {
head.push_str(&format!("The page first says:\n{context}\n\n"));
}
let prompt = format!(
"You are this person: {body}\n\n{instructions}\n{head}The page offers these options:\n\n{}\n\nWhich one do you pick? Judge only from your own situation and the wording in front of you. Give your honest confidence between 0 and 1; if two options fit you about equally, confidence is low.\nReply as JSON: {{\"choice\": <the option's number>, \"confidence\": 0.00}}",
listed.join("\n\n")
);
let reply = llm_env(cmd, &prompt, &[("FORMAT", "json"), ("SEED", &seed.to_string()), ("TEMPERATURE", "0.2")])?;
let parsed = simulate::first_object(&reply).unwrap_or(serde_json::Value::Null);
let names: Vec<&str> = options.iter().map(|(n, _)| *n).collect();
let raw = match &parsed["choice"] {
serde_json::Value::Number(n) => n.to_string(),
other => other.as_str().unwrap_or_default().to_string(),
};
// A number, or a heading for a model that wrote one anyway.
let choice = match raw.trim().trim_end_matches('.').parse::<usize>() {
Ok(n) if (1..=names.len()).contains(&n) => names[n - 1].to_string(),
_ => simulate::resolve_choice(&names, &raw),
};
let confidence = parsed["confidence"].as_f64().unwrap_or(0.0);
answers.push_str(&serde_json::to_string(&serde_json::json!({ "id": id, "choice": choice, "confidence": confidence }))?);
answers.push('\n');
}
Ok(answers)
}
/// FNV-1a over the task id: a seed that is the same on every run.
fn fnv(text: &str) -> u32 {
text.bytes().fold(0x811c_9dc5u32, |h, b| (h ^ u32::from(b)).wrapping_mul(0x0100_0193))
}
/// Fisher-Yates on a small xorshift, so the order is fixed by the seed.
fn shuffle<T>(items: &mut [T], seed: u32) {
let mut x = seed.max(1);
for i in (1..items.len()).rev() {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
items.swap(i, (x as usize) % (i + 1));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn files_are_parsed_from_blocks_and_prose_is_ignored() {
let files = parse_files("Sure!\n<<<FILE site.yaml>>>\ntitle: A\n<<<END>>>\nnoise\n<<<FILE questions/index.yaml>>>\nname: Q?\n<<<END>>>\n").unwrap();
assert_eq!(files["site.yaml"], "title: A\n");
assert_eq!(files.len(), 2);
assert!(parse_files("no blocks here").is_err());
}
#[test]
fn mangled_markers_from_a_small_model_still_separate_the_files() {
// Verbatim shape of a nemotron reply: a short END, a stray
// think tag, the next FILE glued on, and no END at the very end.
let files = parse_files(
"<<<FILE questions/desk/index.yaml>>>\nname: Desk?\n<<<END>></think><<<FILE questions/index.yaml>>>\nname: Hva trenger du?\n<<<FILE site.yaml>>>\ntitle: A\n",
)
.unwrap();
assert_eq!(files["questions/desk/index.yaml"], "name: Desk?\n");
assert_eq!(files["questions/index.yaml"], "name: Hva trenger du?\n");
assert_eq!(files["site.yaml"], "title: A\n");
}
#[test]
fn a_task_is_shuffled_the_same_way_every_time_and_differently_from_the_next() {
let mut a = ["w", "x", "y", "z"];
let mut b = a;
shuffle(&mut a, fnv("scaffolder@/"));
shuffle(&mut b, fnv("scaffolder@/"));
assert_eq!(a, b);
let mut c = ["w", "x", "y", "z"];
shuffle(&mut c, fnv("apprentice@/"));
assert_ne!(a, c);
let mut sorted = a;
sorted.sort();
assert_eq!(sorted, ["w", "x", "y", "z"]);
}
#[test]
fn only_content_paths_may_be_written() {
assert!(allowed("site.yaml"));
assert!(allowed("aggregates.yaml"));
assert!(allowed("questions/desk/_section.yaml"));
// The spec is frozen after phase one.
assert!(!allowed("needs.yaml"));
assert!(!allowed("../outside.yaml"));
assert!(!allowed("/etc/passwd.yaml"));
assert!(!allowed("questions/run.sh"));
assert!(!allowed(".gitea/workflows/deploy.yaml"));
}
}
+529
View File
@@ -0,0 +1,529 @@
//! From an intake, in plain words, to a `plan.yaml` a person can check.
//!
//! This is the one step where a model decides structure: which needs
//! the intake implies, the stages each goes through, who handles it,
//! what the form collects and how much that person will put up with.
//! Everything after it is deterministic (`build`), so this is where a
//! misreading of the business has to be caught, and it is caught by a
//! person reading the plan, not by a verifier. The model's YAML is
//! parsed and validated exactly as `build` would, and the errors go
//! back to it for another round; what passes is written verbatim, so
//! what the person reads is what the model wrote.
//!
//! Personas are never asked of this model: a persona written by the
//! same model that phrased the needs tests nothing. They come from a
//! person or a sector file, attached with `--personas`.
use anyhow::{anyhow, bail, Context};
use crate::trainer::build::Plan;
use crate::trainer::simulate::first_object;
const REFERENCE: &str = r#"# plan.yaml
A plan is a needs spec that also says what each form collects. A
builder turns it into a working site with no further decisions, so
every structural fact about the business has to be in it.
```yaml
business: <name>
language: en # the intake's language code
contact: { name: <who answers for the site>, email: <their email> }
about: >
What the business does, in its own words.
mail: { from: "<name> <post@their-domain>", reply_to: <their inbox> }
# who every mail the site sends comes from; required as soon
# as any need has `mails`
does: # the front door's first card: what the business does, one
- id: kebab-case # or two features, one role each, no button. Say it for the
for: <need id> # role the business exists for and the next one it serves.
text: what it does for them, in the intake's own words
shows: # what the site shows as it is: a live figure, the latest
- id: kebab-case # releases, what has been built; `resource` is portal's block
text: one line on what it is
resource: { public: true, source: { kind: url, url: https://... } }
doors: # a first question before the forms, only when the offers
- id: kebab-case # are more than one page holds (measured: four doors beat
who: who comes through it # ten offers on one page; six offers on one page beat doors)
groups: # groups with a label the public may see: the committees
- { id: traffic, label: Traffic, invited_by: [board] } # a person can ask to join (optional; label defaults to the id)
invites_by: [board] # groups whose desk may invite people into every desk
needs:
- id: kebab-case # ASCII only
who: the kind of person, in plain words, in the intake's language
wants: what they want from the business
door: <door id> # the door this public need sits behind; omit to put it on the front door
enters_as: <group> # ONLY for a role inside the business; omit for the public
lands_in: <bucket> # snake_case, ASCII
handled_by: <group> # the role that must see and move the record
stages: [open, <stage>, ..., <end>, <end>]
# EVERY stage the business said a case goes through, first to
# last, read off their own sentences one verb at a time: "they
# come in, we go and look, we send a quote, we win or lose it"
# is [open, surveyed, quoted, won, lost]. A pipeline is not an
# inbox: "answered" is rarely the real outcome.
done_when: [<end>, <end>] # every stage that counts as finished, good or bad
success: [<end>] # the finished stages that are a good outcome for the business
skippable: [<stage>] # stages a case may pass over (papers already complete)
requires: <one sentence> # what the person must ALREADY have or be for this to work:
# a membership, a reference number, the link from a mail, an
# account. Stated on the card above the form. Omit when there
# is none; never invent one
turned_down_from: [open, <stage>]
# the unfinished stages a case can still be turned down from;
# omit for every one. An applicant is declined before they
# start, not after - after, they depart
reached_from: { <stage>: [<stage>, ...] }
# where a stage is entered from, when the line does not say it.
# Two things need it and nothing else does: a case SENT BACK to
# a stage it was already past ("papers missing" again, after the
# hearing turned something up), and a GOOD ENDING partway along,
# where a case finishes well without walking to the end ("we
# changed our own decision", instead of passing it upwards).
# A stage named here is entered from exactly those stages and
# nowhere else, so it also says where a refusal may NOT come
# from. Omit unless the business described one of those two
moves_by: { <stage>: [<group>, ...] }
# only where someone other than handled_by moves a case INTO a
# stage: another group, or `submitter` (the person who sent the
# form; the form must then collect a required `email`)
watched_by: [<group>] # groups that see these cases and move nothing; `public` opens a
# read-only page of the bucket to everyone (contact details hidden)
mails: { open: submitter, <end>: submitter, <stage>: <address> }
# who hears when a case enters a stage: `submitter` (the form
# must then collect a required `email`) or one address. Tell the
# person on arrival and on every decision that is about them.
grants: { <stage>: <group> }
# a stage that makes the person a member of a group when their
# case arrives (an approval that IS membership); the form must
# then collect a required `name` and a required `email`
deadlines: { <stage>: { days: 30, to: <stage> } }
# a stage a clock moves on from when a case sits in it that long
# (a notice that expires, a hearing with no answer); only along
# a move the stages already allow
public_states: [<stage>] # with `public` in watched_by: the stages the public list shows
# (a noticeboard shows what is up, not what was taken down)
stages_text: { open: <words>, <stage>: <words> }
# each stage in the intake's language, where the ASCII id
# would read wrong to a person: "ikke_lost" is "ikke løst"
events: { open: applied } # ONLY when rebuilding a live site: the event names its
# aggregates.yaml already has, so its records keep replaying
attended_by: > # ONLY for a stage no desk button moves: the automation that does
what moves it, in a sentence
max_fields: 4 # decide this BEFORE writing collects, from what the intake
# says about the person; a budget that equals the form's size
# is counted, not decided, and is reported as such
# how many required fields THIS person will tolerate, from what
# the intake says about them: someone on a phone with gloves
# on gets 3, a first enquiry 4 to 6, a firm's paperwork 5 to 6
collects: # the form; name is snake_case ASCII, type one of
# text (default), email, tel, textarea, date, select, location
# (a pin on a map, stored as lat/lon/zoom; optional: true,
# since a map needs a browser that can draw one)
- { name: name }
- { name: phone, type: tel }
- { name: problem, type: textarea }
- { name: urgency, type: select, options: [This week, This month, No rush] }
- { name: can_do, type: select, multiple: true, options: [Drive, Cook, Carry] } # any number
- { name: committee, type: select, options_from: groups } # the labelled groups above
- { name: address, optional: true, private: true } # never on a public page
```
What a portal site can do - use what serves this business, leave the
rest. Each is one line in the plan, and the builder does the wiring:
- **Show, not only ask.** A bucket with `watched_by: [public]` becomes
a public list: its newest few records sit inline on the front door,
linked to the whole list, contact details pruned. What neighbours
reported and where it stands, which changes were approved, what is
on the noticeboard: a visitor who sees the place working trusts it,
and a person who reported something sees it being dealt with.
`public_states` shows only the stages worth showing.
- **Stay in dialogue.** `mails` tells the person at the stages that
are about them, and a reply to that mail comes back to the case as
a note. `moves_by: { <stage>: [submitter] }` gives them a move of
their own through their link: confirm, withdraw, say it is solved.
- **Let a decision do the work.** `grants` makes an approval into
membership: the person gets an account and a place in the group the
moment the case gets there; `deadlines` lets a stage end on its own
(a notice that expires, a request nobody took up); `invites_by` lets
a desk bring a person in without anyone touching an admin tool.
- **Let nothing wait unseen.** `escalate: { open: { days: 7, to: styret } }`
sends a case nobody has moved in a week up to another group's desk,
where it sits with the same buttons until someone finishes it; the
desk that had it keeps it too, and may send it up itself. A desk job,
not a mail: the group sees it when they sit down.
- **Let one record answer another.** A need `about` another need is
one answer per record of it, from that record's own row on the
public list: a neighbour saying "I can lend you that" to a notice, a
bid to a request. `mails: { open: owner }` sends the answer straight
to whoever posted the record, and the site keeps no queue - the
poster's inbox is the queue. The site never becomes a go-between.
- **Keep some things for members.** A need with `door` and `enters_as`
is offered to everyone on the door and taken on the group's page
behind sign-in, with name and address filled from the account: a
seat on a committee for members, a discount for customers. The
group is one a decision `grants`, so nobody has to be waved in.
- **Tell it two ways and find out.** `tones` lists tones of voice, one
storyline each: every word on the site is written once per tone, a
visitor reads one storyline throughout, and the site counts what
each brought in. Two is plenty; name them as a person would ("plain,
like a good notice on the door"; "warm, as a neighbour would put
it"). Leave it out to tell one story.
- **Let a person follow their own.** `followed_by: [customers]` gives
a group a desk that lists each member's own cases and nobody else's
(the ones carrying the address they sign in with), and the files on
them. With `grants` on the stage where a customer says yes, the
person who sent the case is the one who ends up able to follow it.
A `file` field takes drawings, photos, a report.
- **Carry a text word for word.** `documents` puts bylaws or terms on
a page of their own, one card per section, from a markdown file
beside the plan. Nothing rewords them.
- **Say who you are.** `values` are the business's own statements -
what it stands on, the experience behind it - carried word for word
into a "who we are" card on the front door. A need with `presents:
true` and `watched_by: [public]` puts its records in that card, all
of them, as cards: the people who work there, entered from inside
(`enters_as`), each with a `picture` field that shows as their
portrait.
- **Let people keep their own.** `one_per_person: true` on a need
entered from inside gives each signed-in person one record there:
their own, which the form opens with and which sending again
replaces - a card on the front page they edit themselves. A picture
left unchosen stays as it was.
- **Let finished things go.** `leaves_after: { <stage>: { minutes: 10 } }`
takes a record out of every list that long after it reaches that
stage (days, hours and minutes add up). A card taken off the front
page need not stand greyed out on the desk for ever; the history
keeps it.
- **Pause what you cannot take on.** `paused: true` on a need keeps
its card on the page, saying what the business does and that it is
not taking new ones right now, with no form and a button that does
not press. Take the line out to open again; the desk and every case
under way are untouched.
- **Show the work.** `slideshow` on the plan is portal's own block,
carried onto the front door as written: a strip of pictures under
the question, each with its caption.
- **Keep the people in portal.** `people: memberships` keeps every
group in portal itself: a desk invite is a place held until the
person signs in, a person is their phone number first, and any
sign-in provider that says who someone is will do (Vipps, for a
Norwegian association). Invite forms then ask for a phone number.
Without it, Kanidm makes an account per invite.
- **Answer for the pages as a group.** `contact: { name, email, group }`
makes the contact a group's inbox rather than a person: no account
is made for it, and every member of the group may suggest changes
to the pages from the page itself.
- **Make the choices real.** `groups` with labels, and a select with
`options_from: groups`, so a form offers exactly the committees or
teams that exist; `multiple: true` where a person can pick several.
- **Place things.** A `location` field puts a pin on a map (where the
hazard is, where the job is), when the site has maps.
- **Open with the business itself.** `does` says what it does for the
roles it exists for; `shows` puts its live content beside that.
Rules:
- One need per (kind of person, thing they want). Work inside the
business counts: a role recording or posting something is a need
with `enters_as`. The intake's "what slows us down" usually names one.
- Groups are the roles the intake names, as snake_case identifiers.
- The front door opens with `does` (at most two features, one role
each) and `shows`, then holds at most seven offers: doors plus needs
with no door. A door with no need behind it is refused; a door on a
need with `enters_as` is the way to the members' page. A role `does`
speaks for must have a move
of its own after sending (`moves_by` with `submitter`) or a public
view, or it is a spectator.
- Every need whose form collects an email should tell the person on
arrival and on the decisions about them (`mails`); the plan then
needs `mail: { from }`.
- Every feature on a card explains itself: a list says what one row is
and what its buttons do, a form says what to have ready. If an
alternative only works for someone who already has something, say so
in `requires` - a condition the reader meets only after filling the
form in has already cost them the filling in.
- Needs that land in the same bucket must have the same stages,
done_when, skippable, moves_by, watched_by and handled_by.
- Every required field is one the business will use to act on the
record. If the intake gives no reason to need it, make it optional or
leave it out. The required fields must not exceed max_fields.
- Only `select` lists `options`, and it must list them.
- Everything a person reads (who, wants, about, select options) is in
the intake's language. Everything a machine reads (ids, buckets,
groups, stages, field names) is plain ASCII: no æ, ø, å.
- Write no personas.
"#;
pub fn run(argv: &[String]) -> anyhow::Result<()> {
let value = |flag: &str| {
argv.iter()
.position(|a| a == flag)
.and_then(|i| argv.get(i + 1))
.cloned()
};
let usage = "usage: portal-trainer plan --intake <file> --out <dir> [--llm 'cmd'] [--personas <yaml with personas:>] [--rounds 4]";
let intake_path = value("--intake").ok_or_else(|| anyhow!(usage))?;
let out = std::path::PathBuf::from(value("--out").ok_or_else(|| anyhow!(usage))?);
let cmd = value("--llm").unwrap_or_else(|| "claude -p".to_string());
let rounds: usize = value("--rounds")
.map(|v| v.parse())
.transpose()?
.unwrap_or(4);
let intake =
std::fs::read_to_string(&intake_path).with_context(|| format!("reading {intake_path}"))?;
let mut personas: Option<serde_yaml::Value> = match value("--personas") {
Some(path) => {
let text = std::fs::read_to_string(&path).with_context(|| format!("reading {path}"))?;
let doc: serde_yaml::Value =
serde_yaml::from_str(&text).with_context(|| format!("parsing {path}"))?;
Some(doc.get("personas").cloned().ok_or_else(|| anyhow!("{path} has no `personas:`"))?)
}
None => None,
};
std::fs::create_dir_all(out.join("llm"))?;
let mut feedback = String::new();
// A structural finding the builder would only warn about (a role
// the opener speaks for with nothing to play) goes back to the
// model once; a second time it is the reader's, not another round.
let mut spectators_sent = false;
for round in 1..=rounds {
let prompt = format!(
"{REFERENCE}\n\n# Task\n\nA business filled in this intake. Write its plan.yaml: every need the intake implies, for the public and for each role inside the business, with the stages read off how the business says things progress, the form each need collects, and how much each person will tolerate.\n\n## Intake\n\n{intake}\n{feedback}\nReply with the YAML only, no prose, no code fences."
);
let reply = crate::trainer::llm_with(&cmd, &prompt, &[("TEMPERATURE", "0.2")])?;
std::fs::write(out.join(format!("llm/{round:02}-prompt.md")), &prompt)?;
std::fs::write(out.join(format!("llm/{round:02}-reply.md")), &reply)?;
let yaml = extract_yaml(&reply);
match check(&yaml) {
Ok(plan) if !plan.spectators().is_empty() && !spectators_sent && round < rounds => {
spectators_sent = true;
let findings = plan.spectators().join("\n- ");
eprintln!("plan round {round}: the plan parses, and a role the opener speaks for has no move after sending; asking once more");
feedback = format!("\n## Your last attempt parsed, with one thing to fix\n\n- {findings}\n\nGive each such need a move the person makes themselves (`moves_by: {{<stage>: [submitter, <group>]}}`, with a required `email` in its form) or `watched_by: [public]`, and return the whole plan again.\n\n```yaml\n{yaml}\n```\n");
continue;
}
Ok(plan) => {
let mut text = yaml.trim_end().to_string();
text.push('\n');
// The attached personas were written against someone
// else's need ids. The plan is final by now, so a model
// may map them to this plan's ids without its words
// reaching any page: it returns ids and nothing else,
// and an id not in the plan is ignored. What it leaves
// unmapped is listed for the reader.
if let Some(list) = personas.as_mut() {
let mapped = map_personas(&cmd, &plan, list)?;
if mapped > 0 {
eprintln!("plan round {round}: {mapped} persona(s) mapped to this plan's needs");
}
text.push_str("\n# Held out from every model that writes words.\n");
text.push_str(&serde_yaml::to_string(&serde_yaml::Mapping::from_iter([(
serde_yaml::Value::from("personas"),
list.clone(),
)]))?);
}
let whole: Plan =
serde_yaml::from_str(&text).context("the plan with its personas attached")?;
let strangers: Vec<String> = whole
.personas
.iter()
.filter(|p| {
!whole
.needs
.iter()
.any(|n| n.id == p["need"].as_str().unwrap_or_default())
})
.map(|p| {
format!(
"{} (need: {})",
p["id"].as_str().unwrap_or_default(),
p["need"].as_str().unwrap_or_default()
)
})
.collect();
std::fs::write(out.join("plan.yaml"), &text)?;
let groups: std::collections::BTreeSet<&str> = plan
.needs
.iter()
.flat_map(|n| [Some(n.handled_by.as_str()), n.enters_as.as_deref()])
.flatten()
.collect();
let buckets: std::collections::BTreeSet<&str> =
plan.needs.iter().map(|n| n.lands_in.as_str()).collect();
eprintln!("plan round {round}: {} need(s), {} group(s), {} bucket(s), {} persona(s) attached", plan.needs.len(), groups.len(), buckets.len(), whole.personas.len());
for n in &plan.needs {
eprintln!(
" {}: {} -> {} ({}), {} of {} field(s) required",
n.id,
n.stages.join(" -> "),
n.lands_in,
n.handled_by,
n.collects.iter().filter(|f| !f.optional).count(),
n.max_fields
);
}
if !strangers.is_empty() {
eprintln!(" {} persona(s) name a need this plan does not have; set their `need:` to one of the ids above before building:\n {}", strangers.len(), strangers.join("\n "));
}
// A budget that equals the form is the tell of a model
// that counted the form and called it the person's
// tolerance. One such need is a form that uses its
// room; most of them is the number being invented.
let tight: Vec<&str> = plan
.needs
.iter()
.filter(|n| n.collects.iter().filter(|f| !f.optional).count() == n.max_fields)
.map(|n| n.id.as_str())
.collect();
if tight.len() * 2 > plan.needs.len() && tight.len() > 1 {
eprintln!(" {} of {} need(s) have max_fields equal to their required fields ({}): check each against what the intake says about that person, not the form", tight.len(), plan.needs.len(), tight.join(", "));
}
println!(
"plan written to {}; read it before building from it",
out.join("plan.yaml").display()
);
return Ok(());
}
Err(e) => {
eprintln!("plan round {round}: {e}");
feedback = format!("\n## Your last attempt was refused\n\n{e}\n\nFix that and return the whole plan again.\n\n```yaml\n{yaml}\n```\n");
}
}
}
bail!(
"no plan passed in {rounds} round(s); the replies are in {}/llm/",
out.display()
)
}
/// Personas whose `need:` is not one of the plan's ids get one mapped
/// by a model that sees the plan's needs and the persona texts and
/// returns ids only. Returns how many were mapped; an id the plan does
/// not have, or a persona the model leaves out, stays as it was.
fn map_personas(cmd: &str, plan: &Plan, personas: &mut serde_yaml::Value) -> anyhow::Result<usize> {
let ids: Vec<&str> = plan.needs.iter().map(|n| n.id.as_str()).collect();
let Some(list) = personas.as_sequence_mut() else { return Ok(0) };
let strangers: Vec<(String, String)> = list
.iter()
.filter(|p| !ids.contains(&p["need"].as_str().unwrap_or_default()))
.map(|p| (p["id"].as_str().unwrap_or_default().to_string(), p["text"].as_str().unwrap_or_default().to_string()))
.filter(|(id, _)| !id.is_empty())
.collect();
if strangers.is_empty() {
return Ok(0);
}
let needs: Vec<String> = plan.needs.iter().map(|n| format!("- {}: {} - wants {}", n.id, n.who, n.wants)).collect();
let people: Vec<String> = strangers.iter().map(|(id, text)| format!("- {id}: {text}")).collect();
let prompt = format!(
"A site has these needs, one per kind of visitor:\n{}\n\nThese people arrive at it:\n{}\n\nFor each person, which need is theirs? Reply with a JSON object mapping each person's id to one need id from the list, and nothing else. Leave a person out if no need fits.",
needs.join("\n"),
people.join("\n")
);
let reply = crate::trainer::llm_with(cmd, &prompt, &[("FORMAT", "json"), ("TEMPERATURE", "0.0")])?;
let Some(mapping) = first_object(&reply) else { return Ok(0) };
let mut mapped = 0;
for persona in list.iter_mut() {
let id = persona["id"].as_str().unwrap_or_default().to_string();
if let Some(need) = mapping.get(&id).and_then(|v| v.as_str()) {
if ids.contains(&need) && !ids.contains(&persona["need"].as_str().unwrap_or_default()) {
persona["need"] = serde_yaml::Value::from(need);
mapped += 1;
}
}
}
Ok(mapped)
}
/// Parsed and validated exactly as `build` will.
fn check(yaml: &str) -> anyhow::Result<Plan> {
let plan: Plan =
serde_yaml::from_str(yaml).map_err(|e| anyhow!("does not parse as a plan: {e}"))?;
if !plan.personas.is_empty() {
bail!("contains personas; write none");
}
if plan.needs.is_empty() {
bail!("has no needs");
}
plan.validate()?;
Ok(plan)
}
/// The YAML in a reply: inside code fences if the model used them,
/// otherwise from the first top-level key on. A stray JSON object
/// (some models answer `{"business": ...}`) is turned into YAML.
fn extract_yaml(reply: &str) -> String {
let text = reply.trim();
if let Some(start) = text.find("```") {
let after = &text[start + 3..];
let after = after.find('\n').map_or(after, |i| &after[i + 1..]);
let body = after.find("```").map_or(after, |i| &after[..i]);
return body.to_string();
}
if text.starts_with('{') {
if let Some(v) = first_object(text) {
return serde_yaml::to_string(&v).unwrap_or_default();
}
}
let start = text
.lines()
.position(|l| {
l.starts_with("business:") || l.starts_with("needs:") || l.starts_with("contact:")
})
.unwrap_or(0);
text.lines().skip(start).collect::<Vec<_>>().join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
const GOOD: &str = "business: B\ncontact: { name: I, email: i@b.example }\nneeds:\n - id: enquiry\n who: an owner\n wants: a look\n lands_in: enquiries\n handled_by: project_managers\n stages: [open, quoted, won, lost]\n done_when: [won, lost]\n success: [won]\n max_fields: 3\n collects:\n - { name: name }\n - { name: phone, type: tel }\n";
#[test]
fn yaml_is_taken_from_fences_prose_or_json() {
assert_eq!(
extract_yaml(&format!("Here you go:\n```yaml\n{GOOD}```\nDone.")),
GOOD
);
assert_eq!(
extract_yaml(&format!("Sure, the plan:\n\n{GOOD}")),
GOOD.trim_end()
);
let from_json = extract_yaml("{\"business\": \"B\", \"needs\": []}");
assert!(from_json.contains("business: B"));
}
#[test]
fn a_plan_is_held_to_the_same_checks_as_build() {
assert!(check(GOOD).is_ok());
assert!(
check("business: B\ncontact: { name: I, email: i@b.example }\nneeds: []\n")
.unwrap_err()
.to_string()
.contains("no needs")
);
assert!(check(&GOOD.replace("max_fields: 3", "max_fields: 1"))
.unwrap_err()
.to_string()
.contains("tolerate 1"));
assert!(check(&format!(
"{GOOD}personas:\n - {{ id: p, need: enquiry, text: hi }}\n"
))
.unwrap_err()
.to_string()
.contains("personas"));
assert!(check(&GOOD.replace(
"lands_in: enquiries",
"lands_in: henvendelser\n extra: 1"
))
.unwrap_err()
.to_string()
.contains("does not parse"));
}
}
+635
View File
@@ -0,0 +1,635 @@
//! Understanding, readability, friendliness: three scores to iterate
//! wording against, each measured the way that keeps it from sticking
//! at its maximum.
//!
//! - **Readability** is counted, not judged: LIX, sentence length plus
//! the share of words over six letters, over the page's prose only -
//! the question, the descriptions and the followup - never headings
//! or field labels, which are not sentences and would drag the score
//! down to "very easy" whatever the prose says. Below 30 reads very
//! easily, 30-40 easily, 40-50 takes effort, above 50 is official
//! prose.
//! - **Understanding** is three yes-or-no questions put to each persona
//! about the page in front of them: which option is theirs, what the
//! form will ask, and what happens after sending. The last needs the
//! followup page, which `rate` reads from the content repo (`--repo`)
//! because the sim export stops at the form. `rate` also puts all
//! three to a deliberately gutted twin of the page (headings replaced
//! by "Option 1", descriptions, the form line and the followup
//! removed). An instrument that still says yes to the twin is not
//! measuring the page, and `rate` says so, per question. Every page
//! on a need's path is rated: behind a door, "which" is decided on
//! the door page and the form's page carries "asked" and "next".
//! - **Friendliness** is a preference between two versions, never an
//! absolute mark: `prefer` shows each persona both versions in both
//! orders; a pick that flips with the order counts as no preference.
use std::collections::BTreeMap;
use std::path::Path;
use anyhow::{anyhow, Context};
use serde_json::{json, Value};
use crate::trainer::card;
use crate::trainer::simulate::ask;
fn flag(argv: &[String], name: &str) -> Option<String> {
argv.iter().position(|a| a == name).and_then(|i| argv.get(i + 1)).cloned()
}
fn load(path: &str) -> anyhow::Result<Value> {
Ok(serde_json::from_str(&std::fs::read_to_string(path).with_context(|| format!("reading {path}"))?)?)
}
/// LIX = words per sentence + 100 * long words / words.
pub fn lix(text: &str) -> f64 {
let words: Vec<&str> = text
.split(|c: char| !(c.is_alphanumeric() || c == '\'' || c == '-'))
.filter(|w| w.chars().any(char::is_alphabetic))
.collect();
if words.is_empty() {
return 0.0;
}
let sentences = text.split(['.', '!', '?', ':', '\n']).filter(|s| s.chars().any(char::is_alphabetic)).count().max(1);
let long = words.iter().filter(|w| w.chars().count() > 6).count();
words.len() as f64 / sentences as f64 + 100.0 * long as f64 / words.len() as f64
}
pub fn lix_band(score: f64) -> &'static str {
match score {
s if s < 30.0 => "very easy",
s if s < 40.0 => "easy",
s if s < 50.0 => "takes effort",
_ => "official prose",
}
}
/// The page as the visitor meets it: the question, every alternative,
/// the form behind the one that serves them, and the page they land on
/// after sending, when the repo is there to read it from.
fn page_text(step: &Value, page: Option<&Value>, followup: Option<&Value>, gutted: bool) -> String {
let mut text = match (gutted, page) {
(false, Some(p)) => card::page_head(p),
_ => format!("{}\n", step["question"].as_str().unwrap_or_default()),
};
// The cards that lead nowhere (the opener, the look around) are
// read before the options; the gutted twin loses them too.
if let Some(context) = step["context"].as_str().filter(|c| !c.trim().is_empty() && !gutted) {
text.push_str(&format!("\n{context}\n"));
}
for (i, option) in step["options"].as_array().into_iter().flatten().enumerate() {
if gutted {
text.push_str(&format!("\n- Option {}\n", i + 1));
continue;
}
// The whole card when the repo is there to read it from;
// heading and description otherwise.
let card = page
.and_then(|p| p["alternatives"].as_array())
.and_then(|alts| alts.iter().find(|a| a["name"] == option["name"]))
.map(|a| card::alternative(a, true));
match card {
Some(c) => text.push_str(&format!("\n{c}")),
None => text.push_str(&format!(
"\n- {}\n {}\n",
option["name"].as_str().unwrap_or_default(),
option["description"].as_str().unwrap_or_default()
)),
}
}
if page.is_some() && !gutted {
// The cards carry their own "Asks for" lines.
return finish_page_text(text, followup);
}
// The twin has no form line at all: "Field 1, Field 2" still
// tells a reader how many things they will be asked, and a model
// answers "can you tell what you will be asked" with yes to that
// (measured: 2 of 2 on every need).
let fields: Vec<&str> = step["fields"].as_array().into_iter().flatten().filter_map(|f| f["label"].as_str()).collect();
if !gutted && !fields.is_empty() {
text.push_str(&format!(
"\nThe form under \"{}\" asks for: {}.\n",
step["alternative"].as_str().unwrap_or_default(),
fields.join(", ")
));
}
if gutted {
return text;
}
finish_page_text(text, followup)
}
fn finish_page_text(mut text: String, followup: Option<&Value>) -> String {
if let Some(next) = followup {
text.push_str(&format!("\nAfter you send it, the next page says:\n{}\n", next["name"].as_str().unwrap_or_default()));
if let Some(d) = next["description"].as_str().filter(|d| !d.trim().is_empty()) {
text.push_str(&format!("{}\n", d.trim()));
}
for alt in next["alternatives"].as_array().into_iter().flatten() {
let d = alt["description"].as_str().unwrap_or_default().trim();
text.push_str(&format!("- {}{}{}\n", alt["name"].as_str().unwrap_or_default(), if d.is_empty() { "" } else { ": " }, d));
}
}
text
}
/// The running text a reader has to parse: the question, each
/// description, and the followup. Headings and labels are left out.
fn prose_text(step: &Value, followup: Option<&Value>) -> String {
let mut prose = vec![step["question"].as_str().unwrap_or_default().to_string()];
prose.extend(step["options"].as_array().into_iter().flatten().filter_map(|o| o["description"].as_str()).map(str::to_string));
if let Some(next) = followup {
prose.extend(next["description"].as_str().map(str::to_string));
prose.extend(next["alternatives"].as_array().into_iter().flatten().filter_map(|a| a["description"].as_str()).map(str::to_string));
}
prose.into_iter().filter(|p| !p.trim().is_empty()).collect::<Vec<_>>().join("\n")
}
/// The page a visitor lands on after the step's alternative: read from
/// the content repo, since the sim export stops at the form. `None`
/// when there is no repo, no `action`, or the page is not there.
fn followup_page(repo: Option<&Path>, step: &Value) -> Option<Value> {
let repo = repo?;
let page = load_page(repo, step["page"].as_str()?)?;
let alternative = step["alternative"].as_str()?;
let action = page["alternatives"].as_array()?.iter().find(|a| a["name"] == alternative)?["action"].as_str()?;
load_page(repo, action)
}
/// Every desk's buttons per bucket, from the simulation model:
/// (page, group, bucket, [(from, to, label)]). A desk with one button
/// for a bucket has nothing to confuse and is left out.
fn desk_buttons(model: &Value) -> Vec<(String, String, String, Vec<(String, String, String)>)> {
let mut out = Vec::new();
for (bucket, spec) in model["buckets"].as_object().into_iter().flatten() {
for desk in spec["desks"].as_array().into_iter().flatten() {
let moves: Vec<(String, String, String)> = desk["moves"]
.as_array()
.into_iter()
.flatten()
.map(|m| (s(&m["from"]), s(&m["to"]), s(&m["label"])))
.filter(|(_, _, l)| !l.is_empty())
.collect();
if moves.len() >= 2 {
out.push((s(&desk["page"]), s(&desk["group"]), bucket.clone(), moves));
}
}
}
out.sort();
out
}
fn s(v: &Value) -> String {
v.as_str().unwrap_or_default().to_string()
}
/// A worker on the desk, told what just happened to a case, picks
/// the button for it. The outcome is put in plain words from the
/// state's own name, never from the label, and the buttons are listed
/// in a seeded shuffle.
fn button_pick(cmd: &str, group: &str, bucket: &str, from: &str, to: &str, labels: &[&str], seed: usize, words: &Value) -> anyhow::Result<String> {
// The state in the plan's own words when the spec carries them,
// else the id made readable.
let plain = |id: &str| words[id].as_str().map(str::to_string).unwrap_or_else(|| id.replace(['_', '-'], " "));
let mut order: Vec<&str> = labels.to_vec();
// A fixed rotation per move: the right answer is not always first.
let by = seed % order.len().max(1);
order.rotate_left(by);
let listed: Vec<String> = order.iter().enumerate().map(|(i, l)| format!("{}. {l}", i + 1)).collect();
let prompt = format!(
"You work on the {} desk of a small organisation. A case in \"{}\" was \"{}\" and has just become \"{}\". The desk shows these buttons for it:\n\n{}\n\nWhich button records what just happened? Reply as JSON: {{\"choice\": <the button's number>}}",
plain(group),
plain(bucket),
plain(from),
plain(to),
listed.join("\n")
);
let reply = ask(cmd, &prompt, &seed.to_string())?;
let n = reply["choice"].as_u64().unwrap_or(0) as usize;
Ok(order.get(n.wrapping_sub(1)).map(|l| l.to_string()).unwrap_or_default())
}
/// Every `mail:` on a state in the repo's aggregates.yaml, as
/// (`bucket:state`, subject, body) with the `{placeholders}` taken
/// out, so they read as the person will read them.
pub(crate) fn mail_texts(repo: &Path) -> Option<Vec<(String, String, String)>> {
let raw = std::fs::read_to_string(repo.join("aggregates.yaml")).ok()?;
let doc: Value = serde_yaml::from_str(&raw).ok()?;
let strip = |s: &str| {
let mut out = String::new();
let mut skip = false;
for c in s.chars() {
match c {
'{' => skip = true,
'}' => skip = false,
_ if !skip => out.push(c),
_ => {}
}
}
out.split_whitespace().collect::<Vec<_>>().join(" ")
};
Some(raw_mails(repo, &doc).into_iter().map(|(name, subject, body)| (name, strip(&subject), strip(&body))).collect())
}
/// Every mail the site sends, as written: the state mails in
/// aggregates.yaml, then the invite mail in site.yaml - onboarding is
/// a mail too, and the first one a new member reads.
fn raw_mails(repo: &Path, aggregates: &Value) -> Vec<(String, String, String)> {
let mut out = Vec::new();
for aggregate in aggregates["aggregates"].as_array().into_iter().flatten() {
let bucket = aggregate["bucket"].as_str().unwrap_or_default();
for (state, spec) in aggregate["states"].as_object().into_iter().flatten() {
if let Some(mail) = spec.get("mail") {
out.push((
format!("{bucket}:{state}"),
mail["subject"].as_str().unwrap_or_default().to_string(),
mail["body"].as_str().unwrap_or_default().to_string(),
));
}
}
}
let site: Value = std::fs::read_to_string(repo.join("site.yaml")).ok().and_then(|t| serde_yaml::from_str(&t).ok()).unwrap_or(Value::Null);
let invite = &site["mail"]["invite"];
if invite.is_object() {
out.push(("invite".to_string(), invite["subject"].as_str().unwrap_or_default().to_string(), invite["body"].as_str().unwrap_or_default().to_string()));
}
out
}
/// A mail as it arrives: the placeholders filled with plausible values,
/// so a reader meets a link where the link will be, not a blank.
fn as_received(template: &str, site_name: &str) -> String {
let mut out = String::new();
let mut rest = template;
while let Some(i) = rest.find('{') {
out.push_str(&rest[..i]);
let after = &rest[i + 1..];
match after.find('}') {
Some(j) if after[..j].chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.') && j > 0 => {
out.push_str(&match &after[..j] {
"site" => "https://example.site".to_string(),
"chain" => "8f3a1c".to_string(),
"link" => "https://id.example.site/reset/8f3a1c".to_string(),
"site_name" => site_name.to_string(),
"expires" => "2026-10-05 12:00 UTC".to_string(),
key => format!("[{}]", key.replace('_', " ")),
});
rest = &after[j + 1..];
}
_ => {
out.push('{');
rest = after;
}
}
}
out.push_str(rest);
out
}
const MAIL_QUESTIONS: [(&str, &str); 3] = [
("happened", "Do you know, from this mail alone, what has happened and to what?"),
("now", "Do you know what, if anything, you can or must do now, and how?"),
("who", "Do you know who sent it, and how you would answer them?"),
];
/// Three yes-or-no questions on one mail, from the person it is for.
fn mail_understanding(cmd: &str, reader: &str, subject: &str, body: &str, seed: usize) -> anyhow::Result<[bool; 3]> {
let prompt = format!(
"You are {reader}. This mail has just arrived:\n---\nSubject: {subject}\n\n{body}\n---\n\nAnswer three questions as yourself. Say yes only when the mail itself tells you; if you would be guessing, say no.\n{}\nReply as JSON: {{\"happened\": true or false, \"now\": true or false, \"who\": true or false}}",
MAIL_QUESTIONS.iter().map(|(k, q)| format!("- {k}: {q}")).collect::<Vec<_>>().join("\n")
);
let reply = ask(cmd, &prompt, &seed.to_string())?;
Ok([reply["happened"] == true, reply["now"] == true, reply["who"] == true])
}
/// `/` is `questions/index.yaml`; `/a/b` is `questions/a/b.yaml` or
/// `questions/a/b/index.yaml`.
pub(crate) fn load_page(repo: &Path, route: &str) -> Option<Value> {
let rel = route.trim_matches('/');
let candidates = if rel.is_empty() {
vec![repo.join("questions/index.yaml")]
} else {
vec![repo.join(format!("questions/{rel}.yaml")), repo.join(format!("questions/{rel}/index.yaml"))]
};
let text = candidates.iter().find_map(|p| std::fs::read_to_string(p).ok())?;
serde_yaml::from_str(&text).ok()
}
/// What one page may ask of one person before it should be split into
/// a further question, or the fields moved to a later stage of the
/// case where they are actually needed. Complexity belongs in the
/// number of steps and states, not in the weight of any one page.
const MAX_OPTIONS: usize = 5;
const MAX_REQUIRED: usize = 5;
/// (alternatives offered, required fields in the form that serves them)
fn page_load(step: &Value) -> (usize, usize) {
(
step["options"].as_array().map_or(0, Vec::len),
step["fields"].as_array().into_iter().flatten().filter(|f| f["optional"] != true).count(),
)
}
const QUESTIONS: [(&str, &str); 4] = [
("which", "Is it clear from the page which option is meant for someone in your situation?"),
("where", "Do you know where you are on this site, who this option is for, and what pressing its button will do?"),
("asked", "Can you tell from the page what you will be asked to provide?"),
("next", "Does the page tell you what happens after you send it, or who will read it?"),
];
const N: usize = QUESTIONS.len();
fn understanding(cmd: &str, who: &str, page: &str, seed: usize) -> anyhow::Result<[bool; N]> {
let prompt = format!(
"You are this person: {who}\n\nThis is the whole of a web page you have just opened:\n---\n{page}---\n\nAnswer four questions about it as yourself. Say yes only when the page text itself gives you that; if you would be guessing, say no.\n{}\nReply as JSON: {{\"which\": true or false, \"where\": true or false, \"asked\": true or false, \"next\": true or false}}",
QUESTIONS.iter().map(|(k, q)| format!("- {k}: {q}")).collect::<Vec<_>>().join("\n")
);
let reply = ask(cmd, &prompt, &seed.to_string())?;
Ok([reply["which"] == true, reply["where"] == true, reply["asked"] == true, reply["next"] == true])
}
pub fn rate(argv: &[String]) -> anyhow::Result<()> {
let usage = "usage: portal-trainer rate --model <model.json> --out <dir> [--repo <content dir>] [--llm 'cmd']";
let model = load(&flag(argv, "--model").ok_or_else(|| anyhow!(usage))?)?;
let out = std::path::PathBuf::from(flag(argv, "--out").ok_or_else(|| anyhow!(usage))?);
let repo = flag(argv, "--repo").map(std::path::PathBuf::from);
let cmd = flag(argv, "--llm").unwrap_or_else(|| "claude -p".to_string());
std::fs::create_dir_all(&out)?;
if repo.is_none() {
eprintln!("rate: no --repo, so no followup page is shown and \"next\" is not measured");
}
let mut report = BTreeMap::new();
// The desks: the inside of the business reads button labels and
// nothing else, so each desk is scored on whether a worker told
// what has just happened to a case picks the right button among
// that desk's buttons for the bucket.
let desks = desk_buttons(&model);
if !desks.is_empty() {
println!("{:<20} {:<24} {:>8} {}", "desk", "bucket", "buttons", "mistaken for");
for (page, group, bucket, moves) in &desks {
// A desk row shows only the buttons that start from the
// row's state, so those are the ones the worker chooses
// among; a state with one button has nothing to confuse.
let mut right = 0;
let mut asked = 0;
let mut mistaken = Vec::new();
for (i, (from, to, label)) in moves.iter().enumerate() {
let labels: Vec<&str> = moves.iter().filter(|(f, _, _)| f == from).map(|(_, _, l)| l.as_str()).collect();
if labels.len() < 2 {
continue;
}
asked += 1;
let picked = button_pick(&cmd, group, bucket, from, to, &labels, i, &model["buckets"][bucket]["words"])?;
if picked == *label {
right += 1;
} else {
mistaken.push(format!("{from}>{to} as {picked:?}"));
}
}
if asked == 0 {
continue;
}
println!("{:<20} {:<24} {:>3} of {:<2} {}", page, bucket, right, asked, mistaken.join("; "));
report.insert(format!("desk {page} {bucket}"), json!({ "right": right, "of": asked, "mistaken": mistaken }));
}
println!();
}
// The mails first, when the repo carries any: a person reads a
// mail alone, with no card around it, so its prose is rated on
// its own - LIX and length.
// Then the three questions a person asks of any mail - what
// happened, what now, who is this - each also put to a gutted twin
// that says only that there is news. A yes the twin also gets is
// the reader agreeing with anything.
if let Some(mails) = repo.as_deref().and_then(mail_texts) {
if !mails.is_empty() {
let dir = repo.as_deref().unwrap_or(Path::new("."));
let site: Value = std::fs::read_to_string(dir.join("site.yaml")).ok().and_then(|t| serde_yaml::from_str(&t).ok()).unwrap_or(Value::Null);
let site_name = site["title"].as_str().unwrap_or("the site").to_string();
let aggregates: Value = std::fs::read_to_string(dir.join("aggregates.yaml")).ok().and_then(|t| serde_yaml::from_str(&t).ok()).unwrap_or(Value::Null);
let raw = raw_mails(dir, &aggregates);
println!("{:<34} {:>5} {:<14} {:>5} {:>8} {:>5} {:>5} {:<16}", "mail", "LIX", "", "words", "happened", "now", "who", "gutted twin says");
for (i, ((name, subject, body), (_, raw_subject, raw_body))) in mails.iter().zip(&raw).enumerate() {
let text = format!("{subject}. {body}");
let score = lix(&text);
let reader = if name == "invite" {
format!("someone a member of {site_name} has just brought in to help run it; you did not ask for this mail")
} else {
format!("someone who sent a form to {site_name} some time ago")
};
let (subject_in, body_in) = (as_received(raw_subject, &site_name), as_received(raw_body, &site_name));
let got = mail_understanding(&cmd, &reader, &subject_in, &body_in, i)?;
let twin = mail_understanding(&cmd, &reader, "News", "There is news.", i)?;
let yn = |b: bool| if b { "yes" } else { "no" };
let failed: Vec<&str> = MAIL_QUESTIONS.iter().zip(twin).filter(|(_, t)| *t).map(|((k, _), _)| *k).collect();
println!(
"{:<34} {:>5.0} {:<14} {:>5} {:>8} {:>5} {:>5} {:<16}",
name, score, lix_band(score), text.split_whitespace().count(), yn(got[0]), yn(got[1]), yn(got[2]),
if failed.is_empty() { "ok".to_string() } else { format!("FAILED: {}", failed.join(", ")) }
);
report.insert(format!("mail {name}"), json!({
"lix": score, "words": text.split_whitespace().count(),
"understanding": { "happened": got[0], "now": got[1], "who": got[2] },
"control_ok": failed.is_empty(),
}));
}
println!();
}
}
println!("{:<28} {:>6} {:<14} {:>8} {:>8} {:>8} {:>8} {:<22} {:<22}", "need", "LIX", "", "which", "where", "asked", "next", "gutted twin says", "page load");
for need in model["needs"].as_array().into_iter().flatten() {
let id = need["id"].as_str().unwrap_or_default();
let steps = need["steps"].as_array().cloned().unwrap_or_default();
let personas: Vec<&Value> = model["personas"].as_array().into_iter().flatten().filter(|p| p["need"] == id).collect();
if personas.is_empty() {
continue;
}
// Every page on the path is rated. The followup follows only
// the last page's alternative: on a door page, what the
// alternative leads to is the next page, not what happens
// after sending.
let mut pages = Vec::new();
for (i, step) in steps.iter().enumerate() {
let followup = if i + 1 == steps.len() { followup_page(repo.as_deref(), step) } else { None };
let page = repo.as_deref().and_then(|r| load_page(r, step["page"].as_str().unwrap_or("/")));
let row = if steps.len() > 1 { format!("{id} @{}", step["page"].as_str().unwrap_or_default()) } else { id.to_string() };
let readability = lix(&prose_text(step, followup.as_ref()));
let (mut yes, mut control) = ([0usize; N], [0usize; N]);
for (i, persona) in personas.iter().enumerate() {
let who = persona["text"].as_str().unwrap_or_default();
for (tally, gutted) in [(&mut yes, false), (&mut control, true)] {
let answers = understanding(&cmd, who, &page_text(step, page.as_ref(), followup.as_ref(), gutted), i)?;
for (slot, answer) in tally.iter_mut().zip(answers) {
*slot += answer as usize;
}
}
}
let n = personas.len();
let measured = |k: usize| k != 3 || followup.is_some();
let share = |k: usize| if measured(k) { format!("{}/{n}", yes[k]) } else { "-".to_string() };
// The twin has no headings, no descriptions, no cards and no
// followup: every question must collapse on it, or that
// question is agreeing with anything.
let control_ok: Vec<bool> = (0..N).map(|k| !measured(k) || control[k] * 2 < n.max(1)).collect();
let failed: Vec<&str> = QUESTIONS.iter().zip(&control_ok).filter(|(_, ok)| !**ok).map(|((k, _), _)| *k).collect();
let (options, required) = page_load(step);
println!(
"{:<28} {:>6.0} {:<14} {:>8} {:>8} {:>8} {:>8} {:<22} {:<22}",
row,
readability,
lix_band(readability),
share(0),
share(1),
share(2),
share(3),
format!(
"{}/{}/{}/{} {}",
control[0],
control[1],
control[2],
if measured(3) { control[3].to_string() } else { "-".to_string() },
if failed.is_empty() { "ok".to_string() } else { format!("FAILED: {}", failed.join(", ")) }
),
format!(
"{options} options, {required} required{}",
if options > MAX_OPTIONS || required > MAX_REQUIRED { " - SPLIT" } else { "" }
),
);
pages.push(json!({
"page": step["page"], "lix": readability, "personas": n,
"options": options, "required_fields": required,
"overloaded": options > MAX_OPTIONS || required > MAX_REQUIRED,
"followup_shown": followup.is_some(),
"understanding": {"which": yes[0], "where": yes[1], "asked": yes[2], "next": if measured(3) { json!(yes[3]) } else { Value::Null }},
"control": {"which": control[0], "where": control[1], "asked": control[2], "next": if measured(3) { json!(control[3]) } else { Value::Null }},
"control_ok": failed.is_empty(),
}));
}
report.insert(id.to_string(), json!({ "steps": pages.len(), "pages": pages }));
}
std::fs::write(out.join("rate.json"), serde_json::to_string_pretty(&report)?)?;
Ok(())
}
pub fn prefer(argv: &[String]) -> anyhow::Result<()> {
let usage = "usage: portal-trainer prefer --a <model-a.json> --b <model-b.json> [--llm 'cmd']";
let a = load(&flag(argv, "--a").ok_or_else(|| anyhow!(usage))?)?;
let b = load(&flag(argv, "--b").ok_or_else(|| anyhow!(usage))?)?;
let cmd = flag(argv, "--llm").unwrap_or_else(|| "claude -p".to_string());
println!("{:<28} {:>5} {:>5} {:>14} {:>5} {:>5} {:>14} {:>9}", "need", "A", "B", "no preference", "A", "B", "no preference", "LIX A->B");
println!("{:<28} {:^26} {:^26}", "", "friendlier", "clearer");
for need_a in a["needs"].as_array().into_iter().flatten() {
let id = need_a["id"].as_str().unwrap_or_default();
let Some(need_b) = b["needs"].as_array().into_iter().flatten().find(|n| n["id"] == id) else { continue };
let (Some(step_a), Some(step_b)) = (need_a["steps"].as_array().and_then(|s| s.first()), need_b["steps"].as_array().and_then(|s| s.first())) else { continue };
let (text_a, text_b) = (page_text(step_a, None, None, false), page_text(step_b, None, None, false));
if text_a == text_b {
continue;
}
// [friendlier, clearer] x [A, B, none]
let mut wins = [[0usize; 3]; 2];
for (i, persona) in a["personas"].as_array().into_iter().flatten().filter(|p| p["need"] == id).enumerate() {
let who = persona["text"].as_str().unwrap_or_default();
let mut picks: [[&str; 2]; 2] = [["", ""], ["", ""]];
for (order, (first, second)) in [(&text_a, &text_b), (&text_b, &text_a)].into_iter().enumerate() {
let prompt = format!(
"You are this person: {who}\n\nTwo versions of the same web page. They lead to the same thing; only the wording differs.\n\n=== VERSION 1 ===\n{first}\n=== VERSION 2 ===\n{second}\n\nAs yourself: which version makes you feel more welcome and at ease, and which one makes it clearer what to do?\nReply as JSON: {{\"friendlier\": 1 or 2, \"clearer\": 1 or 2}}"
);
let reply = ask(&cmd, &prompt, &(i * 2 + order).to_string())?;
for (k, key) in ["friendlier", "clearer"].iter().enumerate() {
let first_won = reply[key] == 1;
// In the second order, version 1 is B.
picks[k][order] = if first_won == (order == 0) { "A" } else { "B" };
}
}
for k in 0..2 {
let slot = match picks[k] {
["A", "A"] => 0,
["B", "B"] => 1,
_ => 2,
};
wins[k][slot] += 1;
}
}
println!(
"{:<28} {:>5} {:>5} {:>14} {:>5} {:>5} {:>14} {:>9}",
id, wins[0][0], wins[0][1], wins[0][2], wins[1][0], wins[1][1], wins[1][2],
format!("{:.0}->{:.0}", lix(&text_a), lix(&text_b))
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lix_separates_plain_words_from_official_prose() {
let plain = "Get someone to look at a building. We come and see it. Then we tell you what it takes.";
let official = "Submission of documentation regarding rehabilitation requirements necessitates comprehensive structural evaluation procedures.";
assert!(lix(plain) < 30.0, "{}", lix(plain));
assert!(lix(official) > 60.0, "{}", lix(official));
assert_eq!(lix_band(lix(plain)), "very easy");
assert_eq!(lix(""), 0.0);
}
#[test]
fn the_gutted_twin_keeps_the_question_and_loses_the_wording() {
let step = json!({
"question": "What brings you here?",
"options": [{"name": "Get a price", "description": "For owners."}, {"name": "Work with us", "description": "For crews."}],
"alternative": "Get a price",
"fields": [{"label": "Email"}, {"label": "The build"}]
});
let next = json!({"name": "What happens now?", "description": "A project manager reads it.", "alternatives": [{"name": "We call you within two days", "description": ""}]});
let page = page_text(&step, None, Some(&next), false);
assert!(page.contains("Get a price") && page.contains("asks for: Email, The build"));
assert!(page.contains("After you send it") && page.contains("A project manager reads it."));
// With the repo's page in hand, each option is its whole card.
let repo_page = json!({"name": "What brings you here?", "description": "", "alternatives": [
{"name": "Get a price", "description": "For owners.", "consequence": ["Send it"], "encouragements": ["We answer within two days."], "features": [{"name": "Your brief", "requirements": [{"name": "email", "label": "Email"}]}]},
{"name": "Work with us", "description": "For crews."}]});
let rich = page_text(&step, Some(&repo_page), Some(&next), false);
assert!(rich.contains("Button: Send it") && rich.contains("We answer within two days.") && rich.contains("Asks for: Email"));
assert!(!rich.contains("asks for: Email, The build"));
let twin = page_text(&step, Some(&repo_page), Some(&next), true);
assert!(!twin.contains("Send it") && !twin.contains("Your brief"));
let twin = page_text(&step, None, Some(&next), true);
assert!(twin.contains("What brings you here?") && twin.contains("Option 2"));
assert!(!twin.contains("asks for"));
assert!(!twin.contains("Get a price") && !twin.contains("Email") && !twin.contains("project manager"));
// Readability is measured on the sentences, not the headings.
let prose = prose_text(&step, Some(&next));
assert_eq!(prose, "What brings you here?\nFor owners.\nFor crews.\nA project manager reads it.");
}
#[test]
fn a_mail_is_read_as_it_arrives_and_the_invite_is_one_of_them() {
let got = as_received("Hei {name}, se {site}/decide/x?chain={chain}. {link} {ikke en nøkkel}", "Tomter Vel");
assert_eq!(got, "Hei [name], se https://example.site/decide/x?chain=8f3a1c. https://id.example.site/reset/8f3a1c {ikke en nøkkel}");
let dir = std::env::temp_dir().join(format!("portal-trainer-mails-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("aggregates.yaml"), "aggregates:\n - bucket: b\n initial: open\n states:\n open: { event: received, mail: { to: submitter, subject: Fått, body: \"Vi har det, {name}.\" } }\n").unwrap();
std::fs::write(dir.join("site.yaml"), "title: T\nmail: { from: x@y.no, invite: { subject: Konto, body: \"Hei {name}\\n{link}\" } }\n").unwrap();
let mails = mail_texts(&dir).unwrap();
assert_eq!(mails.iter().map(|m| m.0.as_str()).collect::<Vec<_>>(), ["b:open", "invite"]);
assert_eq!(mails[0].2, "Vi har det, .");
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn the_followup_page_is_read_from_the_repo_by_following_the_action() {
let dir = std::env::temp_dir().join(format!("portal-trainer-rate-{}", std::process::id()));
std::fs::create_dir_all(dir.join("questions/received")).unwrap();
std::fs::write(dir.join("questions/index.yaml"), "name: What?\nalternatives:\n - name: Get a price\n action: /received/price\n").unwrap();
std::fs::write(dir.join("questions/received/price.yaml"), "name: What happens now?\ndescription: We read it.\nalternatives:\n - name: Back\n").unwrap();
let step = json!({"page": "/", "alternative": "Get a price"});
let next = followup_page(Some(&dir), &step).unwrap();
assert_eq!(next["name"], "What happens now?");
assert!(followup_page(None, &step).is_none());
assert!(followup_page(Some(&dir), &json!({"page": "/", "alternative": "Nope"})).is_none());
std::fs::remove_dir_all(dir).ok();
}
}
+196
View File
@@ -0,0 +1,196 @@
# Portal content reference (for the generator)
Portal serves a site that is one question per page. Each page offers a
few alternatives. An alternative may carry a form; submitting it
records the answer into a *bucket* whose records move through a state
machine, worked from a *desk*: a page gated to a group, listing the
bucket with one button per allowed move. There is no other mechanism.
Everything a business needs is expressed as: who answers which
question, where the answer lands, who moves it, through which states.
A content repo is these files and nothing else:
```
needs.yaml what the business needs (the spec you are held to)
aggregates.yaml one state machine per bucket
site.yaml title and language
questions/index.yaml the front door, "/"
questions/<name>.yaml "/<name>"
questions/<dir>/index.yaml "/<dir>"
questions/<dir>/_section.yaml applies `qualifies` to the whole directory
questions/<dir>/<name>.yaml "/<dir>/<name>" - a followup page by default
```
## needs.yaml
```yaml
needs:
- id: kebab-case
who: the kind of person, in plain words
wants: what they want from the business
enters: / # page they arrive on; default /
enters_as: <group> # only when they are logged-in members of a group; omit for the public
via: <alternative name> # only when several alternatives on the entry page record into the same bucket
lands_in: <bucket>
handled_by: <group> # the role inside the business that must see and move the record
done_when: [<state>, <state>] # every state that counts as finished, good or bad
max_steps: 1 # submissions before the record exists (1 or 2)
max_fields: 4 # required fields the visitor will tolerate across the path
success: [<state>] # the done_when states that are a good outcome for the business
stages: [open, <stage>, <stage>, <end>, <end>]
# EVERY stage the business said a case goes through, first to last,
# read off their own sentences one verb at a time ("they come in, we
# go and look, we send a quote, we win or lose it" is five stages).
# The state machine must have a state for each, or the verifier fails.
personas:
- id: kebab-case
need: <need id>
text: >
Two or three sentences in the visitor's own voice and vocabulary.
```
Rules:
- One need per (kind of person, thing they want). Internal work counts:
a role inside the business recording or posting something is a need
with `enters_as`.
- States come from the business's own description of how a thing
progresses. A pipeline is not an inbox: "answered" is rarely the real
outcome.
- `max_fields` is small on purpose. Reporting something from a phone
gets 3. A first enquiry gets 4 to 6.
- Two or three personas per public need. At least one must avoid the
trade's own vocabulary. A persona must never quote a page heading.
## aggregates.yaml
```yaml
aggregates:
- bucket: leads
initial: open
states: # state: { event: past-tense verb }
open: { event: received }
quoted: { event: quoted }
won: { event: won }
lost: { event: lost }
transitions: # only moves the business described
open: [quoted, lost]
quoted: [won, lost]
```
The initial state should be `open` (a desk transition with no `from`
means from `open`).
## A page
```yaml
name: What brings you here? # always a question the visitor could ask themselves
description: >
One or two sentences.
responsible: { name: <person or team>, contact: <email> } # required on every entry page
alternatives:
- name: <heading> # what the visitor picks. Must work WITHOUT the description.
description: >
One or two sentences.
action: /received # absolute path of an existing page
consequence: [Send] # the button label
record_as: leads # omit for a pure navigation alternative
features:
- name: About the building
description: Optional line of guidance.
requirements:
- { name: email, label: Email, type: email }
- { name: problem, label: What is wrong, type: textarea }
- { name: urgency, label: How soon, type: select, options: [This week, This month, No rush] }
- { name: address, label: Address, optional: true }
```
- Field types: `text` (default), `email`, `tel`, `textarea`, `date`,
`select` (must list `options`). Use no other types.
- Every `action` must name a page that exists. After a recording
alternative, send the visitor to a followup page that says who reads
it, when they answer, and what happens next. A followup page is a
top-level file with `followup: true`, or any non-index file in a
subdirectory. Give it one alternative with `action: /` to go back.
- A page for members of a group sets `qualifies: <group>` (or sits in a
directory whose `_section.yaml` does). Only `enters_as: <group>`
needs can use it.
- Every bucket that is recorded into must be read by a desk.
## A desk
```yaml
# questions/desk/_section.yaml
qualifies: project_managers
```
```yaml
# questions/desk/index.yaml
name: What came in?
responsible: { name: ..., contact: ... }
alternatives:
- name: Leads
description: One line on what to do with them.
action: /desk
consequence: [Confirm]
features:
- name: ""
description: ""
resource:
source: { kind: kv, bucket: leads }
requires_group: project_managers
transitions:
- { to: quoted, label: Quote sent }
- { to: lost, label: Not for us }
- { from: quoted, to: won, label: Won }
- { from: quoted, to: lost, label: Lost }
```
- One desk directory per handling group; one alternative per bucket
that group handles.
- Offer every move the state machine allows and no other. A state with
no move out of it, on the way to a finished state, strands records.
- A group may read a bucket it does not handle: the same `resource`
block with its own `requires_group` and no `transitions`.
## site.yaml
```yaml
title: <business name>
lang: en
```
## Language
Everything a person reads is written in the intake's `language`: page
names, headings, descriptions, field labels, button labels, the
`who`/`wants` of each need, and the personas. Write it the way people
in that trade and country actually speak, not as a translation.
Everything a machine reads stays plain ASCII snake_case or kebab-case:
need ids, persona ids, bucket names, state names, field `name`s, file
names and paths. Letters such as æ, ø and å belong in the copy and
never in an identifier. Set `lang` in site.yaml to the intake's code.
## Copy rules
- Headings say what the visitor gets, in the visitor's words.
- Lead with what a thing enables. Never define something by what it
is not. No negations in headings.
- Two alternatives must never be separable only by a distinction the
business makes and the visitor does not.
- Every required field is one the business will use to answer.
## The verifier
`question_lint` runs after every attempt. Non-zero exit means you are
not done. Its messages are exact:
- `no path from ... records into ...`: no chain of alternatives from
the entry page reaches an alternative with that `record_as`.
- `the path asks for N required field(s), over the budget`: mark fields
`optional: true` or drop them.
- `no desk gated on "g" reads "b"`: add the desk.
- `"g" cannot move a record to "s"` / `records strand in "s"`: the desk
is missing a transition the state machine allows, or the state
machine is missing the edge.
- `action ... does not match any declared question id`: the page does
not exist.
- `entry page ... names no one responsible`: add `responsible`.
+127
View File
@@ -0,0 +1,127 @@
//! What a live site's storylines did, read back as counts.
//!
//! `portal-trainer report --site https://vel.example [--needs needs.yaml]`
//! fetches the site's `/report` (portal docs, Storylines): per bucket,
//! per storyline, per state, a count and nothing else. With the site's
//! `needs.yaml` the states that end well are known, and each storyline
//! is scored on how many cases it brought in and how many of those
//! ended well. Storylines are assigned evenly, so the counts compare
//! directly. This is the live half of what the scorer measures offline
//! with personas: the same tones, judged by what people did.
use std::collections::BTreeMap;
use anyhow::{anyhow, bail, Context};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Report {
storylines: usize,
/// bucket -> storyline -> state -> count
buckets: BTreeMap<String, BTreeMap<String, BTreeMap<String, u64>>>,
}
#[derive(Debug, Default, Deserialize)]
struct Needs {
#[serde(default)]
needs: Vec<Need>,
#[serde(default)]
tones: Vec<String>,
}
#[derive(Debug, Deserialize)]
struct Need {
lands_in: String,
#[serde(default)]
done_when: Vec<String>,
#[serde(default)]
success: Vec<String>,
}
/// One storyline's showing in one bucket.
#[derive(Debug, Default, PartialEq)]
struct Showing {
arrived: u64,
ended_well: u64,
}
/// Per bucket, per storyline index, how many arrived and how many
/// ended in a state the need calls success (or, without `success`,
/// any finished state).
fn showings(counts: &BTreeMap<String, BTreeMap<String, BTreeMap<String, u64>>>, needs: &[Need]) -> BTreeMap<String, Vec<Showing>> {
let mut out = BTreeMap::new();
for (bucket, per_story) in counts {
let well: Vec<&str> = needs
.iter()
.filter(|n| &n.lands_in == bucket)
.flat_map(|n| if n.success.is_empty() { n.done_when.iter() } else { n.success.iter() })
.map(String::as_str)
.collect();
let arity = per_story.keys().filter_map(|k| k.parse::<usize>().ok()).max().map(|m| m + 1).unwrap_or(1);
let mut rows: Vec<Showing> = (0..arity).map(|_| Showing::default()).collect();
for (story, states) in per_story {
let Ok(n) = story.parse::<usize>() else { continue };
for (state, count) in states {
rows[n].arrived += count;
if well.contains(&state.as_str()) {
rows[n].ended_well += count;
}
}
}
out.insert(bucket.clone(), rows);
}
out
}
pub fn run(argv: &[String]) -> anyhow::Result<()> {
let value = |flag: &str| argv.iter().position(|a| a == flag).and_then(|i| argv.get(i + 1)).cloned();
let site = value("--site").ok_or_else(|| anyhow!("usage: portal-trainer report --site <https://the.site> [--needs <needs.yaml>]"))?;
let url = format!("{}/report", site.trim_end_matches('/'));
let fetched = std::process::Command::new("curl").args(["-sSf", "--max-time", "30", &url]).output().context("running curl")?;
if !fetched.status.success() {
bail!("could not read {url}: {}", String::from_utf8_lossy(&fetched.stderr).trim());
}
let report: Report = serde_json::from_slice(&fetched.stdout).with_context(|| format!("reading {url}"))?;
let needs: Needs = match value("--needs") {
Some(path) => serde_yaml::from_str(&std::fs::read_to_string(&path).with_context(|| format!("reading {path}"))?)?,
None => Needs::default(),
};
println!("{site}: {} storyline(s)", report.storylines);
for (i, tone) in needs.tones.iter().enumerate() {
println!(" [{i}] {tone}");
}
if report.buckets.is_empty() {
println!("nothing sent in yet");
return Ok(());
}
let rows = showings(&report.buckets, &needs.needs);
for (bucket, per_story) in &rows {
println!("\n{bucket}");
for (n, showing) in per_story.iter().enumerate() {
let rate = if showing.arrived > 0 { format!("{:.0}%", 100.0 * showing.ended_well as f64 / showing.arrived as f64) } else { "-".to_string() };
println!(" storyline {n}: {} arrived, {} ended well ({rate})", showing.arrived, showing.ended_well);
}
if per_story.len() > 1 {
let best = per_story.iter().enumerate().max_by_key(|(_, s)| (s.ended_well, s.arrived)).map(|(n, _)| n).unwrap_or(0);
println!(" most so far: storyline {best}");
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_storyline_is_scored_on_what_arrived_and_what_ended_well() {
let counts: BTreeMap<String, BTreeMap<String, BTreeMap<String, u64>>> =
serde_json::from_str(r#"{"hazards": {"0": {"open": 3, "fixed": 4}, "1": {"open": 1, "fixed": 9, "dropped": 2}}}"#).unwrap();
let needs = vec![Need { lands_in: "hazards".into(), done_when: vec!["fixed".into(), "dropped".into()], success: vec!["fixed".into()] }];
let rows = showings(&counts, &needs);
assert_eq!(rows["hazards"][0], Showing { arrived: 7, ended_well: 4 });
assert_eq!(rows["hazards"][1], Showing { arrived: 12, ended_well: 9 });
// Without a success list, any finished state counts.
let any = vec![Need { lands_in: "hazards".into(), done_when: vec!["fixed".into(), "dropped".into()], success: vec![] }];
assert_eq!(showings(&counts, &any)["hazards"][1].ended_well, 11);
}
}
+100
View File
@@ -0,0 +1,100 @@
//! `score`: one command for the whole grading of a built site, which
//! every run under `runs/` used to carry as its own `score.sh`. The
//! lint (iris) writes the visitor tasks and the simulation model, the
//! blind visitor answers them with and without descriptions, the lint
//! scores the answers, and `rate` reads the cards. What comes out is
//! the two routing numbers, the misroutes, the rating table, and a
//! `summary.json` a run's README can quote.
use anyhow::{anyhow, bail, Context};
use std::path::{Path, PathBuf};
use std::process::Command;
pub fn run(argv: &[String]) -> anyhow::Result<()> {
let flag = |name: &str| argv.iter().position(|a| a == name).and_then(|i| argv.get(i + 1)).cloned();
let usage = "usage: portal-trainer score --site <content dir> --out <dir> [--iris <path>] [--llm 'cmd']";
let site = PathBuf::from(flag("--site").ok_or_else(|| anyhow!(usage))?);
let out = PathBuf::from(flag("--out").ok_or_else(|| anyhow!(usage))?);
let iris = flag("--iris").unwrap_or_else(|| "iris".to_string());
let cmd = flag("--llm").unwrap_or_else(|| "claude -p".to_string());
let questions = site.join("questions");
if !questions.is_dir() {
bail!("{} has no questions/ directory", site.display());
}
std::fs::create_dir_all(&out)?;
let tasks_full = out.join("tasks-full.jsonl");
let tasks_skim = out.join("tasks-skim.jsonl");
let model = out.join("model.json");
let mut log = String::new();
log.push_str(&lint(&iris, &questions, &["--needs-tasks", &s(&tasks_full), "--needs-sim", &s(&model)])?);
log.push_str(&lint(&iris, &questions, &["--needs-tasks", &s(&tasks_skim), "--skim"])?);
std::fs::write(out.join("iris.log"), &log)?;
let mut summary = serde_json::Map::new();
for (mode, tasks, skim) in [("full", &tasks_full, false), ("skim", &tasks_skim, true)] {
eprintln!("score: the visitor answers {mode}");
let answers = crate::trainer::answer_blind(&cmd, &std::fs::read_to_string(tasks)?, Some(&site), 0)?;
let answers_path = out.join(format!("answers-{mode}.jsonl"));
std::fs::write(&answers_path, &answers)?;
let (tasks_arg, answers_arg) = (s(tasks), s(&answers_path));
let mut args = vec!["--needs-tasks", tasks_arg.as_str(), "--needs-score", answers_arg.as_str()];
if skim {
args.push("--skim");
}
let report = lint(&iris, &questions, &args)?;
println!("== {}", if skim { "headings only" } else { "with descriptions" });
let mut right = None;
for line in report.lines() {
if line.starts_with("MISROUTE") || line.starts_with("HESITANT") || line.starts_with("UNANSWERED") {
println!("{line}");
}
if let Some(rest) = line.strip_prefix("wording: ") {
// "wording: 19/27 routed right (70%)"
let mut parts = rest.split_whitespace().next().unwrap_or_default().split('/');
let a: usize = parts.next().and_then(|x| x.parse().ok()).unwrap_or(0);
let b: usize = parts.next().and_then(|x| x.parse().ok()).unwrap_or(0);
right = Some((a, b));
println!("{line}");
}
}
let (a, b) = right.ok_or_else(|| anyhow!("iris printed no wording score for {mode}; its output:\n{report}"))?;
summary.insert(mode.to_string(), serde_json::json!({ "right": a, "of": b }));
}
println!("== rate");
let rated = out.join("rated");
let rate_argv: Vec<String> = ["rate", "--model", &s(&model), "--out", &s(&rated), "--repo", &s(&site), "--llm", &cmd].iter().map(|x| x.to_string()).collect();
crate::trainer::rate::rate(&rate_argv)?;
summary.insert("site".into(), serde_json::json!(s(&site)));
summary.insert("visitor".into(), serde_json::json!(cmd));
std::fs::write(out.join("summary.json"), serde_json::to_string_pretty(&serde_json::Value::Object(summary.clone()))?)?;
println!(
"== summary: with descriptions {} of {}, headings only {} of {} (rate.json in {})",
summary["full"]["right"], summary["full"]["of"], summary["skim"]["right"], summary["skim"]["of"], rated.display()
);
Ok(())
}
fn s(path: &Path) -> String {
path.display().to_string()
}
/// `iris check --path <questions> <args>`; stdout and stderr together,
/// since the lint reports on both. A lint that fails is a site that
/// cannot be scored, and its output is the reason.
fn lint(iris: &str, questions: &Path, args: &[&str]) -> anyhow::Result<String> {
let output = Command::new(iris)
.arg("check")
.arg("--path")
.arg(questions)
.args(args)
.output()
.with_context(|| format!("running {iris} (pass --iris <path> if it is not on PATH)"))?;
let text = format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
if !output.status.success() {
bail!("{iris} check --path {} {} failed:\n{text}", questions.display(), args.join(" "));
}
Ok(text)
}
+678
View File
@@ -0,0 +1,678 @@
//! Plays the whole business, many times.
//!
//! Input is the model `question_lint --needs-sim` exports. Each case is
//! one persona on one run. A visitor model picks an alternative and
//! fills the form in that person's words, in a manner that varies by
//! run; the record lands in its bucket. Then the case is walked along
//! the handling group's own desk buttons to a finished state - a
//! different one each run, so every state and button gets exercised -
//! and at each button a handler model is asked the one thing a model
//! can judge: with only what the form collected, could this role
//! really do what the button claims? If not, its question goes back to
//! the visitor, who may or may not know the answer.
//!
//! What comes out is about the content, never the market:
//! - a **misroute** is wording;
//! - an **abandoned** form asks too much of that person;
//! - an **ask-back** at (state, button) means the form did not collect
//! what the role needs there, and the question names the field;
//! - an **unanswerable** ask-back is a fact the visitor never had, so
//! the process itself has to supply it;
//! - **no route** means a finished state the desk cannot reach.
//!
//! Who wins a job is not simulated. That comes from the live bucket:
//! the `success` states in needs.yaml are what a report over real
//! records counts.
use std::collections::BTreeMap;
use std::io::Write as _;
use anyhow::{anyhow, Context};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::trainer::llm_with;
const TRAITS: &[&str] = &[
"is precise and businesslike",
"types two short lines on a phone and skips anything optional",
"explains at length, with every detail they can think of",
"is unsure of the right terms and describes things loosely",
"is in a hurry and a little impatient",
];
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(tag = "outcome", content = "detail", rename_all = "snake_case")]
pub enum Outcome {
Finished(String),
Stuck(String),
Misrouted(String),
Abandoned(String),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AskBack {
pub state: String,
pub button: String,
pub question: String,
/// The visitor knew the answer. When false, no form field would
/// have helped: the process has to find it out another way.
pub answerable: bool,
}
#[derive(Debug, Serialize)]
struct Case {
persona: String,
need: String,
run: usize,
target: String,
record: BTreeMap<String, Value>,
states: Vec<String>,
/// "state -> button", in the order pressed.
pressed: Vec<String>,
/// Who pressed each of them: a group, or `submitter`.
moved_by: Vec<String>,
touches: usize,
ask_backs: Vec<AskBack>,
outcome: Outcome,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct NeedScore {
pub cases: usize,
pub finished: usize,
pub stuck: usize,
pub misrouted: usize,
pub abandoned: usize,
pub touches: usize,
pub ask_backs: usize,
pub unanswerable: usize,
pub asked: Vec<AskBack>,
/// "state -> button": (times pressed, times the role had to ask first)
pub buttons: BTreeMap<String, (usize, usize)>,
pub stuck_at: Vec<String>,
pub misroutes: Vec<String>,
pub abandon_reasons: Vec<String>,
}
pub fn run(argv: &[String]) -> anyhow::Result<()> {
let value = |flag: &str| {
argv.iter()
.position(|a| a == flag)
.and_then(|i| argv.get(i + 1))
.cloned()
};
let usage = "usage: portal-trainer simulate --model <model.json> --out <dir> [--llm 'cmd'] [--handler-llm 'cmd'] [--runs 3] [--need <id>]";
let model_path = value("--model").ok_or_else(|| anyhow!(usage))?;
let out = std::path::PathBuf::from(value("--out").ok_or_else(|| anyhow!(usage))?);
let visitor_cmd = value("--llm").unwrap_or_else(|| "claude -p".to_string());
let handler_cmd = value("--handler-llm").unwrap_or_else(|| visitor_cmd.clone());
let runs: usize = value("--runs").map(|v| v.parse()).transpose()?.unwrap_or(3);
let only = value("--need");
let model: Value = serde_json::from_str(
&std::fs::read_to_string(&model_path).with_context(|| format!("reading {model_path}"))?,
)?;
std::fs::create_dir_all(&out)?;
let mut cases_file = std::fs::File::create(out.join("cases.jsonl"))?;
let mut scores: BTreeMap<String, NeedScore> = BTreeMap::new();
// A dry run asks no model anything: it walks every route of every
// aggregate, so each button of each role is pressed once. Its cases
// are what `needs_replay` puts through the real engine.
if argv.iter().any(|a| a == "--dry") {
for need in model["needs"].as_array().into_iter().flatten() {
let id = need["id"].as_str().unwrap_or_default();
if only.as_deref().is_some_and(|o| o != id) {
continue;
}
let bucket = &model["buckets"][need["lands_in"].as_str().unwrap_or_default()];
let done: Vec<&str> = need["done_when"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
for (run, route) in all_routes(bucket, &done).into_iter().enumerate() {
let mut states = vec![bucket["initial"].as_str().unwrap_or("open").to_string()];
states.extend(route.iter().map(|m| m.to.clone()));
let case = Case {
persona: "route".to_string(),
need: id.to_string(),
run,
target: states.last().cloned().unwrap_or_default(),
record: BTreeMap::from([("note".to_string(), json!("dry run"))]),
pressed: route.iter().map(|m| format!("{} -> {}", m.from, m.label)).collect(),
moved_by: route.iter().map(|m| m.by.clone()).collect(),
touches: route.len(),
ask_backs: Vec::new(),
outcome: Outcome::Finished(states.last().cloned().unwrap_or_default()),
states,
};
tally(scores.entry(id.to_string()).or_default(), &case);
writeln!(cases_file, "{}", serde_json::to_string(&case)?)?;
}
}
std::fs::write(out.join("score.json"), serde_json::to_string_pretty(&scores)?)?;
let relays: usize = scores.values().map(|s| s.cases).sum();
println!("dry run: {relays} route(s) across {} need(s) written to {}", scores.len(), out.join("cases.jsonl").display());
return Ok(());
}
for persona in model["personas"].as_array().into_iter().flatten() {
let need_id = persona["need"].as_str().unwrap_or_default();
if only.as_deref().is_some_and(|o| o != need_id) {
continue;
}
let Some(need) = model["needs"]
.as_array()
.into_iter()
.flatten()
.find(|n| n["id"] == need_id)
else {
continue;
};
for run in 0..runs {
let case = play(&model, need, persona, run, &visitor_cmd, &handler_cmd)?;
eprintln!(
"{} #{run}: {:?} after {} touch(es), {} ask-back(s)",
case.persona,
case.outcome,
case.touches,
case.ask_backs.len()
);
tally(scores.entry(need_id.to_string()).or_default(), &case);
writeln!(cases_file, "{}", serde_json::to_string(&case)?)?;
}
}
std::fs::write(out.join("score.json"), serde_json::to_string_pretty(&scores)?)?;
print_scores(&scores);
Ok(())
}
fn play(
model: &Value,
need: &Value,
persona: &Value,
run: usize,
visitor_cmd: &str,
handler_cmd: &str,
) -> anyhow::Result<Case> {
let who = persona["text"].as_str().unwrap_or_default();
let manner = TRAITS[run % TRAITS.len()];
let seed = |step: usize| (run * 1000 + step).to_string();
let mut case = Case {
persona: persona["id"].as_str().unwrap_or_default().to_string(),
need: need["id"].as_str().unwrap_or_default().to_string(),
run,
target: String::new(),
record: BTreeMap::new(),
states: Vec::new(),
pressed: Vec::new(),
moved_by: Vec::new(),
touches: 0,
ask_backs: Vec::new(),
outcome: Outcome::Stuck("never started".to_string()),
};
// The visitor's side.
for (i, step) in need["steps"].as_array().into_iter().flatten().enumerate() {
let options = step["options"].as_array().cloned().unwrap_or_default();
if options.len() > 1 {
let prompt = format!(
"You are this person: {who}\n\nYou open a web page that asks: {}\nIt offers:\n{}\nWhich one do you pick? Judge only from your own situation and the wording.\nReply as JSON: {{\"choice\": \"<option heading, copied exactly>\"}}",
step["question"],
options
.iter()
.map(|o| format!("- {}: {}", o["name"].as_str().unwrap_or_default(), o["description"].as_str().unwrap_or_default()))
.collect::<Vec<_>>()
.join("\n")
);
let reply = ask(visitor_cmd, &prompt, &seed(i * 10))?;
let names: Vec<&str> = options.iter().filter_map(|o| o["name"].as_str()).collect();
let choice = resolve_choice(&names, reply["choice"].as_str().unwrap_or_default());
let expected = step["expect"].as_array().cloned().unwrap_or_default();
if !expected.iter().any(|e| e.as_str() == Some(choice.as_str())) {
case.outcome = Outcome::Misrouted(choice);
return Ok(case);
}
}
let fields = step["fields"].as_array().cloned().unwrap_or_default();
if fields.is_empty() {
continue;
}
let prompt = format!(
"You are this person: {who}\nToday you are someone who {manner}.\n\nYou chose \"{}\" and now face this form:\n{}\n\nFill it in as yourself. Use only what you would actually know or have at hand; never invent precise facts a person like you would not know - say so in the field instead. Optional fields may be left out. If this form asks for something you would refuse to give, or is more effort than your situation is worth to you, abandon it.\nReply as JSON: {{\"abandon\": false, \"why\": \"\", \"values\": {{\"<field name>\": \"<what you type>\"}}}}",
step["alternative"].as_str().unwrap_or_default(),
fields
.iter()
.map(|f| format!(
"- {} (name: {}, type: {}{}{})",
f["label"].as_str().unwrap_or_default(),
f["name"].as_str().unwrap_or_default(),
f["type"].as_str().unwrap_or("text"),
if f["optional"] == true { ", optional" } else { ", required" },
match f["options"].as_array() {
Some(o) if !o.is_empty() => format!(", one of {}", Value::Array(o.clone())),
_ => String::new(),
}
))
.collect::<Vec<_>>()
.join("\n")
);
let reply = ask(visitor_cmd, &prompt, &seed(i * 10 + 1))?;
if reply["abandon"] == true {
case.outcome = Outcome::Abandoned(reply["why"].as_str().unwrap_or_default().to_string());
return Ok(case);
}
if let Some(values) = reply["values"].as_object() {
for (k, v) in values {
case.record.insert(k.clone(), v.clone());
}
}
}
// The business's side. A model is a poor judge of who wins a job,
// and an 8B one decides by the tone of its prompt (measured: every
// case "won", then, one sentence later, every case "lost"). So the
// route is scripted, not decided: run by run, cases are sent to
// each finished state in turn, along the desk's own buttons, which
// covers every state and button of the machine. At each button the
// model is asked only what it can judge: with what the form
// collected, could this role really do what the button claims?
let bucket_name = need["lands_in"].as_str().unwrap_or_default();
let bucket = &model["buckets"][bucket_name];
let done: Vec<&str> = need["done_when"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let initial = bucket["initial"].as_str().unwrap_or("open").to_string();
let target = done.get(run % done.len().max(1)).copied().unwrap_or_default().to_string();
case.target = target.clone();
case.states.push(initial.clone());
let Some(route) = route_to(bucket, &initial, &target) else {
case.outcome = Outcome::Stuck(format!("no route of buttons from {initial} to {target}"));
return Ok(case);
};
for (step, mv) in route.iter().enumerate() {
let (from, label, to, group) = (&mv.from, &mv.label, &mv.to, &mv.by);
case.moved_by.push(group.clone());
case.touches += 1;
case.pressed.push(format!("{from} -> {label}"));
case.states.push(to.clone());
// The submitter's own decision is theirs to make; there is no
// role whose information could be short.
if group == SUBMITTER {
continue;
}
let prompt = format!(
"You work at a business as one of its {group}. A case in `{bucket_name}` is in state `{from}`. It came from {}, who wants {}.\n\nThis is everything you have about it - what the form collected, plus any follow-up:\n{}\n\nThe next thing that happens to this case is the desk button \"{label}\", which moves it to `{to}`. Pressing it claims that this has really been done.\n\nUsing only what is in front of you, could you really do that now? Answer false only when a fact that ONLY THE PERSON can give is missing and you could not proceed without it. Facts you find out yourself while doing the work do not count: you learn a building's condition by visiting it, a firm's registration by looking it up.\nReply as JSON: {{\"can_act\": true or false, \"need_to_know\": \"<the one question you would send them>\" or null}}",
need["who"].as_str().unwrap_or_default(),
need["wants"].as_str().unwrap_or_default(),
serde_json::to_string_pretty(&case.record)?,
);
let reply = ask(handler_cmd, &prompt, &seed(100 + step))?;
let question = reply["need_to_know"].as_str().unwrap_or_default().trim().to_string();
if reply["can_act"] == false && !question.is_empty() {
let answer = ask(
visitor_cmd,
&format!(
"You are this person: {who}\nToday you are someone who {manner}.\n\nThe business you wrote to comes back with a question: {question}\nAnswer as yourself, briefly. Use only what a person like you would really know.\nReply as JSON: {{\"known\": true or false, \"answer\": \"...\"}}"
),
&seed(200 + step),
)?;
let n = case.ask_backs.len() + 1;
case.record.insert(format!("follow_up_{n}"), json!({ "asked": question, "answered": answer["answer"] }));
case.ask_backs.push(AskBack {
state: from.clone(),
button: label.clone(),
question,
answerable: answer["known"] != false,
});
case.touches += 1;
}
}
case.outcome = Outcome::Finished(target);
Ok(case)
}
pub(crate) const SUBMITTER: &str = "submitter";
/// One button: who holds it, and where it takes a case.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Move {
pub from: String,
pub label: String,
pub to: String,
pub by: String,
}
/// Every legal button on an aggregate, whoever holds it: each group's
/// desk, and the submitter's own link. Roles overlap on one aggregate,
/// so a route is a relay, not one desk's work.
pub(crate) fn all_moves(bucket: &Value) -> Vec<Move> {
let legal = |from: &str, to: &str| bucket["transitions"][from].as_array().is_some_and(|a| a.iter().any(|x| x == to));
let mut moves: Vec<Move> = Vec::new();
for desk in bucket["desks"].as_array().into_iter().flatten() {
for m in desk["moves"].as_array().into_iter().flatten() {
let (Some(from), Some(label), Some(to)) = (m["from"].as_str(), m["label"].as_str(), m["to"].as_str()) else { continue };
if legal(from, to) && !moves.iter().any(|x| x.from == from && x.to == to) {
moves.push(Move { from: from.into(), label: label.into(), to: to.into(), by: desk["group"].as_str().unwrap_or("ungated").into() });
}
}
}
let states: Vec<String> = bucket["transitions"].as_object().map(|t| t.keys().cloned().collect()).unwrap_or_default();
for to in bucket["self_moves"].as_array().into_iter().flatten().filter_map(Value::as_str) {
for from in &states {
if legal(from, to) && !moves.iter().any(|x| &x.from == from && x.to == to) {
moves.push(Move { from: from.clone(), label: "their own link".into(), to: to.into(), by: SUBMITTER.into() });
}
}
}
moves
}
/// The shortest relay of buttons from one state to another.
fn route_to(bucket: &Value, from: &str, to: &str) -> Option<Vec<Move>> {
let moves = all_moves(bucket);
let mut queue = std::collections::VecDeque::from([(from.to_string(), Vec::new())]);
let mut seen = std::collections::HashSet::from([from.to_string()]);
while let Some((state, path)) = queue.pop_front() {
if state == to {
return Some(path);
}
for mv in moves.iter().filter(|m| m.from == state) {
if seen.insert(mv.to.clone()) {
let mut next = path.clone();
next.push(mv.clone());
queue.push_back((mv.to.clone(), next));
}
}
}
None
}
/// Every simple route from the first state to any finished one: what a
/// dry run walks, so that each button of each role is pressed at least
/// once against the real engine.
pub(crate) fn all_routes(bucket: &Value, done: &[&str]) -> Vec<Vec<Move>> {
fn walk(state: &str, done: &[&str], moves: &[Move], path: &mut Vec<Move>, out: &mut Vec<Vec<Move>>) {
if done.contains(&state) {
out.push(path.clone());
return;
}
for mv in moves.iter().filter(|m| m.from == state) {
if path.iter().any(|p| p.from == mv.to) {
continue;
}
path.push(mv.clone());
walk(&mv.to, done, moves, path, out);
path.pop();
}
}
let mut out = Vec::new();
walk(bucket["initial"].as_str().unwrap_or("open"), done, &all_moves(bucket), &mut Vec::new(), &mut out);
out
}
/// Models often answer "Heading: its description" or change the case.
/// The pick is the longest option heading the answer starts with;
/// anything else is kept verbatim and counts as a misroute.
pub(crate) fn resolve_choice(names: &[&str], raw: &str) -> String {
let answer = raw.trim().trim_matches('"').to_lowercase();
names
.iter()
.filter(|n| answer.starts_with(&n.to_lowercase()))
.max_by_key(|n| n.len())
.map(|n| n.to_string())
.unwrap_or_else(|| raw.trim().to_string())
}
/// One JSON-answering call. The backend is asked for JSON where it can
/// be (`FORMAT=json`, honoured by engines/ollama.sh) and the first
/// object in the reply is taken either way.
pub(crate) fn ask(cmd: &str, prompt: &str, seed: &str) -> anyhow::Result<Value> {
let reply = llm_with(cmd, prompt, &[("FORMAT", "json"), ("SEED", seed), ("TEMPERATURE", "0.7")])?;
Ok(first_object(&reply).unwrap_or(Value::Null))
}
pub(crate) fn first_object(text: &str) -> Option<Value> {
let start = text.find('{')?;
let mut depth = 0usize;
let mut in_string = false;
let mut escaped = false;
for (i, c) in text[start..].char_indices() {
match (in_string, escaped, c) {
(true, true, _) => escaped = false,
(true, false, '\\') => escaped = true,
(true, false, '"') => in_string = false,
(false, _, '"') => in_string = true,
(false, _, '{') => depth += 1,
(false, _, '}') => {
depth -= 1;
if depth == 0 {
return serde_json::from_str(&text[start..start + i + 1]).ok();
}
}
_ => {}
}
}
None
}
fn tally(score: &mut NeedScore, case: &Case) {
score.cases += 1;
score.touches += case.touches;
score.ask_backs += case.ask_backs.len();
score.unanswerable += case.ask_backs.iter().filter(|a| !a.answerable).count();
score.asked.extend(case.ask_backs.iter().cloned());
for button in &case.pressed {
score.buttons.entry(button.clone()).or_default().0 += 1;
}
for a in &case.ask_backs {
score.buttons.entry(format!("{} -> {}", a.state, a.button)).or_default().1 += 1;
}
match &case.outcome {
Outcome::Finished(_) => score.finished += 1,
Outcome::Stuck(at) => {
score.stuck += 1;
score.stuck_at.push(at.clone());
}
Outcome::Misrouted(picked) => {
score.misrouted += 1;
score.misroutes.push(format!("{}: {picked}", case.persona));
}
Outcome::Abandoned(why) => {
score.abandoned += 1;
score.abandon_reasons.push(format!("{}: {why}", case.persona));
}
}
}
fn pct(n: usize, of: usize) -> String {
if of == 0 {
"-".to_string()
} else {
format!("{:.0}%", n as f64 * 100.0 / of as f64)
}
}
fn per_case(n: usize, s: &NeedScore) -> String {
let reached = s.cases - s.misrouted - s.abandoned;
if reached == 0 {
"-".to_string()
} else {
format!("{:.1}", n as f64 / reached as f64)
}
}
fn print_scores(scores: &BTreeMap<String, NeedScore>) {
println!(
"\n{:<28} {:>5} {:>9} {:>9} {:>10} {:>9} {:>8} {:>10} {:>13}",
"need", "cases", "finished", "misroute", "abandoned", "no route", "touches", "ask-backs", "unanswerable"
);
for (need, s) in scores {
println!(
"{:<28} {:>5} {:>9} {:>9} {:>10} {:>9} {:>8} {:>10} {:>13}",
need,
s.cases,
pct(s.finished, s.cases),
pct(s.misrouted, s.cases),
pct(s.abandoned, s.cases),
pct(s.stuck, s.cases),
per_case(s.touches, s),
per_case(s.ask_backs, s),
per_case(s.unanswerable, s),
);
}
println!("\nWhere the role could not act on what the form collected:");
for (need, s) in scores {
for (button, (pressed, asked)) in s.buttons.iter().filter(|(_, (_, asked))| *asked > 0) {
println!(" {need}: {button} - had to ask first in {asked} of {pressed}");
}
}
for (need, s) in scores {
for a in &s.asked {
println!(
" {need} [{} / {}]{} {}",
a.state,
a.button,
if a.answerable { "" } else { " (visitor did not know)" },
a.question
);
}
for at in &s.stuck_at {
println!(" {need}: {at}");
}
for m in &s.misroutes {
println!(" {need}: misrouted - {m}");
}
for r in &s.abandon_reasons {
println!(" {need}: abandoned - {r}");
}
}
}
/// `compare <a/score.json> <b/score.json>`: the same seeded cases
/// against two versions of a site.
pub fn compare(argv: &[String]) -> anyhow::Result<()> {
let (a, b) = match (argv.get(1), argv.get(2)) {
(Some(a), Some(b)) => (a, b),
_ => return Err(anyhow!("usage: portal-trainer compare <a/score.json> <b/score.json>")),
};
let load = |p: &String| -> anyhow::Result<BTreeMap<String, NeedScore>> {
Ok(serde_json::from_str(&std::fs::read_to_string(p).with_context(|| format!("reading {p}"))?)?)
};
let (a, b) = (load(a)?, load(b)?);
println!(
"{:<28} {:>14} {:>14} {:>14} {:>16} {:>16}",
"need", "misroute", "abandoned", "no route", "touches / case", "ask-backs / case"
);
for (need, sa) in &a {
let Some(sb) = b.get(need) else { continue };
println!(
"{:<28} {:>14} {:>14} {:>14} {:>16} {:>16}",
need,
format!("{} -> {}", pct(sa.misrouted, sa.cases), pct(sb.misrouted, sb.cases)),
format!("{} -> {}", pct(sa.abandoned, sa.cases), pct(sb.abandoned, sb.cases)),
format!("{} -> {}", pct(sa.stuck, sa.cases), pct(sb.stuck, sb.cases)),
format!("{} -> {}", per_case(sa.touches, sa), per_case(sb.touches, sb)),
format!("{} -> {}", per_case(sa.ask_backs, sa), per_case(sb.ask_backs, sb)),
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_first_json_object_is_found_inside_chatter() {
let v = first_object("Sure! {\"choice\": \"A {b}\", \"n\": {\"x\": 1}} trailing").unwrap();
assert_eq!(v["choice"], "A {b}");
assert_eq!(v["n"]["x"], 1);
assert!(first_object("no json").is_none());
}
#[test]
fn a_choice_is_matched_by_its_heading_however_the_model_dresses_it() {
let names = ["Ask about working", "Ask about working with us", "Get a price"];
assert_eq!(resolve_choice(&names, "Ask about working with us: For carpenters who..."), "Ask about working with us");
assert_eq!(resolve_choice(&names, " get a PRICE "), "Get a price");
assert_eq!(resolve_choice(&names, "Something else"), "Something else");
}
fn bucket() -> Value {
json!({
"initial": "open",
"transitions": {"open": ["surveyed", "lost"], "surveyed": ["quoted", "lost"], "quoted": ["won", "lost"]},
"desks": [
{"group": "pm", "moves": [
{"from": "open", "to": "surveyed", "label": "Looked"},
{"from": "surveyed", "to": "quoted", "label": "Quote sent"},
{"from": "quoted", "to": "won", "label": "Won"},
{"from": "open", "to": "lost", "label": "Not for us"},
// Offered by the desk, refused by the machine.
{"from": "open", "to": "won", "label": "Shortcut"}
]},
{"group": "other", "moves": [{"from": "quoted", "to": "lost", "label": "Theirs"}]}
]
})
}
#[test]
fn a_route_is_a_relay_of_legal_buttons_across_roles() {
// "Shortcut" is offered by a desk and refused by the machine.
assert!(!all_moves(&bucket()).iter().any(|m| m.label == "Shortcut"));
// Losing a quoted job is the other group's button, so the way
// from open to that ending is a relay: two roles, one case.
let route = route_to(&bucket(), "surveyed", "lost").unwrap();
let relay: Vec<(&str, &str)> = route.iter().map(|m| (m.label.as_str(), m.by.as_str())).collect();
assert_eq!(relay, [("Quote sent", "pm"), ("Theirs", "other")]);
assert_eq!(route_to(&bucket(), "open", "open").unwrap().len(), 0);
assert!(route_to(&bucket(), "won", "open").is_none());
}
#[test]
fn the_submitters_own_link_is_a_move_like_any_other() {
let mut b = bucket();
b["self_moves"] = json!(["lost"]);
let theirs: Vec<Move> = all_moves(&b).into_iter().filter(|m| m.by == SUBMITTER).collect();
// Only where the machine allows it and no desk already holds it:
// open->lost is the project manager's and quoted->lost the other
// group's, which leaves surveyed->lost to the link.
let froms: Vec<&str> = theirs.iter().map(|m| m.from.as_str()).collect();
assert_eq!(froms, ["surveyed"]);
}
#[test]
fn a_dry_run_walks_every_route_to_every_ending() {
let routes = all_routes(&bucket(), &["won", "lost"]);
let ends: Vec<String> = routes.iter().map(|r| format!("{}:{}", r.len(), r.last().unwrap().to)).collect();
// open->lost; open->surveyed->quoted->won; and the relay
// open->surveyed->quoted->lost, closed by the other group.
assert_eq!(ends.len(), 3, "{ends:?}");
assert_eq!(ends.iter().filter(|e| *e == "3:lost").count(), 1);
assert!(ends.contains(&"1:lost".to_string()) && ends.contains(&"3:won".to_string()));
assert!(routes.iter().any(|r| r.iter().any(|m| m.by == "other")));
}
#[test]
fn a_case_is_tallied_by_how_it_ended_and_what_had_to_be_asked() {
let mut score = NeedScore::default();
let base = |outcome| Case {
persona: "p".into(),
need: "n".into(),
run: 0,
target: "won".into(),
record: BTreeMap::new(),
states: vec![],
pressed: vec!["open -> Looked".into(), "surveyed -> Quote sent".into()],
moved_by: vec!["pm".into(), "pm".into()],
touches: 3,
ask_backs: vec![
AskBack { state: "open".into(), button: "Looked".into(), question: "Which floor?".into(), answerable: true },
AskBack { state: "surveyed".into(), button: "Quote sent".into(), question: "Load-bearing?".into(), answerable: false },
],
outcome,
};
tally(&mut score, &base(Outcome::Finished("won".into())));
tally(&mut score, &base(Outcome::Stuck("no route".into())));
tally(&mut score, &base(Outcome::Misrouted("Wrong door".into())));
assert_eq!((score.cases, score.finished, score.stuck, score.misrouted), (3, 1, 1, 1));
assert_eq!((score.ask_backs, score.unanswerable), (6, 3));
}
}
+12 -7
View File
@@ -15,7 +15,7 @@ use serde::Serialize;
use crate::server::AppState;
pub const MAX_UPLOAD_BYTES: usize = 20 * 1024 * 1024;
pub const MAX_UPLOAD_BYTES: usize = crate::app::MAX_UPLOAD_BYTES;
#[derive(Clone)]
pub struct Garage {
@@ -277,13 +277,15 @@ pub async fn attachment(
// cannot be used to learn which buckets, records or fields exist.
let missing = || (StatusCode::NOT_FOUND, "not found".to_string());
if !may_read_bucket(&state, &session, &bucket).await {
return Err(missing());
}
let store = state.jetstream.get_key_value(&bucket).await.map_err(|_| missing())?;
let bytes = store.get(&record).await.map_err(|_| missing())?.ok_or_else(missing)?;
let answer: crate::answers::Answer = serde_json::from_slice(&bytes).map_err(|_| missing())?;
let as_listed: serde_json::Value = serde_json::from_slice(&bytes).map_err(|_| missing())?;
// Through a list the caller may read, and one that shows this
// record: a list of "my cases" opens my files and nobody else's.
if !may_read_record(&state, &session, &bucket, &as_listed).await {
return Err(missing());
}
let answer: crate::answers::Answer = serde_json::from_value(as_listed).map_err(|_| missing())?;
let key = answer
.responses
.get(&field)
@@ -331,20 +333,23 @@ pub async fn attachment(
/// Whether this caller may see this bucket at all: whether any feature
/// in the loaded content lists it and the policy lets them read that
/// feature. The desk that shows the record is what grants the file.
async fn may_read_bucket(
async fn may_read_record(
state: &AppState,
session: &tower_sessions::Session,
bucket: &str,
record: &serde_json::Value,
) -> bool {
use crate::auth::{User, SESSION_USER_KEY};
let user = session.get::<User>(SESSION_USER_KEY).await.ok().flatten();
let principal = crate::access::Principal::from_user(user.as_ref());
let params = crate::resource::with_person(Default::default(), user.as_ref());
let access = state.access.load();
state.questions.load().values().any(|question| {
question.alternatives.iter().any(|alternative| {
alternative.features.iter().any(|feature| {
feature.resource.as_ref().and_then(|r| r.bucket()) == Some(bucket)
&& feature.resource.as_ref().is_some_and(|r| crate::resource::matches_filter(r, record, &params))
&& access.allows(
&principal,
crate::access::Action::Read,
+330 -11
View File
@@ -173,6 +173,61 @@ main.not-found {
gap: 1rem;
}
/* Who is here and the way in or out: top right of every page, on a
site that has sign-in. */
.session {
position: absolute;
top: 1rem;
right: 1.5rem;
z-index: 5;
display: flex;
gap: 0.9rem;
align-items: baseline;
font-size: 0.88rem;
}
.session a {
color: var(--ink);
text-decoration: none;
border-bottom: 0.06rem solid var(--line);
}
.session a:hover {
color: var(--accent);
border-bottom-color: var(--accent);
}
.session-name {
color: var(--ink-dim);
}
/* A page with pictures: the wordmark is a bar of its own, the strip
runs the full width under it, and the question follows. */
.hero-slides {
max-width: none;
padding: 0 0 2rem;
align-items: stretch;
gap: 0;
}
.hero-bar {
display: flex;
align-items: center;
padding: 0.9rem 1.5rem;
}
.hero-slides .slideshow {
margin-bottom: 2rem;
}
.hero-slides .hero-copy {
width: 100%;
max-width: 46rem;
margin: 0 auto;
padding: 0 1.5rem;
box-sizing: border-box;
}
.wordmark {
display: inline-flex;
opacity: 0.85;
@@ -269,6 +324,69 @@ main.not-found {
/* position + z-index on these three: everything that scrolls over the
sticky canvas must be a positioned box above the hero's z-index 0,
or the (positioned) hero would paint over it. */
/* Pictures across the page (`slideshow`): the full width of the
screen, every picture the strip's height and as wide as its own
shape, never wider than the screen. The caption floats over the
foot of its picture. */
.slideshow {
--swiper-navigation-color: #fff;
--swiper-navigation-size: 1.8rem;
position: relative;
z-index: 1;
display: block;
width: 100%;
height: var(--slideshow-height, 60svh);
max-height: var(--slideshow-height, 60svh);
margin: 0 0 3rem;
}
/* Before the Swiper bundle has upgraded the element, or without it:
a row that scrolls sideways. */
.slideshow:not(:defined) {
display: flex;
gap: 6px;
overflow-x: auto;
overflow-y: hidden;
}
.slideshow swiper-slide {
flex: none;
width: auto;
height: 100%;
}
.slide {
position: relative;
height: 100%;
margin: 0;
}
.slide img {
display: block;
height: 100%;
width: auto;
/* A picture that has not loaded and says nothing of its size still
takes a place, or the whole strip would sit in view at once. */
min-width: 12rem;
max-width: 100vw;
object-fit: cover;
background: var(--line);
}
.slide figcaption {
position: absolute;
left: 0;
right: 0;
bottom: 0;
padding: 2.4rem 1rem 0.9rem;
color: #fff;
font-size: 0.95rem;
line-height: 1.35;
text-shadow: 0 0.06rem 0.2rem rgba(0, 0, 0, 0.6);
background: linear-gradient(to top, rgba(0, 0, 0, 0.72), rgba(0, 0, 0, 0));
pointer-events: none;
}
.alternatives {
position: relative;
z-index: 1;
@@ -679,7 +797,7 @@ main.not-found {
.feature p {
color: var(--ink-dim);
font-size: 0.95rem;
font-size: 0.95em;
}
.field {
@@ -690,7 +808,7 @@ main.not-found {
}
.field-label {
font-size: 0.85rem;
font-size: 0.85em;
font-weight: 600;
color: var(--ink-dim);
}
@@ -700,17 +818,74 @@ main.not-found {
margin-left: 0.2em;
}
/* Controls take their size from the text around them (em, not rem):
a site that sets its body larger, or a card that sets itself
smaller, gets fields, pills and buttons to match, and everything
inside a control - the date picker's icon, the file picker's button
- scales with the control. */
input,
textarea {
font: inherit;
color: var(--ink);
background: var(--paper);
border: 0.06rem solid var(--line);
border-radius: 0.6rem;
padding: 0.65rem 0.8rem;
border-radius: 0.6em;
padding: 0.65em 0.8em;
width: 100%;
}
/* The calendar icon at the size of the text it sits beside, and a
target worth aiming at. */
input[type="date"],
input[type="time"],
input[type="datetime-local"] {
min-height: 2.9em;
}
input[type="date"]::-webkit-calendar-picker-indicator,
input[type="time"]::-webkit-calendar-picker-indicator,
input[type="datetime-local"]::-webkit-calendar-picker-indicator {
width: 1.35em;
height: 1.35em;
padding: 0.2em;
margin-left: 0.4em;
cursor: pointer;
opacity: 0.75;
}
input[type="date"]::-webkit-calendar-picker-indicator:hover,
input[type="time"]::-webkit-calendar-picker-indicator:hover,
input[type="datetime-local"]::-webkit-calendar-picker-indicator:hover {
opacity: 1;
}
/* The file picker's own button, in the field's colours rather than
the browser's: it follows whatever ink the field has, so it holds
on a light field and a dark one alike. */
input[type="file"] {
padding: 0.45em;
cursor: pointer;
}
input[type="file"]::file-selector-button {
font: inherit;
font-size: 0.85em;
font-weight: 600;
color: inherit;
background: color-mix(in srgb, currentColor 9%, transparent);
border: 0.06rem solid color-mix(in srgb, currentColor 28%, transparent);
border-radius: 999rem;
padding: 0.4em 1em;
margin-right: 0.8em;
cursor: pointer;
transition: border-color 120ms, background 120ms;
}
input[type="file"]::file-selector-button:hover {
background: var(--accent-soft);
border-color: var(--accent);
}
textarea {
min-height: 5rem;
resize: vertical;
@@ -971,14 +1146,14 @@ textarea:focus {
}
.alt-submit {
font-family: var(--sans);
font-family: inherit;
font-weight: 600;
font-size: 0.95rem;
font-size: 0.95em;
color: var(--paper);
background: var(--accent);
border: none;
border-radius: 0.7rem;
padding: 0.75rem 1.4rem;
border-radius: 0.7em;
padding: 0.75em 1.4em;
cursor: pointer;
transition: filter 120ms, transform 120ms;
/* A gateway alternative renders this as an <a> (navigation, no POST);
@@ -1094,6 +1269,86 @@ textarea:focus {
color: var(--accent);
}
/* A read-only list whose records carry a picture: shown, not read. */
.answer-cards {
grid-template-columns: repeat(auto-fill, minmax(min(100%, 11rem), 1fr));
align-items: start;
}
.answer-card {
padding: 0;
overflow: hidden;
gap: 0;
}
.answer-picture {
display: block;
width: 100%;
aspect-ratio: 4 / 5;
object-fit: cover;
background: var(--line);
}
.answer-card-text {
padding: 0.9rem 1.1rem 1.1rem;
display: grid;
gap: 0.35rem;
}
.answer-card-heading {
margin: 0;
font-size: 1.05rem;
}
.answer-card-text p {
margin: 0;
font-size: 0.92rem;
color: var(--ink-dim);
white-space: pre-line;
}
.answer-card-text p:first-of-type {
color: var(--ink);
font-weight: 600;
}
.answer-card .answer-link {
margin: 0 1.1rem 1.1rem;
}
/* A picture on a desk's record: small, and it opens. */
.answer-thumb {
display: block;
max-width: 8rem;
max-height: 8rem;
border-radius: 0.4rem;
object-fit: cover;
}
/* Why a send was refused, under its button. */
.alt-error {
margin: 0.6em 0 0;
color: var(--accent);
font-size: 0.92em;
}
/* The file already on a card of one's own, above the picker. */
.field-current {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.6em;
font-size: 0.9em;
color: var(--ink-dim);
}
/* A stored file on a record: its name, and it opens. */
.answer-file {
color: var(--accent);
text-decoration: none;
border-bottom: 0.06rem solid var(--accent);
}
/* The page about a listed record, when the list offers one. */
.answer-link {
display: inline-block;
@@ -1184,13 +1439,13 @@ textarea:focus {
}
.select-option {
font-family: var(--sans);
font-size: 0.85rem;
font-family: inherit;
font-size: 0.85em;
color: var(--ink);
background: var(--paper);
border: 0.06rem solid var(--line);
border-radius: 999rem;
padding: 0.4rem 0.9rem;
padding: 0.45em 1em;
cursor: pointer;
transition: border-color 120ms, color 120ms, background 120ms;
}
@@ -1338,3 +1593,67 @@ textarea:focus {
.resource-loading {
min-height: 1.4em;
}
/* Pages move the way their addresses do (public/page-motion.js):
deeper comes in from the right, back up from the left, a page at the
same depth from below or above. The cards leave and arrive as
islands of their own, one after another. Transforms and opacity
only. */
@media (prefers-reduced-motion: no-preference) {
:root {
--pm-duration: 340ms;
--pm-ease: cubic-bezier(0.22, 0.8, 0.24, 1);
--pm-step: 45ms;
}
::view-transition-old(*),
::view-transition-new(*) {
animation-duration: var(--pm-duration);
animation-timing-function: var(--pm-ease);
animation-fill-mode: both;
}
/* A named card has only an old or only a new picture; its group must
not also morph. */
::view-transition-group(*) {
animation-duration: var(--pm-duration);
}
}
@keyframes pm-out-left { to { transform: translateX(-18%); opacity: 0; } }
@keyframes pm-out-right { to { transform: translateX(18%); opacity: 0; } }
@keyframes pm-out-up { to { transform: translateY(-10%); opacity: 0; } }
@keyframes pm-out-down { to { transform: translateY(10%); opacity: 0; } }
@keyframes pm-in-right { from { transform: translateX(18%); opacity: 0; } }
@keyframes pm-in-left { from { transform: translateX(-18%); opacity: 0; } }
@keyframes pm-in-below { from { transform: translateY(10%); opacity: 0; } }
@keyframes pm-in-above { from { transform: translateY(-10%); opacity: 0; } }
/* The cards, one step apart: out first, in after the page has begun. */
@media (prefers-reduced-motion: no-preference) {
:root[data-motion="forward"]::view-transition-old(*) { animation-name: pm-out-left; }
:root[data-motion="forward"]::view-transition-new(*) { animation-name: pm-in-right; }
:root[data-motion="back"]::view-transition-old(*) { animation-name: pm-out-right; }
:root[data-motion="back"]::view-transition-new(*) { animation-name: pm-in-left; }
:root[data-motion="down"]::view-transition-old(*) { animation-name: pm-out-up; }
:root[data-motion="down"]::view-transition-new(*) { animation-name: pm-in-below; }
:root[data-motion="up"]::view-transition-old(*) { animation-name: pm-out-down; }
:root[data-motion="up"]::view-transition-new(*) { animation-name: pm-in-above; }
::view-transition-old(pm-out-1) { animation-delay: calc(0 * var(--pm-step)); }
::view-transition-new(pm-in-1) { animation-delay: calc(90ms + 0 * var(--pm-step)); }
::view-transition-old(pm-out-2) { animation-delay: calc(1 * var(--pm-step)); }
::view-transition-new(pm-in-2) { animation-delay: calc(90ms + 1 * var(--pm-step)); }
::view-transition-old(pm-out-3) { animation-delay: calc(2 * var(--pm-step)); }
::view-transition-new(pm-in-3) { animation-delay: calc(90ms + 2 * var(--pm-step)); }
::view-transition-old(pm-out-4) { animation-delay: calc(3 * var(--pm-step)); }
::view-transition-new(pm-in-4) { animation-delay: calc(90ms + 3 * var(--pm-step)); }
::view-transition-old(pm-out-5) { animation-delay: calc(4 * var(--pm-step)); }
::view-transition-new(pm-in-5) { animation-delay: calc(90ms + 4 * var(--pm-step)); }
::view-transition-old(pm-out-6) { animation-delay: calc(5 * var(--pm-step)); }
::view-transition-new(pm-in-6) { animation-delay: calc(90ms + 5 * var(--pm-step)); }
::view-transition-old(pm-out-7) { animation-delay: calc(6 * var(--pm-step)); }
::view-transition-new(pm-in-7) { animation-delay: calc(90ms + 6 * var(--pm-step)); }
::view-transition-old(pm-out-8) { animation-delay: calc(7 * var(--pm-step)); }
::view-transition-new(pm-in-8) { animation-delay: calc(90ms + 7 * var(--pm-step)); }
}
+33 -4
View File
@@ -34,7 +34,7 @@ async fn a_submission_is_created_moved_refused_and_read_back_through_the_real_en
let now = chrono::Utc::now().timestamp_millis();
// The submission: a KV record in the initial state, plus the first event.
store_answer(&js, &schemas, &bucket, "rec-1".into(), "/", "Hire us", &json!({"email": "a@b.example"}), now)
store_answer(&js, &schemas, &bucket, "rec-1".into(), "/", "Hire us", &json!({"email": "a@b.example"}), now, 0)
.await
.expect("store");
let store = js.get_key_value(&bucket).await.expect("bucket exists");
@@ -178,9 +178,9 @@ async fn a_membership_is_invited_becomes_active_at_sign_in_and_can_be_taken_back
leptos_options: leptos::config::LeptosOptions::builder().output_name("test").build(),
nats,
jetstream: js,
questions: std::sync::Arc::new(arc_swap::ArcSwap::from_pointee(questions)),
aggregates: std::sync::Arc::new(arc_swap::ArcSwap::from_pointee(aggregates)),
site: std::sync::Arc::new(arc_swap::ArcSwap::from_pointee(Default::default())),
questions: std::sync::Arc::new(arc_swap::ArcSwap::from_pointee(portal::content::Storylines::one(questions))),
aggregates: std::sync::Arc::new(arc_swap::ArcSwap::from_pointee(portal::content::Storylines::one(aggregates))),
site: std::sync::Arc::new(arc_swap::ArcSwap::from_pointee(portal::content::Storylines::one(Default::default()))),
access: std::sync::Arc::new(arc_swap::ArcSwap::from_pointee(access)),
gitea_base: String::new(),
content_raw_base: String::new(),
@@ -248,3 +248,32 @@ async fn a_membership_is_invited_becomes_active_at_sign_in_and_can_be_taken_back
let groups = memberships::on_signed_in(&state, &kari).await;
assert!(groups.contains(&styret.to_string()));
}
#[tokio::test]
async fn a_card_of_ones_own_is_replaced_not_added_to_even_on_a_double_click() {
use portal::answers::{keep_newest_own, own_records, OWNER_FIELD};
let Ok(url) = std::env::var("PORTAL_TEST_NATS_URL") else {
eprintln!("skipped: PORTAL_TEST_NATS_URL is not set");
return;
};
let js = async_nats::jetstream::new(async_nats::connect(&url).await.expect("connect"));
ensure_stream(&js).await.expect("event stream");
let bucket = format!("own_{}", chrono::Utc::now().timestamp_millis());
let schemas = std::collections::HashMap::new();
let now = chrono::Utc::now().timestamp_millis();
let card = |name: &str, by: &str| json!({"name": name, OWNER_FIELD: by});
// Kari's first card, then two sends of her second pressed at once,
// and Ola's card beside them.
store_answer(&js, &schemas, &bucket, "k1".into(), "/kontor/ansatt", "a", &card("Kari", "kari"), now, 0).await.unwrap();
store_answer(&js, &schemas, &bucket, "o1".into(), "/kontor/ansatt", "a", &card("Ola", "ola"), now + 1, 0).await.unwrap();
store_answer(&js, &schemas, &bucket, "k2".into(), "/kontor/ansatt", "a", &card("Kari N.", "kari"), now + 2, 0).await.unwrap();
store_answer(&js, &schemas, &bucket, "k3".into(), "/kontor/ansatt", "a", &card("Kari N.", "kari"), now + 2, 0).await.unwrap();
// Both racing sends settle after storing; both must keep the same one.
let (a, b) = tokio::join!(keep_newest_own(&js, &bucket, "open", "kari"), keep_newest_own(&js, &bucket, "open", "kari"));
let _ = (a, b);
let kari = own_records(&js, &bucket, "kari").await;
assert_eq!(kari.iter().map(|a| a.id.as_str()).collect::<Vec<_>>(), vec!["k3"], "one card, the newest");
assert_eq!(own_records(&js, &bucket, "ola").await.len(), 1, "nobody else's card is touched");
}