Compare commits

..
136 Commits
Author SHA1 Message Date
dckc bb1fbbdc00 build(diigo-cache): ship the docs, and name the commit a build came from
systemctl status's Docs: line now leads to the README, at a profile
path that survives upgrades, and, for a build from a clean tree, to the
commit's source on git.inference.coop. The version ends in the short
rev (-dirty for a dirty tree), and share/doc/diigo-cache/REVISION holds
the full one. pnpmDeps keeps version 0.0.0, so a new commit doesn't
refetch the deps.

Generated-by: Claude Opus 5.5
2026-11-19 14:29:16 -06:00
dckcandClaude Opus 5.5 3c4915f5ad feat(good-fences): a chat page that shows the yard as it's mowed
The page talks to a Neighbor over the agent WebSocket: it sends chat
requests, shows the code the model runs and what came of it, and draws
the yard from the agent's state.

The yard is the Neighbor's state, so the page hears each move and a
yard survives eviction: the mower picks up where the saved yard left
off. Moves go out at most every 200ms, so a long run of pushes is not a
write per cell. Only the server may change that state; Agent state
otherwise accepts updates from any connected client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 23:29:21 -06:00
dckcandClaude Opus 5.5 76ec2c0019 feat(good-fences): a deploy config, with the loader codemode needs
Deploys the Neighbor agent as good-fences3. worker_loaders (Dynamic
Workers) is refused on the free plan, including Wrangler's temporary
accounts, so this deploys to a Workers Paid account with a token scoped
to this one Worker (.env, gitignored).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 23:18:55 -06:00
dckcandClaude Opus 5.5 9a15fb2a86 docs(diigo-cache): open issue 10, page storage drift
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 16:26:02 -05:00
dckcandClaude Opus 5.5 0116ccd0d2 docs(diigo-cache): open issue 9, observability
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-15 09:24:40 -05:00
dckcandClaude Opus 5.5 992e871c56 feat(diigo-cache): refresh each cache every 3 hours
workerd has no cron triggers, but it runs Durable Object alarms, and
the cache DOs already hold their wiring to the webapp: a refresh
scheduled from inside the DO needs no credential outside it (a systemd
timer would need a cache id to call /api with).

A fill that ends (done or failed) sets an alarm 3 hours out; it starts
a fill that refetches every page through the deepest one holding an
item updated in the last 2 days (page 1 at least, where new bookmarks
land). Refetching overwrites pages in place rather than dropping them
first, so a refresh that fails leaves the cache as it was. stopFill now
also stops a finished job's refreshes.

FillStatus gains refetchThrough (optional; additive). Caches whose fill
ended before this get their first refresh alarm when they next wake.

The service starts at boot as well as on the socket: alarms fire only
while workerd runs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 23:31:48 -05:00
dckcandClaude Opus 5.5 9cfc150f2c docs(capsite): UX map and checklist after first use on bldbox
The map predates search (1d) and showed no way to the public page once
the created page is gone; add both, and private search, which has no
home yet. 1h tracks the alignment work the map was input to. Goal 5
now records the bldbox deployment instead of wrangler deploy.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 23:12:47 -05:00
dckcandClaude Opus 5.5 857816166e feat(diigo-cache): production deployment with tailscale, systemd, and nix
diigo binds the session cookie to the IP it was issued to, so a
Cloudflare deployment can't use a cookie minted in the browser. Run
diigo-cache and webapp in one workerd on bldbox instead.

The flake bundles each worker with wrangler's dry run, so the modules
match what `wrangler deploy` ships, and generates the workerd config
from the bundles. workerd comes from nixpkgs' wrangler, the only
packaged one. A smoke check serves the home page and mints a webapp
instance, which covers the WEBAPP binding and Durable Object storage.

The service is a system unit with DynamicUser, so the webapp state
holding the cookie isn't readable by processes running as the user.
It listens on loopback behind tailscale serve: HTTPS, which
PasswordCredential needs, at the tailnet name only.

Operator docs in doc/; unsettled points recorded as IBIS issues.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 23:12:47 -05:00
dckcandClaude Opus 5.5 9c3eaa9819 capsite/docs: Good Fences slides as presented
Dan's edits in HackMD, with image links pointed back at the PNGs beside
the deck. cookie-rotation-wiring.png comes along from the
webapp-cookie-rotation branch so the deck's images all resolve on main.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 14:04:39 -05:00
dckcandClaude Opus 5.5 cbb59ad3bc capsite/docs: Good Fences slides: TADA images fit the slide
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 12:33:13 -05:00
dckcandClaude Opus 5.5 ef2d71bfc3 capsite/docs: Good Fences slides: 🎉 for the TADA
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 12:29:39 -05:00
dckcandClaude Opus 5.5 85f91a9da1 capsite/docs: Good Fences slides: diigo is the tension (#23, 2016), potluck the TADA
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 12:29:35 -05:00
dckcandClaude Opus 5.5 c1c7a10f9b capsite/docs: Good Fences slides: TADA in two, diigo then potluck
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 12:28:20 -05:00
dckcandClaude Opus 5.5 a550a6aa34 capsite/docs: Good Fences slides: TADA frame from the Loom
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 12:25:21 -05:00
dckcandClaude Opus 5.5 5fa4d2800f capsite/docs: Good Fences Make Good Agents slides (hackmd)
A flashback deck: the weekly roundup drafts itself, how it's wired, the
toybox it belongs to, the mower as the toy version, the high of Project
Think and the low of JSON tool calls without durable, passable
references. Slides show challenges; they don't pose questions.

Images are relative paths; cookie-rotation-wiring.png is on the
webapp-cookie-rotation branch. Upload both to hackmd.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 12:17:21 -05:00
dckc 7cd6d0af01 capsite/docs: weekly-roundup wiring diagram, as on main
Who holds what in the S1 pipeline as it runs in dev: Alice's cache id,
the one-shot wiring to a webapp access whose init.headers carry the
cookie, and diigo-week reaching only the public cache's viewer. Drawn in
the style of cookie-rotation-wiring.html (webapp-cookie-rotation
branch), to contrast with it: on main a fresh cookie means a new access
and a new cache.

Generated-by: Claude Opus 5.5
2026-10-09 12:17:21 -05:00
dckcandClaude Opus 5.5 1fb01b3d55 capsite: docs: learn by watching — an agent finds a site's hidden API
Diigo needed devtools spelunking; sketch handing a browser debug
capability to an agent that watches, records sanitized fixtures, and
writes small deterministic steps behind a policy facet.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 02:45:59 -05:00
dckc 1d8a220bbc capsite: checklist: 2-iv, the weekly draft works in dev
Generated-by: Claude Opus 5.5
2026-10-09 02:12:41 -05:00
dckc 68132ff4b3 diigo-week: a dashboard card drafts last week in one click
The card shows last week's issue with a link to it, or a button to
draft it. Drafting a week that already has an issue (draft or
published) is refused, with a link to that issue, rather than making
a duplicate.

Generated-by: Claude Opus 5.5
2026-10-09 02:12:41 -05:00
dckc 9c09e8c5a4 capsite: checklist: 4b, consider scruffier tags
Generated-by: Claude Opus 5.5
2026-10-09 02:12:41 -05:00
dckc 94a059af25 diigo-week: draft a potluck issue from a week of diigo bookmarks
An EmDash plugin (native, content:write only) with one admin page:
a diigo username and an ISO week. It reads diigo-cache's public page
(?in=<week>&by=created) as microformats, follows rel=next, and
creates a draft in issues shaped like seed/issues.json.

Transport is a DIIGO_CACHE service binding rather than ctx.http.fetch:
EmDash's SSRF guard refuses localhost, and the binding names one
worker. Logic lives in src/week.ts with the fetcher passed in; tests
read fixtures in diigo-cache's markup. The checklist's goal 2 now
names potluck; DiigoBridge waits.

Generated-by: Claude Opus 5.5
2026-10-09 02:12:41 -05:00
dckc be796d9d0d diigo-cache: the public page is an h-feed of h-entry bookmarks
Microformats are the public page's API for other sites (potluck
first): each bookmark is an h-entry with u-bookmark-of, p-name,
p-summary, a p-category per tag (linked to a tag search),
dt-published (bookmarked) and dt-updated (last edited). Prev/next
links carry rel=prev/next, so a reader can follow a filter's pages.
Tests parse the page with microformats-parser to pin the contract.

Generated-by: Claude Opus 5.5
2026-10-09 01:49:40 -05:00
dckc c66aaea366 potluck, diigo-cache: docs one line per paragraph; potluck deploy caveat
Obsidian and GitHub render each newline as a line break, so the
hard-wrapped READMEs and CONTRIBUTINGs rendered ragged. Whitespace
only, except a note in potluck's CONTRIBUTING that other workerd
hosts are untested: they'd have to supply the D1 and R2 bindings.

Generated-by: Claude Opus 5.5
2026-10-09 01:30:56 -05:00
dckc a25bd699e1 potluck: README: workerd, not a vendor
Generated-by: Claude Opus 5.5
2026-10-09 01:29:31 -05:00
dckc ea3e256bb8 diigo-cache: README: workerd, not a vendor
Generated-by: Claude Opus 5.5
2026-10-09 01:28:50 -05:00
dckc 0af7a3ea6c diigo-cache: README sells and gets to TADA; CONTRIBUTING updated
New README: two sentences, the dev run through connect, fill, and a
filtered public page, then features. CONTRIBUTING gains the 1d
filters and its own run and deploy sections instead of pointing at
the checklist; links to the old README now point at CONTRIBUTING.

Generated-by: Claude Opus 5.5
2026-10-09 01:27:45 -05:00
dckc 9719fd0aa8 diigo-cache: README becomes CONTRIBUTING; AGENTS.md links to it
Generated-by: Claude Opus 5.5
2026-10-09 01:27:12 -05:00
dckc bce2424cc0 potluck: README: a heading that says something
Generated-by: Claude Opus 5.5
2026-10-09 01:25:47 -05:00
dckc 7f1e19fe85 potluck: README: two sentences, then getting started, then features
Generated-by: Claude Opus 5.5
2026-10-09 01:25:13 -05:00
dckc 8a812d76e3 potluck: README sells and gets to TADA; CONTRIBUTING has the rest
The README was EmDash's template blurb. Now it says what potluck is
and its first block runs from a fresh clone to /issues, using a new
`pnpm seed:issues` script that applies seed/issues.json to the local
D1 database. CONTRIBUTING covers how it's put together, seeds, checks,
the EmDash rules, and deploying; the template's stale notes (Inter,
three-column articles) are gone. AGENTS.md is now a symlink to it.

Generated-by: Claude Opus 5.5
2026-10-09 01:24:10 -05:00
dckc 002f08b456 diigo-cache: date windows and search on the public page (1d)
/public/<username> takes days, after, before, in (year, month,
quarter, ISO week), by=updated|created, and q (words, "phrases",
#tags, -negation, gmail/Slack/GitHub date operators). JSON answers
echo the parsed filter; a malformed one is a 400.

Filters query the stored items in sqlite through the read-only
viewer instead of walking diigo pages: the public page keeps no
fetch authority, and a filled cache already holds every item.
Results say `complete` when every diigo page is stored; freshness
is 1f's head refresh. So the fetch budget and the O(log pages)
walk test go, and the fake deep account shrinks to 300.

Generated-by: Claude Opus 5.5
2026-10-09 01:17:03 -05:00
dckcandClaude Opus 5.5 efb54ad4cc docs: Good Fences Make Good Agents (design story + IBIS)
The story behind good-fences: lend a governed mower over the fence to a
neighbor whose tenants are model-written code, with the design IBIS
worked out so far. Previously an untracked note at the workspace root.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 01:00:15 -05:00
dckcandClaude Opus 5.5 8c110098ff feat(good-fences): a Think agent mows with a codemode mower connector
Neighbor is a Project Think agent on gpt-oss-120b. Its execute tool
runs model-written code in a dynamic worker; MowerConnector puts the
mower there as the `mower.*` namespace (start/push/turn/stop, each
taking an args object). makeMower is the Logo-turtle mower on a
wrapping yard; for now it lives inside the agent's DO.

Getting to green, one symptom at a time:
- chatted instead of acting: say it acts by running code
- reply cut mid-sentence: maxOutputTokens 4096 via beforeTurn
- execute failed creating codemode's runtime facet ("Incorrect type
  for the 'class' field"): declare CodemodeRuntime as a DO class
- looked for the mower in the workspace filesystem: activeTools
  ["execute"], and name the namespace in the prompt
- found the mower, then asked for lawn dimensions: "don't ask me
  questions: put it to use"

Green: 36 mower calls, a 30-cell rectangle.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 00:35:56 -05:00
dckcandClaude Opus 5.5 d61cb8c9a1 test(good-fences): lent a mower, a Think agent mows (red)
The first end-to-end test: a Project Think agent, on the real model,
writes code that runs in a dynamic worker and drives a mower; the test
counts the cells cut, and saves the turn to itest-output/.

Installs @cloudflare/think, @cloudflare/codemode, agents, ai,
workers-ai-provider, zod. The model-test worker now has a main entry,
the Neighbor DO, and a LOADER binding.

Red: src/worker.ts doesn't exist yet.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 00:31:25 -05:00
dckcandClaude Opus 5.5 a2ca59a27e feat(good-fences): code-mode prompt; the model writes code to mow
codeModeMessages turns what I say plus `about` into a prompt: a
neighbor persona, rules for the reply (one async arrow function over
`env`), and the lent things' types. Things are remote and calls on one
are delivered in order, so a lamp example shows pipelining: await only
for a value, or on a batch's last call. With only the rule, the model
awaited every call; with the example, it pipelines.

aboutMower gives the Mower type with Promise returns. The model test
checks the code calls only Mower methods, pushes, and awaits less often
than it calls; it saves the code to itest-output/ via a reporter, since
the test runs in workerd, which can't write files. Model tests get 60s.

Green: both model tests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 00:21:44 -05:00
dckcandClaude Opus 5.5 4a85143a66 fix(good-fences): give the model room to answer
gpt-oss-120b reasons before it answers, and Workers AI's default
max_tokens (256) ran out mid-thought: finish_reason "length", content
null. Ask for 4096, and when there's no reply text, say which choice
and message keys came back instead.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 00:21:44 -05:00
dckcandClaude Opus 5.5 37faa92649 test(good-fences): lent a mower, the model writes code to mow (red)
Code mode (2c): the harness turns what I say plus `about` into a prompt;
the model replies with `(env) => ...` code. Checked textually for now,
since workerd won't eval it: the code pushes `env.mower` and calls only
methods in `about`. It also prints the code, to see what the model writes.

Red: src/code-mode.ts doesn't exist yet.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 00:01:39 -05:00
dckcandClaude Opus 5.5 ec24f3e8e4 feat(good-fences): complete(messages) on a Workers AI model
makeWorkersAiModel narrows the AI binding to one model's chat
completion: the harness gets `complete`, not `run` on any model at
any cost. gpt-oss-120b replies in the OpenAI shape (checked with a
one-off probe), so the text is choices[0].message.content; anything
else throws, naming the keys it got.

Green: the model counts 3 rs in strawberry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 23:41:18 -05:00
dckcandClaude Opus 5.5 47a2337afe test(good-fences): the model counts the rs in strawberry (red)
A first integration test of the model call: Workers AI through the AI
binding, behind the same `complete(messages)` interface as the sim's
fake model. Opt-in (`pnpm test:model`) since it needs `wrangler login`
and costs money.

Red: src/model.ts doesn't exist yet.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 23:36:46 -05:00
dckcandClaude Opus 5.5 9b12943be4 test(good-fences): show which mower the neighbor gets
The chat and load arrows drew `things: { mower }` whether I lent the
raw mower or the governed one. Name objects by the reply arrow that
introduced them, so the diagram reads `things: { mower: governed }`
and lending the raw mower would fail the trace comparison.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 23:27:13 -05:00
dckcandClaude Opus 5.5 9a3e7348c6 test(good-fences): lend-the-mower journey (red)
The spec is a sequence diagram of the a2030.md story: I lend a governed
mower; the neighbor's harness shows the model only `about`, runs its
code as a tenant, and the governor stops the tipsy tenant at a 2-cell
fence. The test runs the actors through a causal tracer and compares
the trace with the diagram, then checks the yard and what the model saw.

The tracer comes from agoric-sdk PR #12895, extended to name
participants made mid-sequence (governor, tenant) and to draw thrown
errors as replies.

Red: src/ doesn't exist yet (ERR_MODULE_NOT_FOUND for src/fence.ts).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 22:17:48 -05:00
dckc b4ab820486 capsite/docs: references to DOs in Discord messages
How a Discord message could carry references to our DOs, after
@endo/chat: names in the text, references beside it in a mailbox DO,
an Adopt button answered ephemerally, and per-user petstores. Webkeys
in markdown work but disclose the capability to every channel reader
and to Discord itself; ephemeral replies still pass through Discord,
so references should never cross it at all.

Generated-by: Claude Opus 5.5
2026-10-08 16:19:45 -05:00
dckc 93d92d0207 capsite: checklist: run potluck, not madmode
The EmDash site is now potluck/, created fresh with create-emdash.

Generated-by: Claude Opus 5.5
2026-10-07 20:33:08 -05:00
dckc 1aeb3a21db capsite: toybox user stories and goals (T1-T3)
toybox-stories.md: the weekly roundup (#23), album-to-album sync
(endojs/playground#16), and drag-to-archive.org (#118), with the needs
they share. The checklist gains the toybox tree: a changed signal (T1),
Blockly composition by petname (T2), and confined code in Dynamic
Workers (T3).

Generated-by: Claude Opus 5.5
2026-10-07 20:33:08 -05:00
dckc a086a8c495 capsite: checklist: 1g, notes on public items are public too
The public cache keeps public items whole, private annotations and
comments included (2,525 of 14,645). Dan finds that acceptable; the
goal is to finish thinking it through, not to fix a leak.

Generated-by: Claude Opus 5.5
2026-10-07 20:33:08 -05:00
dckc 45223eb0b7 capsite: checklist: reconcile 1d with 1f; decide DiigoBridge's fate (2-iii)
1d's query.ts plans to filter while walking diigo's pages, but a filled
cache holds every item: choose before implementing. madmode's public
reads need no cache id, so DiigoBridge's cache-id TODO is moot unless a
private-reading caller wants it.

Generated-by: Claude Opus 5.5
2026-10-07 20:33:08 -05:00
dckc fd7fd5728d capsite/potluck: a weekly zine of issues, not a blog
- issues collection (ISO-week slug, week, dek, rich-text body); home,
  /issues, and /issues/<week> pages; seed/issues.json holds three
  sketched issues (W38-W40) from public diigo bookmarks, editorial
  lines marked (draft); issues-sketch.md is the dry run behind them
- microformats: h-feed of h-entry lists; an issue is an h-entry
  (p-name, dt-published, p-summary, e-content); off-site links render
  as h-cite, /tag/<tag> links as rel-tag p-category (CiteLink.astro)
- diigo tags: shown on each bookmark and attached to issues via the
  tag taxonomy (now posts + issues); /tag/<tag> lists issues
- demo blog content gone: posts dropped from the seed, home page lists
  issues, site title/tagline, footer About widget, and About page
  rewritten; nav is Home / About / Issues; search and RSS cover issues
- .column container gives potluck's pages the header's margins

Generated-by: Claude Opus 5.5
2026-10-07 20:31:54 -05:00
dckc b9f3156d6d capsite/potluck: plain style after kmjn.org's "Plain HTML with a few bureaucratic gestures"
https://www.kmjn.org/notes/modern_plain_html.html and its stylesheet:
system fonts (Verdana; no Google webfonts), one 800px column,
line-height 1.35, links in the text color with a dotted underline, no
rounding, shadows, or tracking; the header is plain, not sticky glass.
Token overrides live in theme.css; per-page scoped styles unchanged.

Generated-by: Claude Opus 5.5
2026-10-07 20:00:29 -05:00
dckc 4b4ef8fea6 capsite: potluck, a fresh EmDash site (cloudflare:blog out of the box)
pnpm create emdash@latest potluck --pm pnpm --install --yes, per
https://docs.emdashcms.com/ ("Create your first EmDash site"); the
--yes defaults are cloudflare + blog. Replaces the old madmode/
starter (never committed).

Generated-by: create-emdash 1.2.0, run by Claude Opus 5.5
2026-10-07 19:57:43 -05:00
dckcandClaude Opus 5.5 af8dd75fd1 capsite: public-origin candidate: sync (as in bib sync #195)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 13:03:27 -05:00
dckcandClaude Opus 5.5 45a2524542 capsite: more public-origin candidates: syndicate, peers
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 13:01:42 -05:00
dckcandClaude Opus 5.5 9dbf34efa7 capsite: pesos.madmode.com as the candidate public origin
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 13:00:40 -05:00
dckcandClaude Opus 5.5 9c3e6fa396 capsite: fedi-cache keeps the token; ActivityPub sources come later
The existing export (mastodon-archive) reads favourites, bookmarks,
and mentions, which ActivityPub doesn't carry. So the client API with
a narrow read-only token (held in webapp) is the primary source;
items are still keyed by ActivityPub uri, and outbox/follower-actor
sources move to a later portability goal.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 12:58:55 -05:00
dckcandClaude Opus 5.5 1e6436e089 capsite: social.coop tree at the ActivityPub level (fedi-cache)
Mastodon is one implementation; the cache speaks the protocol: outbox
for backfill, and fedi-cache as a follower actor so Update/Delete are
delivered rather than polled for. Its own keypair replaces an access
token, so webapp drops out of this one.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 11:16:05 -05:00
dckcandClaude Opus 5.5 99ce5b6964 capsite: goal trees for a zotero cache and a social.coop cache
Both follow the diigo-cache pattern (webapp holds the credential,
read-only and minted narrow at the source; the cache serves a public
page). Zotero's versioned sync answers diigo's stale-head problem;
Mastodon's doesn't announce edits/deletes, so its tree carries that
as a design question.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 10:21:24 -05:00
dckc 279ddb4caa fixup! diigo-cache: the public page only reads
Comments written for the reader: no restating what the shebang says, no traces of the design conversation; the publish comment no longer mentions a projection that no longer exists.

Generated-by: Claude Opus 5.5
2026-10-07 09:46:21 -05:00
dckc 7c0d1d62c6 fixup! diigo-cache: RSS in diigo's export shape, from cached items
Comments written for the reader: no restating what the shebang says, no traces of the design conversation; the publish comment no longer mentions a projection that no longer exists.

Generated-by: Claude Opus 5.5
2026-10-07 09:46:21 -05:00
dckc 697fd95514 fixup! diigo-cache: RSS in diigo's export shape, from cached items
compare-export.ts: the manual is a HELP string at the top of the module
(a docstring, as a value) and main prints it on bad usage. No reading
its own source, no regex, one copy; @file points at it.

Generated-by: Claude Opus 5.5
2026-10-07 09:44:26 -05:00
dckc 2055e8c1c9 fixup! diigo-cache: RSS in diigo's export shape, from cached items
compare-export.ts: the usage message comes from the @file manual's
synopsis line (read from the script's own source, on the bad-usage path
only), docopt-style, so the synopsis lives in one place; if the header
changes shape, it says "see the @file comment".

Generated-by: Claude Opus 5.5
2026-10-07 09:42:31 -05:00
dckc 8400078656 fixup! diigo-cache: RSS in diigo's export shape, from cached items
compare-export.ts: the manual drops "exits 2 on bad usage"; it's the
convention, and BAD_USAGE documents it.

Generated-by: Claude Opus 5.5
2026-10-07 09:40:47 -05:00
dckc a40d2e924a fixup! diigo-cache: RSS in diigo's export shape, from cached items
compare-export.ts: the usage exit status is a named constant,
BAD_USAGE = 2, whose JSDoc cites the convention (Bash Reference Manual
§3.7.5); the manual just says "Exits 2 on bad usage".

Generated-by: Claude Opus 5.5
2026-10-07 09:40:10 -05:00
dckc 549ff5bf4b fixup! diigo-cache: RSS in diigo's export shape, from cached items
compare-export.ts: exit 2 on bad usage is an external convention, so its
@file cites the source (Bash Reference Manual §3.7.5, Exit Status).

Generated-by: Claude Opus 5.5
2026-10-07 09:39:00 -05:00
dckc 9c99f4f969 fixup! diigo-cache: RSS in diigo's export shape, from cached items
compare-export.ts: as a program script, its @file is its manual
(purpose, usage, outputs, exit code), per docs-files-api's exception;
main's JSDoc keeps only the edge and attenuation.

Generated-by: Claude Opus 5.5
2026-10-07 09:37:31 -05:00
dckc 2bb18a9e96 fixup! diigo-cache: diigo counts pages from 0; migrate stored pages (schema v2)
Docs per the docs-files-api skill: a 1–2 line @file; what a declaration is or does in JSDoc on it, not in // comments or the file header.

Generated-by: Claude Opus 5.5
2026-10-07 09:34:06 -05:00
dckc 2a7d0ae0cb fixup! diigo-cache: SQL in .sql files, behind a read-only facet
Docs per the docs-files-api skill: a 1–2 line @file; what a declaration is or does in JSDoc on it, not in // comments or the file header.

Generated-by: Claude Opus 5.5
2026-10-07 09:34:06 -05:00
dckc ab195b51c4 fixup! diigo-cache: date windows and search, designed as skipped specs (goal 1d)
Docs per the docs-files-api skill: a 1–2 line @file; what a declaration is or does in JSDoc on it, not in // comments or the file header.

Generated-by: Claude Opus 5.5
2026-10-07 09:34:06 -05:00
dckc 11c4583a17 fixup! diigo-cache: bookmark cache in Durable Objects (goal 1c)
Docs per the docs-files-api skill: a 1–2 line @file; what a declaration is or does in JSDoc on it, not in // comments or the file header.

Generated-by: Claude Opus 5.5
2026-10-07 09:34:06 -05:00
dckc 2fc5cfb9ae fixup! refactor: rename diigo-dump to diigo-cache
Docs per the docs-files-api skill: a 1–2 line @file; what a declaration is or does in JSDoc on it, not in // comments or the file header.

Generated-by: Claude Opus 5.5
2026-10-07 09:34:06 -05:00
dckc 0a5de621ec fixup! diigo-cache: fill from a webkey page over Cap'n Web
Docs per the docs-files-api skill: a 1–2 line @file; what a declaration is or does in JSDoc on it, not in // comments or the file header.

Generated-by: Claude Opus 5.5
2026-10-07 09:34:06 -05:00
dckc 164d3cb8cb fixup! diigo-cache: the public page only reads
Docs per the docs-files-api skill: a 1–2 line @file; what a declaration is or does in JSDoc on it, not in // comments or the file header.

Generated-by: Claude Opus 5.5
2026-10-07 09:34:06 -05:00
dckc 2a1942fc2a fixup! diigo-cache: invalidate the last N days of cached pages
Docs per the docs-files-api skill: a 1–2 line @file; what a declaration is or does in JSDoc on it, not in // comments or the file header.

Generated-by: Claude Opus 5.5
2026-10-07 09:34:06 -05:00
dckc 76b9ed1494 fixup! diigo-cache: RSS in diigo's export shape, from cached items
Docs per the docs-files-api skill: a 1–2 line @file; what a declaration is or does in JSDoc on it, not in // comments or the file header.

Generated-by: Claude Opus 5.5
2026-10-07 09:34:06 -05:00
dckc 38d9ed4122 fixup! docs: goal tree aims at the weekly roundup (#23)
5-ii: rate-limiting is chiefly about /api now that public pages only read.

Generated-by: Claude Opus 5.5
2026-10-07 09:26:09 -05:00
dckc d857018e4b fixup! docs: diigo-cache UX map
The public page's write access is resolved: it reads through viewer().

Generated-by: Claude Opus 5.5
2026-10-07 09:26:09 -05:00
dckc d7190abaf8 diigo-cache: the public page only reads
/public/<username> reads through the cache's viewer() facet
(PageViewer: stored pages, knownTotal, fill progress — the reader
alone), so it can't fetch from diigo or write storage.

Behavior change, agreed beforehand: an unfetched page no longer fills
itself on a miss; it says "not fetched yet" (JSON: stored: false), and
the owner fills via the webkey page. The HIT/MISS line becomes "stored
<when>". Strangers can no longer make the cache spend the owner's diigo
session; the README's deployment concern shrinks to /api.

Tests: viewing an unfetched page makes no webapp call; the page appears
once stored; fill progress shows after one fill step.

Generated-by: Claude Opus 5.5
2026-10-07 09:26:09 -05:00
dckc a17d287e1d diigo-cache: SQL in .sql files, behind a read-only facet
No SQL text in the cache logic any more. Statements live in two files,
parsed by sqlStatements (`-- name:` sections, as in finquick's
brcal/gcbook.js) and imported as text (wrangler Text rule for *.sql):

- cache-read.sql: selects only, checked when the module loads
- cache-write.sql: schema, the v2 renumbering, etch, drops

store.ts turns them into two frozen facets with domain methods:
makeReader(sql) runs only the read statements (page, knownTotal,
deepestPageSince, pagesThrough); makeWriter(storage) only the write
ones (migrate, etch, dropPagesThrough), each change one transaction.

The cache migrates in its constructor under blockConcurrencyWhile, as
Cloudflare recommends, so readers never meet missing tables; the
migration test plants v1 storage and evicts to get a fresh activation.
A viewer() facet (PageViewer: stored pages and fill progress, from the
reader alone) is added for the public page.

Pure refactor: stored state and behavior unchanged.

Generated-by: Claude Opus 5.5
2026-10-07 09:24:33 -05:00
dckc 6dd7a37532 docs: diigo-cache UX map
capsite-notes gains a map of what a person can do in diigo-cache, where,
by which transport (HTTP route or Cap'n Web RPC), and with what
authority — a flowchart of the pages plus a table — marking the
misalignments: publish and dump are cache-key actions on HTTP forms, not
the RPC facet; the public page can write (a miss fills from diigo).
Input to aligning the admin UX with the RPC interface.

Generated-by: Claude Opus 5.5
2026-10-07 09:21:30 -05:00
dckc 0bffff8175 fixup! docs: goal tree aims at the weekly roundup (#23)
1c-vi: the cache proven complete against diigo's RSS export (and the
0-based page_num found on the way); 1e: the password-manager login;
1f: "invalidate the last N days" as today's stopgap; how-to-run: the
webkey page and compare-export.

Generated-by: Claude Opus 5.5
2026-10-07 09:06:55 -05:00
dckc 1a3bc14416 docs: goal tree aims at the weekly roundup (#23)
From the "Capsite checklist revisited" session: the root goal becomes
madmode publishing a weekly roundup of diigo bookmarks; goal 2 reads the
public cache (no credential on madmode's side); new 1f (stale head
pages must refresh); goals 3–7 restated around the weekly page,
deployment, cookie expiry, and bib sync.

Generated-by: Claude Code
2026-10-07 09:06:55 -05:00
dckc f3241e4985 fixup! diigo-cache: RSS in diigo's export shape, from cached items
compare-export.ts does its file I/O asynchronously (node:fs/promises;
main is async), so no sync-I/O precedent. The one exception says why:
node:sqlite has only DatabaseSync.

Generated-by: Claude Opus 5.5
2026-10-07 08:44:22 -05:00
dckc dc4f23ad04 fixup! diigo-cache: RSS in diigo's export shape, from cached items
compare-export.ts: Object.fromEntries(Object.entries(…).map(…)) as
objectMap(original, mapFn), with @endo/common's signature.

Generated-by: Claude Opus 5.5
2026-10-07 08:41:30 -05:00
dckc 21505a5b8f fixup! diigo-cache: RSS in diigo's export shape, from cached items
compare-export.ts runs main only under import.meta.main (Node's
`if __name__ == "__main__"`), so importing it — say, from a test —
runs nothing.

Generated-by: Claude Opus 5.5
2026-10-07 08:40:00 -05:00
dckc dfd9a3d1ef fixup! diigo-cache: RSS in diigo's export shape, from cached items
compare-export.ts per the ocap style guide (dckc/awesome-ocap,
style-guide/): main takes standard authorities under standard names as
default arguments — argv, fs, connect, now, stdout, stderr, exit (the
transitional form of _script_io) — and attenuates them itself:
connect(dbPath) to a read-only cacheItems, the output directory to an
outDir that writes only plain file names inside it. Counts go to
stdout (program output), usage to stderr.

Generated-by: Claude Opus 5.5
2026-10-07 08:36:57 -05:00
dckc d145841a2e fixup! diigo-cache: RSS in diigo's export shape, from cached items
compare-export.ts under ocap discipline: parseExport and compare are
pure; main is the program's edge and takes every power it uses (argv,
file reads and writes, the sqlite read, the clock, console, the exit
code) as default arguments. Nothing ambient at module level; the last
line just calls main().

Generated-by: Claude Opus 5.5
2026-10-07 08:34:02 -05:00
dckc 7be87d37dc chore: Update pnpm-lock.yaml
Generated-by: Claude Opus 5.5
2026-10-07 08:34:02 -05:00
dckc 0006c7c3a3 diigo-cache: lint typechecks the program scripts
scripts/tsconfig.json gives scripts/ node's types (@types/node, a new
devDependency) and allows the .ts import specifiers node's type
stripping needs; the worker's tsconfig still keeps node's types out.
pnpm lint runs it.

Generated-by: Claude Opus 5.5
2026-10-07 08:34:02 -05:00
dckc cbde0dfbd3 fixup! diigo-cache: RSS in diigo's export shape, from cached items
A diigo note item's body (note_content) renders first, as a Highlight:
line, as the export does: the 6 "export has notes, cache none" items
from the comparison were notes whose bodies the cache had all along.

Generated-by: Claude Opus 5.5
2026-10-07 08:31:07 -05:00
dckc 81f91a6747 fixup! diigo-cache: invalidate the last N days of cached pages
README: the invalidate control.

Generated-by: Claude Opus 5.5
2026-10-07 08:27:19 -05:00
dckc 904f620f06 diigo-cache: invalidate the last N days of cached pages
invalidateRecent(days) drops the cached pages holding anything diigo
updated within the last N days (on the cache's injected clock), and
every page before them, so the next read or fill refetches them; item
rows stay. Exposed on the fill capability (private and public) and on
the webkey page as "invalidate the last N days" per cache.

A user-requested refetch, not a change in what stored state means.

Generated-by: Claude Opus 5.5
2026-10-07 08:27:13 -05:00
dckc cffb1fa9b2 diigo-cache: diigo counts pages from 0; migrate stored pages (schema v2)
Comparing a cache with diigo's RSS export: the size-100 walk had missed
exactly the 100 newest bookmarks (everything updated since 2026-09-16).
diigo's page_num is 0-based, and we sent our 1-based page number
unchanged, so "page 1" was really page 2 and the newest page was never
fetched. diigo's total (16744) was right; the "total-overstated"
reading was a misdiagnosis.

- page() asks for page_num = n - 1
- BREAKING for stored state, agreed beforehand, migrated in place:
  schema v2 renumbers every stored page +1 (pages and page_members, via
  negation so no number collides), once, recorded as kv "schema" = 2;
  nothing is refetched, page 1 just becomes a miss
- fill jobs record their numbering; a job saved without it fails ("page
  numbering changed …; start the fill again") instead of resuming
- the fake pages from 0 like diigo (7 tests failed until the fix);
  tests feed v1-shaped storage and a v1-numbered job to the new code
- the next-page peek guard stays; its comments no longer claim diigo
  overstates its total
- the fixed test clock moves to 2099: pinned to "today" its alarms came
  due in real time and fired on their own

Generated-by: Claude Opus 5.5
2026-10-07 08:26:13 -05:00
dckc e6deb9fda0 diigo-cache: RSS in diigo's export shape, from cached items
src/rss.ts renders items as RSS 2.0 in the shape of diigo's RSS export:
title, link, and a description packing Tags:…;Description:…;
Annotations and Sticky notes:… (Highlight:/Sticky notes: lines). Unlike
the export it is well-formed (characters XML forbids are dropped; the
export carries some raw) and keeps whole titles (the export cuts at
255). Pure: dates come from the caller.

scripts/compare-export.ts (a program script: node, node:sqlite) loads a
cache's items, writes the RSS, and compares it with an export, keyed on
link, reporting counts by category.

Generated-by: Claude Opus 5.5
2026-10-07 05:22:12 -05:00
dckc 6af05190a6 chore: ignore export/ (diigo exports are personal data)
Generated-by: Claude Opus 5.5
2026-10-07 05:22:12 -05:00
dckc 4034fba76b diigo-cache: a fill ends at the first page past the data
Seen live: "filled: 168 of 1 pages". diigo's total overstated by 100
(16744 vs 16644), so the walk went on to page 168, which diigo answered
empty with a total ≤ 100; the fill recomputed its page count from that,
ceil(total/100) = 1.

Now a page whose own total says the data ended before it ends the walk,
with the count set to the last page with items ("167 of 167"). Judged
by total, not by items, since the public cache may keep none of a page
that isn't the end. The known-pages estimate ignores zero totals. The
fake answers past-the-end pages as diigo does (no items, total 0).

Generated-by: Claude Opus 5.5
2026-10-07 05:08:12 -05:00
dckc fd16c7db53 diigo-cache: pace diigo calls only; cache hits don't wait
page() ran the 500 ms pacing gate before the cache check, so every hit
waited too: a fill rerun skipping 166 cached pages took ~80 s and
looked like a start from scratch. The gate now sits after the hit
check (re-checking storage once through it, in case a request ahead
had just etched the page).

Regression test: the fixed-clock test cache records its sleeps; a miss
sleeps once, three hits add none (failed before: 4 sleeps).

Generated-by: Claude Opus 5.5
2026-10-07 05:06:17 -05:00
dckc f5d57f73d3 diigo-cache: a short page before the stated end peeks at the next page
The real fill failed at "diigo returned 44 items for page 167 of 168":
diigo's `total` overstates what load_user_items returns, so the true
last page looked short and the guard took it for a capped page size.

A short page that isn't the last by `total` now fetches the next page
(paced like any diigo call): empty means the data really ends there —
accepted, with a "total-overstated" notice logging total vs actual;
anything else means items would be skipped — refused, the message now
giving both counts. The fake gains an account whose total claims 60
more than it has; a fill on it runs to done.

Generated-by: Claude Opus 5.5
2026-10-07 05:04:04 -05:00
dckc f4b68f1b59 fixup! diigo-cache: bookmark cache in Durable Objects (goal 1c)
README: PAGE_SIZE is 100, diigo's cap.

Generated-by: Claude Opus 5.5
2026-10-07 04:59:39 -05:00
dckc 563cb83995 diigo-cache: page size 100, diigo's cap; fill jobs record their page size
Asked for 128, diigo returned 100 (the short-page guard caught it on the
first real fill), so PAGE_SIZE = 100: ~168 pages for 16.7k bookmarks.

The same run showed a fill job outliving a page-size change: progress
counted in 24s ("page 25 of 698") resumed as if counted in 128s. Stored
state reinterpreted, so: FillStatus records pageSize (additive; jobs
saved without it counted in 24), and a job whose size differs from
PAGE_SIZE fails with "page size changed …; start the fill again"
instead of resuming; starting again replaces it. Tested with the old
shape in storage.

Generated-by: Claude Opus 5.5
2026-10-07 04:59:39 -05:00
dckc 3baffcab4c fixup! diigo-cache: bookmark cache in Durable Objects (goal 1c)
README: page size is PAGE_SIZE (128), not 24.

Generated-by: Claude Opus 5.5
2026-10-07 04:57:01 -05:00
dckc 826153e35f diigo-cache: fetch 128 items per diigo page; refuse short pages
PAGE_SIZE = 128 (was 24), one constant for the fill job, public pages,
dumps, and DiigoBridge, so a cache never mixes sizes: ~131 pages instead
of ~698 for 16.7k bookmarks.

Cache invalidation, agreed beforehand: pages are cached by (page number,
size), so pages cached at 24 become misses and refetch at 128. Items are
keyed by link_id and just re-upsert; nothing is lost.

Unknown whether diigo honors count=128, so a short page that isn't the
last is refused loudly (logged, thrown; a fill fails with the reason)
rather than silently skipping items. The fake gains a capped account to
test it; the plain account grows to 300 (3 pages), the deep one to 6000.

Generated-by: Claude Opus 5.5
2026-10-07 04:56:56 -05:00
dckc efaf74023d diigo-cache: webkey page logs in with the password manager
/cache/ without a fragment is now a login form: petname
(autocomplete=username) and cache id (type=password,
autocomplete=current-password), the shape password managers fill from
the entries the save button makes. Its inputs have no name, so a native
submit (script failed) sends nothing; the key stays in memory, out of
the address bar and history. Home links to it.

Generated-by: Claude Opus 5.5
2026-10-07 04:48:15 -05:00
dckc 961515d8db fixup! diigo-cache: the caches take their clock as a constructor argument
Past the transitional idiom: the cache logic (DiigoCacheLogic,
PublicCacheLogic in cache.ts) requires its Clock, with no default, so
cache.ts reaches no ambient time. The worker's entry module is the
edge: it makes the live clock and exports the runtime-constructed
DiigoCache/PublicCache as (ctx, env) subclasses that supply it (the
Cloudflare constraint: the runtime constructs DOs with ctx and env
only). Binding class names are unchanged, so stored state is too. The
tests' FixedClockCache extends the logic class.

Generated-by: Claude Opus 5.5
2026-10-07 04:39:29 -05:00
dckc cf901ded5f fixup! diigo-cache: the caches take their clock as a constructor argument
No module-level liveClock: the live clock is made in the default
argument expression, at the edge where the runtime constructs the DO,
so module scope holds no powerful object.

Generated-by: Claude Opus 5.5
2026-10-07 04:35:39 -05:00
dckc b6823867ff diigo-cache: the caches take their clock as a constructor argument
Ocap discipline: no ambient time in logic. PagedCache reads time and
waits only through a Clock { now, sleep }, a default constructor
argument (the live clock; the runtime constructs DOs with ctx and env
only). The fill job's timestamps and alarms, the etch time, and the
diigo-call pacing all go through it.

Tests interpose through the constructor: tests/test-worker.ts (now the
tests' main module) adds FixedClockCache, bound as CLOCKED_DO, and a
test pins startedAt, updatedAt, and the alarm time to the fixed clock
(an ambient new Date() fails it).

Generated-by: Claude Opus 5.5
2026-10-07 04:34:48 -05:00
dckc 7d2100bf77 fixup! docs: goal tree and rules track the 1c cache
1e: the fill is driven from the webkey page over Cap'n Web.

Generated-by: Claude Opus 5.5
2026-10-07 04:32:44 -05:00
dckc 3706e6de2c fixup! docs: webkeys — ids as bearer capabilities, kept out of URLs
The cache page now follows the paper's form (fragment + skeleton page),
with the XHR replaced by a Cap'n Web call taking the key in-band.

Generated-by: Claude Opus 5.5
2026-10-07 04:32:44 -05:00
dckc 3d0e3aea69 chore: Update pnpm-lock.yaml
Generated-by: Claude Opus 5.5
2026-10-07 04:32:44 -05:00
dckc 8c221abe6f diigo-cache: fill from a webkey page over Cap'n Web
Starting a fill no longer POSTs the cache id to /_fill. Instead:

- the created page links the cache's webkey, /cache/#<cache id>: a
  skeleton page, the same for every key, that reads the key from the
  fragment (never sent to the server or in a Referer)
- its script trades the key in-band for a capability over Cap'n Web at
  /api: CacheApi.cache(key) returns a CacheCap facet (fill, status,
  fingerprint, the public companion's fill) and never the DO's wiring
  methods; malformed and unknown keys get one refusal that never echoes
  the key, and each refusal is logged without it
- then calls startFill(): trade and call pipeline into one round trip
- the worker serves capnweb's browser build itself at /_capnweb.js (a
  wrangler Text rule), so no third-party script sits beside the key

The /_fill route and its forms are gone. Tests run the real capnweb
client against the worker (fetch routed to worker.fetch).

Generated-by: Claude Opus 5.5
2026-10-07 04:32:44 -05:00
dckc fbe2538345 fixup! docs: goal tree and rules track the 1c cache
1e done: compressed to a pointer at the API and tests.

Generated-by: Claude Opus 5.5
2026-10-07 04:25:38 -05:00
dckc 31ded9735b diigo-cache: fill job — a button that grabs every page (goal 1e)
POST /_fill (cache id in the body; target private|public; action
start|stop) starts or stops a background walk of every diigo page into
the cache. DO alarms advance it pagesPerStep pages per step (default
20), a second apart; progress (FillStatus) is stored in the DO after
each page, so it survives eviction. Cached pages are skipped; starting
while running rejoins the job; a stop mid-step wins; a failure is
recorded with its reason and logged once. The created page gets fill
buttons; the public page shows "filling: n of m pages".

Fill state is new, additive DO storage (fill, fillStep): no existing
state changes meaning.

The 13 fill specs are unskipped and green, plus one: a fill makes one
diigo call per page fetched.

Generated-by: Claude Opus 5.5
2026-10-07 04:25:38 -05:00
dckc 530942f5d9 diigo-cache: dispose RPC stubs after each fetch; one fetch per miss
Two bugs in page()'s miss path, found while building the fill job:

- the webapp stubs (app, pathjoin, query) were never disposed, which
  kept the DO from being evicted (evictDurableObject hung after a single
  miss); they are now disposed once the page is in hand
- a miss on page n > 1 also fetched page 1 and threw it away, doubling
  diigo calls; every page carries `total`, so only page n is fetched

Regression test: a miss, then eviction, then a cache hit. tsconfig adds
the ESNext.Disposable lib for Symbol.dispose.

Generated-by: Claude Opus 5.5
2026-10-07 04:25:23 -05:00
dckc cf5ccce4e2 diigo-cache: fill job, designed as skipped specs (goal 1e)
A button that grabs every page into a cache: owner-only POST /_fill
(cache id in the body; target private|public; action start|stop),
advanced by DO alarms a few pages per step, progress stored in the DO
(new, additive state) so it survives eviction, cached pages skipped,
a rerun rejoins the running job, failures recorded and logged once.
The created page gets the button; the public page shows progress.

startFill/fillStatus/stopFill on PagedCache are JSDoc'd stubs; 13
specs are describe.skip until it lands (alarms driven by
runDurableObjectAlarm, eviction by evictDurableObject).

Generated-by: Claude Opus 5.5
2026-10-07 04:19:54 -05:00
dckc 3e5e139dea diigo-cache: date windows and search, designed as skipped specs (goal 1d)
The public page's filters, toward the weekly PESOS roundup (#23):
?days=N (7/30/90/365 presets), gmail-style after/before (UTC days,
half-open: after inclusive, before exclusive; yyyy/mm/dd accepted), and
q (words, "phrases", #tags exact against diigo's comma-separated tags,
- negation); q alone searches the last 365 days and says so; malformed
filters are a 400. Filtering walks diigo's updated-desc pages from 1 and
stops at the window, so ?days=7 costs one page.

src/query.ts is the typed, JSDoc'd API (stubs that throw); 22 specs are
describe.skip until it lands. The fake webapp gains a dated account.

Generated-by: Claude Opus 5.5
2026-10-07 04:19:54 -05:00
dckc 860bbee2b5 diigo-cache: public list shows each bookmark's date first
The list is in diigo's updated order; each item now leads with its
updated_at as Date#toISOString() (diigo sends epoch seconds; updatedISO
converts, tested), or "(no date)".

Generated-by: Claude Opus 5.5
2026-10-07 04:19:54 -05:00
dckc 80c9279825 diigo-cache: test that a cached page replays fetch-time order
A hit must replay diigo's order as fetched (page_members.pos), not a
column sort. The fake webapp's link_id and updated_at are scrambled so
neither column sorts back into diigo's order; ordering the replay by
updated or item_id fails the new test.

Generated-by: Claude Opus 5.5
2026-10-07 04:19:54 -05:00
dckc a1b1640e06 chore: Update pnpm-lock.yaml
Generated-by: Claude Opus 5.5
2026-10-07 04:19:54 -05:00
dckc 0cfa9d204e diigo-cache: own test toolchain; pnpm lint, pnpm test
vitest, @cloudflare/vitest-plugin, and typescript are devDependencies
here instead of being borrowed from diigo-bookmarks through hand-made
node_modules symlinks and a deep-path import.

- lint: wrangler types, then tsc over src/ and tests/ (Cloudflare's
  documented typecheck shape: regenerate types, then tsc)
- test: vitest run
- tests/tsconfig.json per the vitest-plugin docs; the dangling
  typecheck script (tsconfig.check.json never existed) is gone

Generated-by: Claude Opus 5.5
2026-10-07 04:19:54 -05:00
dckc 22ae9a2b61 build: tsconfig noEmit for diigo-cache and webapp
wrangler bundles; tsc only checks. Without noEmit a bare `tsc` wrote
compiled .js beside the sources (a stray webapp/src/index.js).

Generated-by: Claude Opus 5.5
2026-10-07 04:19:54 -05:00
dckc d0a9b899f2 docs: goal tree and rules track the 1c cache
- checklist: 1c (diigo-dump evolves into a bookmark cache) with its
  create-flow, id-wiring, and verification subgoals
- notes: diigo-cache replaces diigo-dump in What-we-built
- AGENTS: no worker secret since 1c; durable state — be LOUD and
  conservative about breaking changes to stored DB state; pointer to
  the workspace skills for commit trailers

Generated-by: opencode (GLM)
Generated-by: Claude Opus 5.5
2026-10-07 04:19:54 -05:00
dckc 6f409fc83a diigo-cache: bookmark cache in Durable Objects (goal 1c)
The dump worker becomes a page cache: a hit is served from DO SQLite
storage with no diigo call; a miss asks the webapp instance in the
cache's wiring and etches the page.

- two independent caches, one behavior (PagedCache): DiigoCache keeps
  every item; PublicCache keeps shared items only, dropping private
  rows before they are stored; served at /public/<username> (HTML page
  form, or JSON)
- create flow on one port: /_connect relays webapp's mint form, /_mint
  proxies the mint, /_wire wires a private or public cache; /_publish
  adds a public cache later
- ids are webkeys: kept out of URLs (POST bodies), shown and logged
  only as a hash fingerprint; saved to the password manager under the
  holder's petname (never sent to the server)
- items keyed on diigo's link_id; username from u_name; unkeyable
  items and every failure path are logged; each page read logs hit/miss
- tests run the real worker + DOs in the vitest pool against a fake
  webapp (tests/fake-webapp.js)

Generated-by: opencode (GLM)
Generated-by: Claude Opus 5.5
2026-10-07 04:19:54 -05:00
dckc c5e433cc9c docs: webkeys — ids as bearer capabilities, kept out of URLs
Close's web-key pattern (W2SP 2008) and its Waterken precursors, applied
to diigo-cache: cache ids are webkeys in substance; they travel in POST
bodies, never query strings, and a one-way hash (swissHash discipline)
stands in for them where log correlation is wanted.

Generated-by: opencode (GLM)
2026-10-07 04:19:54 -05:00
dckc cbf1435571 webapp: mint form servable by a proxying worker
wrangler's multi-config dev binds aux workers but doesn't serve their
HTTP, so diigo-cache relays webapp's own mint form:

- WebAppFactory gains fetch(): the HTTP surface over the binding
- GET /form?render=1 leaves the form action as a placeholder the proxy
  points at its relay; ?title= sets the page title
- a dedicated cookie field (sugar for the cookie header; must agree
  with the JSON if both are given)

Generated-by: opencode (GLM)
2026-10-07 04:19:54 -05:00
dckc 58be2ccaf8 refactor: rename diigo-dump to diigo-cache
Pure rename ahead of the dump worker's evolution into a bookmark cache
(goal 1c), so history follows the files. The diigo-login helper script
is dropped: the cookie now enters through webapp's mint form, never a
local script.
2026-10-07 03:25:56 -05:00
Connolly 2c7d8c9b4d docs: notes layering + goal reduced to confinement principle
capsite-notes: What-we-built gains the webapp/diigo-dump layers (links
to READMEs and the goal tree, not repeats); root Goal restated as
'confine the diigo secret to a small auditable piece behind an
attenuated interface' per discussion, with the dead API-key path noted
and details delegated to the tree; credentials section de-staled
(placeholder values, unconditional 401 finding, cookie-path direction);
private-bookmarks note no longer recommends the dead HTTP Basic path.
diigo-bookmarks/README: title corrected sandboxed->native with the
conversion note and a disclaimer that its Develop/Publish sections are
inherited scaffold text (larger rework deferred).

Generated-by: opencode (GLM)
2026-10-06 23:52:06 -05:00
Connolly fcb6ab9b0e docs: drop redundant 'the goal tree' section header
The whole doc is the goal tree; the H2 restated the title.

Generated-by: opencode (GLM)
2026-10-06 23:43:42 -05:00
Connolly 68f73e33c1 docs: capsite AGENTS.md for agent working rules
The hard rules move from the goal tree into a proper AGENTS.md at the
capsite root (discoverable by agents without reading the tree; the
workspace AGENTS.md's commit-trailer policy stays where it is, linked).
Checklist keeps a one-line pointer, so a continuation prompt still
surfaces them. Error hygiene (no header/param values in messages)
groups with secrets discipline there rather than as its own rule.

Generated-by: opencode (GLM)
2026-10-06 23:42:53 -05:00
Connolly c587481761 docs: de-duplicate run instructions, READMEs track current code
diigo-dump/README was stale three ways: described the pre-DO connect
flow (askpass + DIIGO_COOKIE, both retired), referenced deleted files
(src/webapp.ts), and named the old entrypoint. Rewritten against
current code (DiigoBridge, DO storage state surface, state-aware
/_connect); run/connect/deploy instructions now live only in the
capsite checklist, linked (intra-repo docs link rather than repeat).
webapp/README Run section: port note corrected (two-config run makes
diigo-dump the primary) and pointed at the checklist as the source.

Generated-by: opencode (GLM)
2026-10-06 23:42:02 -05:00
Connolly 079415b961 docs: capsite-notes references as descriptive links
Two prose referrals (preamble + root goal) and the Pointer bullet now
use [the capsite notes](capsite-notes.md) — descriptive, frontloaded,
context-free per the hypertext-links skill; no raw filename visible in
any anchor text. Also wrapped the bib-sync issue URL in the root goal.

Generated-by: opencode (GLM)
2026-10-06 23:39:56 -05:00
Connolly fa20b243be docs: pointers as descriptive links per STYLE.md; hypertext-links skill
Pointers section now uses [descriptive text](url) links with
frontloaded, context-free anchor text (intra-repo relative paths for
local docs; mm-diigo repo link for the provenance collection).

New opencode skill hypertext-links encodes the Prism
docs/research/STYLE.md link rules for reuse here.

Generated-by: opencode (GLM)
2026-10-06 23:38:03 -05:00
Connolly 945de95fd3 docs: API-key path marked dead per prior-session evidence
ses_eec320fe4ffehaMAn44U1nTKJU verified both real keys, all documented
auth schemes, and two endpoints -> 401 unconditionally, with historical
proof the same creds worked in 2024-2025 (13.5k bookmarks downloaded).
Goal 2 is now 'plugin rides the webapp cookie path', with the cookie-
rotation cost explicit (2-iii); the earlier DECISION POINT framing
('try a real key') contradicted that record and is removed.

Generated-by: opencode (GLM)
2026-10-06 23:36:18 -05:00
Connolly e1c3e9b5c6 docs: checklist to goal tree
Explicit tree semantics in the header: a goal is checked only when all
its children are (leaves: when verified). Architecture sketch moved out
(its content already lives in capsite-notes.md + per-worker READMEs;
duplicates would drift) — the tree's items carry just enough provenance
to stay self-contained. Adds 1b-i/1b-ii mint-loop subgoals and the 2-iii
decision point (API key vs cookie path for the plugin) surfaced this
session; hard rules + run instructions retained.

Generated-by: opencode (GLM)
2026-10-06 23:33:28 -05:00
Connolly 36bcf2e17d docs: checklist as a continuation prompt
Now carries the architecture sketch (webapp factory / diigo-dump
consumer / madmode site), the ladder state including what's verified
vs not (DO round trip still to exercise end-to-end), the run/how-to
commands, the hard rules learned this session (assistant never runs
dev servers; secrets discipline; error hygiene; wrangler types),
and pointers into the notes and provenance repos.

Generated-by: opencode (GLM)
2026-10-06 23:31:46 -05:00
Connolly 3f8e77eaa2 feat: webapp DO factory worker; diigo-dump as its consumer
webapp/ (new, site-agnostic, independently deployable):
- WebApp: fluent client (pathjoin/query/withHeaders/cookies/get/post)
  as RpcTarget; flower-style unions cite NuxiNL/flower v0.11 (Jan 2019);
  url/headers private (RpcTarget property reads are RPC); Error messages
  carry no header/param values; query-stripped URLs only
- WebAppDo: per-instance authority in DO storage (survives eviction);
  one-shot configure(), refuses different-url re-configure
- WebAppFactory: newWebApp(init) -> {id, app}, at(id); ids are bearer
  capabilities and are not logged
- HTTP surface: GET / mint form (secret header keys render blank),
  POST / mint (form or JSON), POST /at/<id> drive-by-capability
- types via wrangler types (worker-configuration.d.ts, gitignored)

diigo-dump/: now a webapp consumer. The diigo knowledge is only the
mint call: url=interact_api/, UA + x-requested-with, cookie, 500ms gate.
- src/webapp.ts, src/diigo-web.ts deleted (webapp's are canonical);
  diigo.ts slimmed to dumpBookmarks + PagedGet
- /_connect is state-aware: connect form pre-mint; health check
  (count=1 probe) + re-mint path post-mint; home-page link relabeled
- mint success page: narrow field + copy button (attribute-quoting
  fixed; id in x-diigo-web-id header for scripts)
- scripts/diigo-login: askpass flow, marked OBSOLETE (page flow is
  the primary); speaks the form protocol; writes only DIIGO_WEB_ID —
  the cookie lives in DO storage, never on disk
- package.json: dev = wrangler dev -c wrangler.jsonc -c ../webapp/...
  (verified: Ready on :8787, GET / 200, /_connect 200);
  wrangler ^4.148.0 devDependency after node_modules was cleaned

TODO(webapp) in webapp/README.md: proxy-page vs primary-worker mint
form; reconsider as the UI grows.

Generated-by: opencode (GLM)
2026-10-06 23:30:27 -05:00
Connolly 309f003fa3 feat(diigo-dump): fluent WebApp over RPC + bound fetch + logged errors
Restore the fluent client from mm-diigo's WebApp.js as RpcTarget classes
(src/webapp.ts): WebApp with pathjoin/query/withHeaders/cookies/get/post,
flower-style unions (NuxiNL/flower v0.11, Jan 2019 — merge only if no
shared key contradicts), pathjoin containment guard; RateLimitedWebApp
shares one gate across all derived handles, enforced at get/post only.
src/diigo.ts ports makeDiigoAPI and the dumpBookmarks generator.

RPC surface: DiigoService (WorkerEntrypoint) with open() handing a
rate-limited stub whose cookie is attached server-side only, and
dumpNdjson. Promise pipelining makes a whole chain a single round trip.

Divergences from the original for the RPC setting:
- url is a private field: a public property on an RpcTarget is readable
  by stub holders, and query strings can carry credentials
- Error messages carry no header/param values; URLs have query stripped
  (structured details via @endo/errors deferred until node_modules)
- fetch default is fetch.bind(globalThis): a detached fetch throws
  'Illegal invocation' in workerd (found live, fixed, verified 200)
- dumpPage/open log failures via console.error for observability

README documents config, RPC use, and each divergence.

Generated-by: opencode (GLM)
2026-10-06 22:13:58 -05:00
dckc 4a8828086e fixup! feat(diigo-dump): session-cookie dump worker, manual test passing
fixup: scrub failed API-key ping from checklist

diigo-ping never authenticated (Diigo 401); the working path is the
session-cookie dump worker. Renumber steps, note the scrub with the
reason, and drop the ping how-to.

Generated-by: opencode (GLM)
2026-10-06 21:36:44 -05:00
Connolly 830f9632de docs(diigo-dump): README with provenance, config, run, status
Documents the cookie-path worker: endpoint and headers mirrored from
the mm-diigo original, DIIGO_COOKIE secret setup (local .dev.vars vs
wrangler secret put), the inert-GET / POST-only-submit behavior, and
the manual test result (200, total 1674, 2026-10-06) with pointers to
the checklist and capsite notes.

Generated-by: opencode (GLM)
2026-10-06 21:33:42 -05:00
Connolly 126aab5cbe feat(diigo-dump): session-cookie dump worker, manual test passing
Port of mm-diigo/projects/diigo-bak/diigo-dump.mjs as a Cloudflare Worker:
one page-number field + button, GET interact_api/load_user_items
(sort=updated, count=24) with DIIGO_COOKIE as a Worker secret.
GET / is inert; dumps happen only on POST submit.

Manual integration testing (local wrangler dev, port 8788, 2026-10-06)
shows it works: status 200, total 1674 bookmarks, page-1 items returned.
The browser-session-cookie path authenticates; the static API-key path
(diigo-ping worker, EmDash plugin) is still rejected by Diigo (401).

Also: project checklist (capsite-checklist.md) with step results, and a
.gitignore for local artifacts (.dev.vars, node_modules, wrangler state).

Generated-by: opencode (GLM)
2026-10-06 21:33:25 -05:00
180 changed files with 41340 additions and 2072 deletions

No files matched your search

+12 -6
View File
@@ -1,7 +1,13 @@
.zig-cache/ # local working artifacts
zig-out/ .node_modules
zig-pkg/
.dfx/
node_modules/ node_modules/
.icp/ .dev.vars
*.key .env
.dev.vars*
dist/
.astro/
.wrangler/
worker-configuration.d.ts
emdash-env.d.ts# diigo exports: personal data
export/
result
+50
View File
@@ -0,0 +1,50 @@
# capsite working rules
Applies to AI agents working in `capsite/` (goal tree + how-to-run:
[capsite-checklist.md](capsite-checklist.md); background:
[the capsite notes](capsite-notes.md); workspace-wide policy:
[AGENTS.md](../AGENTS.md) — points to the workspace skills, incl. commit trailers).
## Dev servers are the user's job
The assistant never starts, stops, or restarts long-running dev servers
(`wrangler dev`, `pnpm dev`/`astro dev`). The user runs them and owns the
terminals; the assistant observes via `.tmp/capsite.script` (the `script`
capture; use `watchme`). One-shot codegen (`wrangler types`), linters,
typechecks, and tests are fine.
## Durable state: be LOUD and conservative about breaking changes
Persistence is a big deal here: DO ids (cache ids, webapp ids, public
ids) are headed toward representing real-world assets. A change that
leaves existing stored state unreadable, unreachable, or differently
interpreted is a **breaking change**, even in dev.
- **Before** making it, say so, prominently: what stored state breaks,
why, and the options (migrate, stay compatible, or reset). Get the
user's go-ahead; don't discover it after the fact.
- Prefer compatibility: read old shapes, add fields rather than repurpose
them, migrate in place (schema steps like `SCHEMA_V1` → `V2`).
- No silent resets. "Wipe `.wrangler/state`" is a last resort the user
chooses, never the default advice.
- Cover it with a test: old-shape state in, current code reads it.
(Prompted 2026-10-07: making `PublicCache` fetch through its own wiring
left public caches created by the earlier `ingest` code unwired — a 502,
and no way back through publish.)
## Secrets discipline
Worker secrets never in source or wrangler config. `.dev.vars` (gitignored)
locally; `wrangler secret put` deployed. Since the 1c cache evolution, no
worker secret is needed at all: the cookie lives only in the webapp DO's
storage; the webapp-instance id rides the cache DO's wiring; the cache id
is a user-held capability (password manager / per-POST paste). Error
messages must not contain header or param values (they cross RPC as
exceptions and land in logs); URLs appear query-stripped.
## Keep config types generated
Run `wrangler types` after any wrangler.jsonc change
(`worker-configuration.d.ts` is generated, gitignored; hand-rolled
`cloudflare:workers` shims drift and gave red squiggles).
-76
View File
@@ -1,76 +0,0 @@
# A Counter in a canister, over OCapN
An Internet Computer canister hosts counters as an [OCapN](https://github.com/ocapn/ocapn) peer: a client makes one, calls `incr` and `decr` on it over CapTP, pipelined, and keeps it in a home that survives a canister upgrade. Both peers are [glowcap](https://github.com/glowcap-org/glowcap) compiled to WebAssembly; this is an exploratory prototype for [vattr97#5](https://github.com/dckc/vattr97/issues/5), canisters as vats.
## Getting started
You need [Nix](https://nixos.org/) with flakes; it supplies Zig 0.17.1 and Node.
```sh
nix develop
(cd client && npm ci --ignore-scripts)
export DO_NOT_TRACK=1 # icp-cli reports usage by default
icp() { npx --prefix client icp "$@"; }
icp network start -d
icp deploy -y counter --args "(blob \"$(head -c32 /dev/urandom | od -An -tx1 | tr -d ' \n' | sed 's/../\\&/g')\")"
ID=$(icp canister status counter --id-only)
node client/counter.mjs http://127.0.0.1:4960 $ID alice.key init c1
icp canister install counter --mode upgrade -y
node client/counter.mjs http://127.0.0.1:4960 $ID alice.key use c1 incr value
```
The output shows each update call and each answer; after the upgrade, Alice's counter picks up where it left off:
```
start 329B -> 345B in 319ms
session open
deliver 551B -> 807B in 258ms
incr 1
incr 2
decr 1
deliver 180B -> 120B in 247ms
kept as c1
Canister counter installed successfully
start 329B -> 345B in 295ms
session open
deliver 363B -> 538B in 261ms
incr 2
value 2
```
With another key file, `use c1` breaks: that home is someone else's. `icp network stop` stops the local network. `zig build test` runs the same story in memory.
## Homes, not swiss numbers
Nodes on a canister's subnet can read its state, so a canister can't keep a swiss number secret. Authority here starts instead with the caller principal, whose signature the Internet Computer checks:
- `fetch("home")` answers the caller's own home, a durable store of named objects: `init(name, object)` and `get(name)`. It's made the first time the caller asks.
- `fetch("makeCounter")` answers the one public maker; `make()` answers a fresh counter at zero.
- The anonymous principal is refused, since everyone who uses it would share one home.
Homes, counters, and the canister's CapTP identity live in a [Loam](https://github.com/glowcap-org/glowcap) store whose engine ([stable_log.zig](src/stable_log.zig)) appends each committed transaction to stable memory, the part of a canister's state that survives an upgrade; `post_upgrade` replays it. CapTP sessions live in the heap, so an upgrade ends them, and a client starts a new one and fetches its home again.
## One update call per round trip
- **The wire.** The canister's Candid interface is two update methods, `start` and `deliver`, each taking and returning a `blob` of CapTP frames in Syrup byte-string envelopes, and an install argument of 32 bytes of entropy ([counter.did](counter.did)). The OCapN locator transport is `icp`, its designator the canister's principal.
- **Sessions.** The canister keeps one CapTP session per caller principal, so the Internet Computer's request signature is what tells sessions apart. `start` carries the caller's `op:start-session`.
- **Pipelining.** The client sends to an answer before it settles, so the handshake is one call and making a counter plus every send to it is another: about 2.6 s on mainnet, 0.6 s on icp-cli's local network. Keeping it with `init` takes a third, since the client passes only settled references as arguments.
- **Answer releases** (`op:gc-answer`) ride ahead of the client's next message rather than costing a call of their own.
- **No server push.** The canister can only answer what a call delivers; promise resolutions it learns of later would need a query to poll.
## Testnets
| Where | How | Update call | Notes |
| --- | --- | --- | --- |
| icp-cli local network | `icp network start -d` | ~250 ms | [icp-cli](https://cli.internetcomputer.org/) 1.8 succeeds dfx; state in `.icp/` |
| dfx local replica | `dfx start` (project-local network in [dfx.json](dfx.json)) | ~1.25 s | dfx 0.30 is deprecated; not in nixpkgs |
| Playground (mainnet) | `dfx deploy --playground` | ~1.2 s | free; canister reclaimed after 20 min; icp-cli has no equivalent |
| Mainnet | `icp deploy -e ic` | ~1.2 s | budget 1–2T cycles (about 1 XDR per T) per canister |
## Known gaps
- **The entropy is not secret** from the subnet's nodes, nor from whoever installs; nothing rests on it but the CapTP keys. A real deployment would draw it from `raw_rand` in a first call after install.
- **One session per principal.** A second `start` from the same caller traps until an upgrade clears sessions; a client that loses its session can't reconnect with the same key.
- **No removal or collection.** A home holds 8 names and can't drop one; Loam garbage collection never runs.
- **The canister pays for every call** and admits any signed caller; it should refuse strangers before doing work (`canister_inspect_message`).
- **Third-party handoffs** need gift ids from entropy and dials to other peers; the canister refuses both.
-50
View File
@@ -1,50 +0,0 @@
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const glowcap = b.dependency("glowcap", .{ .target = target, .optimize = optimize });
const test_step = b.step("test", "Run the unit tests and the in-memory client/canister round trip");
for ([_][]const u8{ "src/pair_test.zig", "src/candid.zig", "src/principal.zig", "src/stable_log.zig" }) |root| {
const t = b.addTest(.{ .root_module = b.createModule(.{
.root_source_file = b.path(root),
.target = target,
.optimize = optimize,
.imports = &.{.{ .name = "glowcap", .module = glowcap.module("glowcap") }},
}) });
test_step.dependOn(&b.addRunArtifact(t).step);
}
// The canister: freestanding 32-bit Wasm whose only imports are `ic0`.
const wasm32 = b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .freestanding });
const canister_glowcap = b.dependency("glowcap", .{ .target = wasm32, .optimize = .ReleaseSmall });
const canister = b.addExecutable(.{
.name = "counter",
.root_module = b.createModule(.{
.root_source_file = b.path("src/canister.zig"),
.target = wasm32,
.optimize = .ReleaseSmall,
.imports = &.{.{ .name = "glowcap", .module = canister_glowcap.module("glowcap") }},
}),
});
canister.entry = .disabled;
canister.root_module.export_symbol_names = &.{ "canister_init", "canister_post_upgrade", "canister_update start", "canister_update deliver" };
const canister_step = b.step("canister", "Build the canister to zig-out/bin/counter.wasm");
canister_step.dependOn(&b.addInstallArtifact(canister, .{}).step);
// The client peer, for a JavaScript host to drive.
const client = b.addExecutable(.{
.name = "client",
.root_module = b.createModule(.{
.root_source_file = b.path("src/client.zig"),
.target = wasm32,
.optimize = .ReleaseSmall,
.imports = &.{.{ .name = "glowcap", .module = canister_glowcap.module("glowcap") }},
}),
});
client.entry = .disabled;
client.rdynamic = true;
const client_step = b.step("client", "Build the client peer to zig-out/bin/client.wasm");
client_step.dependOn(&b.addInstallArtifact(client, .{}).step);
}
-13
View File
@@ -1,13 +0,0 @@
.{
.name = .icp_ocapn_counter,
.version = "0.0.0",
.fingerprint = 0xe943337525286da8,
.minimum_zig_version = "0.17.1",
.dependencies = .{
.glowcap = .{
.url = "git+https://github.com/glowcap-org/glowcap#349e2f9523096a0e77916511e10b1a9a9ba87119",
.hash = "glowcap-0.1.7-jdWOP7VktwB5muPJABefGNmsq-kOzfbNF4W3fBIykMby",
},
},
.paths = .{ "build.zig", "build.zig.zon", "src" },
}
+232
View File
@@ -0,0 +1,232 @@
# capsite goal tree
Nested checkboxes form the goal tree itself: each `- [ ]` is a goal; its
indented children are the subgoals/steps that must pass before it (an item
is only checked when **all** its children are checked — or, for leaf
items, when it has passed verification itself). Working notes live under
each goal; [the capsite notes](capsite-notes.md) carry the background
narrative.
- [ ] **madmode publishes a weekly roundup of diigo bookmarks**
([#23](https://github.com/dckc/madmode-blog/issues/23)); the diigo
session stays inside webapp, so madmode holds no credential at all
(background: [the capsite notes](capsite-notes.md); after that,
[bib sync #195](https://github.com/dckc/madmode-blog/issues/195))
- [x] Credential discipline: no worker secrets; the cookie lives only
in webapp's DO storage, ids are held by the user
([AGENTS.md](AGENTS.md), secrets section).
- [x] **1. Cookie-path dump worker**: port of mm-diigo's diigo-dump.mjs
(verified 2026-10-06: 200, `total: 1674`); evolved into 1c.
- [x] **1b. webapp DO factory** ([webapp/README.md](webapp/README.md));
mint verified end-to-end in dev 2026-10-07 (via 1c). Prod mint is
goal 5.
- [x] **1c. diigo-dump evolves into a bookmark cache**
([diigo-cache/CONTRIBUTING.md](diigo-cache/CONTRIBUTING.md); design in the
JSDoc of `src/cache.ts`, `src/index.ts`, `src/pm-save.ts`):
- [x] 1c-i. Two independent page caches, private and public
(`PagedCache`, `DiigoCache`, `PublicCache`).
- [x] 1c-ii. Create flow on one port: `/_connect` → `/_mint`
→ `/_wire` (`mintPage`, `proxyMint`, `wire`).
- [x] 1c-iii. Ids saved by explicit user action under the
holder's petname (`pmSave`); pages show a fingerprint
(`nick`).
- [x] 1c-iv. Verified against live diigo in dev, 2026-10-07:
create, dump, publish; `/public/dckc-madmode?page=4` →
`cache: HIT`.
- [x] 1c-v. Tests: `pnpm lint && pnpm test` (the real worker +
DOs against [a fake webapp](diigo-cache/tests/fake-webapp.js)).
- [x] 1c-vi. Complete: a filled cache holds everything in diigo's
RSS export (16,744 of 16,744; differences are form only),
2026-10-07, via `scripts/compare-export.ts`. Getting there
found diigo's `page_num` is 0-based (schema v2 migration).
- [x] **1d. Date windows and search on the public page**, toward the
weekly PESOS roundup of [#23](https://github.com/dckc/madmode-blog/issues/23)
(a week's permalink: `in=2026-W41`). One filter, two spellings:
devs pass `{ days: 7, q: "#weekly" }`, URLs the same fields;
`q` takes gmail/Slack/GitHub operators. UTC, ISO weeks, half-open
windows (`diigo-cache/src/query.ts`; `tests/query.test.ts`,
`tests/caches.test.ts` "public page filters"). Filters read
stored `items` only (the public page never fetches): results are
as fresh as the cache, and say `complete` when every diigo page
is stored. Keeping them fresh is 1f. 2026-10-09.
- [x] **1e. Fill job: a button that grabs every page** into a cache
from the webkey page `/cache/#<key>`, which trades the key for a
capability over Cap'n Web (`diigo-cache/src/api.ts`;
`startFill`/`fillStatus`/`stopFill` in `src/cache.ts`;
`tests/fill.test.ts`). `/cache/` without a key is a login form
the password manager fills.
- [ ] **1f. Cached pages go stale: the head must refresh.** A page hit
never expires, and diigo pages are updated-desc, so every new or
edited bookmark shifts the page boundaries: this week's bookmarks
sit on page 1, cached last week. Proposal: refetch the head
(pages from 1 until a fetched page's items are all already stored
with the same `updated`), upserting into `items` (already keyed by
`item_id`); the window/search reads of 1d run over `items`, not
over cached page numbers. A fill or a cron alarm (`ctx.storage`
alarm in the cache DO, not in madmode) can drive it.
**Durable state**: additive only if `pages`/`page_members` keep
their meaning; say so before changing them (capsite AGENTS.md).
Needs a test: an item added to the fake webapp shows up after a
refresh. Stopgap today: "invalidate the last N days" on the
webkey page (`invalidateRecent`), then fill.
- [ ] **1g. Policy: notes on public items are public too.** The public
cache drops private *items* (`publicOnly`) but keeps public items
whole, including annotations, comments, and sticky notes that
diigo marks private (`pri_a_count`/`pri_c_count`/
`pri_sticky_count`: 2,525 of 14,645 stored public items, found
2026-10-08), and `/public/<username>` JSON serves them. **Dan
finds this acceptable as is**; this goal is to finish thinking
it through, not to fix a leak. Open points: does diigo.com's
own public view hide them (so readers are surprised)? the
`comments` array may carry *other people's* words; which fields
does potluck quote (annotations are the best commentary: see
[the issues sketch](potluck/issues-sketch.md))? If the policy
changes, stripping stored rows is a durable-state migration.
- [ ] **1h. Align the UX with the RPC interface: every action findable, under the authority it needs.** Map and misalignments: [the UX map](capsite-notes.md#diigo-cache-ux-map-2026-10-07). First use on bldbox (2026-10-14) found search but no way there.
- [ ] 1h-i. Home links each public page in the username index.
- [ ] 1h-ii. The webkey page links its public companion's page.
- [ ] 1h-iii. Search private bookmarks from the webkey page: the 1d filters over the private cache's `items`, by RPC held by the cache key.
- [ ] 1h-iv. Publish and dump move from HTTP form routes to the webkey page's RPC.
- [ ] **2. potluck reads the public cache**: public data, so no capability, no cookie, no secret on potluck's side. The [diigo-week](diigo-week/README.md) plugin reads `GET /public/dckc-madmode?in=<week>&by=created` as microformats (an `h-feed` of `h-entry` bookmarks). Working in dev 2026-10-09; 2-iii postponed.
- [x] 2-i. Transport: the `DIIGO_CACHE` service binding in potluck's `wrangler.jsonc`, in dev too: the plugin's `ctx.http.fetch` refuses localhost (EmDash's SSRF guard), and a binding names one worker, not a host.
- [x] 2-ii. The page's microformats are the contract: diigo-cache's tests parse it with microformats-parser; diigo-week's tests read fixtures in the same markup.
- [ ] 2-iii. Decide `DiigoBridge`'s fate (postponed: nothing on this path uses it; it matters only for a caller that reads private items).
- [x] 2-iv. Run it in dev: diigo-cache and potluck both up; the dashboard card → a draft issue of 22 bookmarks for 2026-W40 (2026-10-09). The service binding resolves across the two dev servers.
- [ ] ~~**3. `/bookmarks` renders real data**~~: superseded by potluck's issues (the madmode starter is gone).
- [ ] **4. The weekly draft**: decided (2026-10-09): a draft issue you edit before publishing, made by diigo-week. The slug comes from the title (`week-2026-w40`).
- [ ] **4b. Consider scruffier tags.** EmDash tags are taxonomy terms (rows that must exist before use); diigo-week auto-creates them, so drafting feels scruffy, but the model is neat. Alternative: the inline `/tag/<tag>` links in issue bodies *are* the tags (matching the microformats `p-category` reading), and potluck's `/tag/<tag>` page finds issues by scanning bodies. Cost: no EmDash tag field or index; a scan over a few dozen issues a year is cheap. Open: does the admin's tag field let you type a new tag inline?
- [ ] **5. Deployed end-to-end**: on bldbox, tailnet only, not Cloudflare: diigo binds the cookie to the IP it was issued to ([operator docs](diigo-cache/doc/README.md)).
- [x] 5-i. webapp and diigo-cache in one workerd under systemd, via [the flake](diigo-cache/flake.nix); behind `tailscale serve` at `https://bldbox.tail09e44.ts.net/`. 2026-10-14.
- [x] 5-ii. Create against prod: cookie from a browser on bldbox, wired public, filled 168 pages. 2026-10-14. Rate limiting `/api` waits while only the tailnet reaches it ([open issue 4](diigo-cache/doc/open-issues.md)).
- [ ] 5-iii. madmode/potluck reads the public page from prod: no service binding off Cloudflare ([open issue 5](diigo-cache/doc/open-issues.md)).
- [ ] **6. Cookie expiry**: when diigo's session ends, head refreshes
fail; the public page keeps serving what's stored (say so on the
page, don't fail silently). Rotation is manual: re-mint via
`/_connect`. Open question: can an existing cache be re-wired to
a new webapp id (keeping its cache id and public username), or
does re-mint mean a new cache? Prefer re-wire — durable ids.
- [ ] **7. bib sync #195**: repeat the pattern for the next
read-access need (webapp mints for any origin; the cache's
item shape is diigo-specific): [the zotero goal tree](zotero-checklist.md).
The social.coop account is next after that:
[the social.coop goal tree](social-coop-checklist.md).
- [ ] **webapp graduates from prototype** (optional; only if it earns it)
- [ ] TODO(webapp): one canonical mint form — proxy-page (current) vs
running webapp as the primary worker so its own port serves the
form directly; revisit as the UI grows.
- [ ] @endo/errors for structured error details (needs node_modules).
- [ ] **toybox: typed pieces that fit together, peer to peer** (working
name; tinker toys per the madmode.com home page). Kinds are typed
interfaces, à la Genode session interfaces, but wired by
introduction (E's Granovetter diagram), not a parent tree; named by
petnames; each piece guards its own resources. Why:
[the toybox user stories](toybox-stories.md).
- [ ] **T1. Changed signal**: a reader can subscribe to "this cache
changed" instead of polling (Genode's ROM-session sigh is the
model: public cache ≈ ROM, `/_publish` ≈ report). Fires on 1f's
head refresh when it upserts anything new. Shape TBD: a Cap'n Web
callback stub the cache holds (live only), or a durable
subscription it calls back via a webkey (survives eviction).
- [ ] **T2. Compose with [Blockly](https://developers.google.com/blockly)**:
connector checks (`setCheck(kind)`) are the shapes; a workspace
is a set of introductions. **Blocks refer to capabilities by
petname**, never by key: workspace JSON is shareable; the keys
live with whatever runs it.
- [ ] **T3. Run compositions in [Dynamic Workers](https://developers.cloudflare.com/dynamic-workers/)**:
code from anywhere: Blockly's JS generator, code written by
agents, by hand. Confinement makes codegen safe: the Worker
Loader isolate's `env` holds only the stubs its petnames resolve
to, with `globalOutbound: null`, so the code's authority is
exactly what it was handed. (Ordinary Workers forbid `eval`;
lifting that is the point of the Worker Loader.)
## How to run (continuation prompts)
Dev (diigo-cache + webapp in one workerd):
cd ~/oros-bots/capsite/diigo-cache
pnpm dev # → http://localhost:8787
# webapp rides along (binding-only)
First connect (or re-connect after cookie expiry) — browser flow, two steps:
open http://localhost:8787/
# 1. "mint the diigo session at webapp" → webapp's own mint form
# (diigo-prefilled, served on :8787); paste the Cookie header from
# diigo.com devtools → mint (the cookie transits diigo-cache as an
# opaque relay into webapp's DO only)
# 2. the wire step: webapp id pre-filled, choose public|private →
# cacheId; copy the ids somewhere you control (password manager),
# paste the cacheId into the dump form
# (no .dev.vars, no restarts: ids ride the form POSTs / your paste)
Terminal flow (the same shape, scripted):
wid=$(curl -s -X POST http://localhost:8787/_mint --data-urlencode \
'url=https://www.diigo.com/interact_api/' --data-urlencode \
'headers={"user-agent":"Mozilla/5.0","x-requested-with":"XMLHttpRequest","cookie":"<paste>"}' \
--data-urlencode 'msPerCall=500' -D - -o /dev/null | grep -i x-webapp-id)
curl -s -X POST http://localhost:8787/_wire -H 'content-type: application/json' \
-d "{\"webappId\":\"<from $wid>\",\"mode\":\"private\"}"
Then: enter a page number, dump → JSON rows with a `cache: HIT/MISS`
line (a repeat page is answered from DO sqlite storage). GET / is inert
(dumps happen only on POST submits). Public pages:
/public/<username>?page=n (each page fills from diigo on first visit).
A private-only cache can be published later from its created page
(`POST /_publish`, cache id in the body).
Fill and invalidate a cache: http://localhost:8787/cache/ (log in with
the cache id from the password manager).
Checks: `cd diigo-cache && pnpm lint && pnpm test`. Against a diigo RSS
export: `node scripts/compare-export.ts <cache.sqlite> <export.xml> <out-dir>`.
potluck (EmDash site, fresh out of the box: `pnpm create emdash@latest
potluck --pm pnpm --install --yes` → cloudflare:blog, 2026-10-08, per
[Create your first EmDash site](https://docs.emdashcms.com/); replaces
the old madmode/ starter):
cd ~/oros-bots/capsite/potluck && pnpm dev # → :4321
# first run: the setup wizard at /_emdash/admin (site title, email)
# dev-bypass auth helper:
# /_emdash/api/setup/dev-bypass?redirect=/_emdash/admin
## Working rules
Agent working rules are in [AGENTS.md](AGENTS.md) — dev servers are the
user's job; durable state (loud about breaking changes); secrets
discipline; keep config types generated. They apply
to every goal in this tree.
## Pointers
- [the toybox user stories](toybox-stories.md) — what the pieces are for
- [the zotero goal tree](zotero-checklist.md) and
[the social.coop goal tree](social-coop-checklist.md) — the next caches
- [the capsite notes](capsite-notes.md) — the original goal and the EmDash
native-plugin wiring details
- [docs/webkeys.md](docs/webkeys.md) — the Waterken URL-capability
pattern, abstracted from the E-on-Java sources (bearer secrets,
YURL32, secret≠address); the reason ids ride only fragments and POST
bodies
- [docs/learn-by-watching.md](docs/learn-by-watching.md) — an agent
watches me use a site, then writes policy-bounded code for its hidden API
- [the mm-diigo diigo-bak scripts](https://github.com/dckc/mm-diigo) —
provenance of the fluent client and dump generator (`projects/diigo-bak/`:
WebApp.js, diigo-dump.mjs, diigo-interact.mjs; mm-diigo commit 7dbb367,
Oct 6 2026)
- [webapp/README.md](webapp/README.md) — HTTP + RPC surfaces of the
factory worker; open TODO on the mint-form placement
- [diigo-cache/CONTRIBUTING.md](diigo-cache/CONTRIBUTING.md) — the cache worker:
create flow, the two DOs, run/deploy details
+175
View File
@@ -0,0 +1,175 @@
`madmode.com` follows the "bake, don't fry" static site generator pattern, which avoids all sorts of security issues.
For years ([#23](https://github.com/dckc/madmode-blog/issues/23) was created in 2016) I have been wishing for a way to exercise read capabilities to get things like bookmarks as well as write access to put it on my site.
Let's give this a try:
- [EmDash 1.0: the stable CMS with a secure plugin registry | Cloudflare Blog](https://blog.cloudflare.com/emdash-cms-plugin-registry/) September 28, 2026
Goal: confine the code that has access to the diigo.com secret to a small,
auditable piece behind an attenuated interface (originally "the API key held
by the host, never inside the plugin"; the API-key path turned out dead —
see [the goal tree](capsite-checklist.md) for the current credential story).
If it works out well, we should be able to expand to [bib sync #195](https://github.com/dckc/madmode-blog/issues/195).
## What we built
- `webapp/` — site-agnostic Durable-Object factory for attenuated credentialed
web clients (fluent client, ids are bearer capabilities);
[webapp/README.md](webapp/README.md)
- `diigo-cache/` — the webapp consumer, evolved from the diigo-dump worker:
bookmark dumps cached in DO SQLite storage (private cache by unique id,
public-only cache by username-in-path); the mint call carries all diigo
knowledge; the cookie lives in the DO's storage (see
[the checklist's goal tree](capsite-checklist.md) for the verified/not-yet
split)
- `madmode/` — Cloudflare Workers EmDash site (Starter template), local dev via `pnpm dev`.
- `diigo-bookmarks/` — **native** EmDash plugin (converted from sandboxed):
- `src/index.ts` exports `createPlugin()` which returns `definePlugin({...})`.
- Declares `capabilities: ["network:request"]`, `allowedHosts: ["secure.diigo.com", "www.diigo.com"]`
(Diigo 301s `secure.diigo.com` → `www.diigo.com`; the host gate re-validates every redirect hop).
- Fetches `https://www.diigo.com/api/v2/bookmarks` with HTTP Basic auth into plugin storage,
serves a public JSON route, and has a Block Kit admin page ("Sync now" button + table).
- Site `/bookmarks` page renders the collected bookmarks (linked from the primary menu).
## diigo-cache UX map (2026-10-07)
What a person can do, where, and with what authority. Input to aligning
the admin UX with the RPC interface (checklist: the store refactor and
"align admin UX and RPC").
```mermaid
flowchart LR
home["/ home<br/>(no authority)"]
connect["/_connect<br/>mint form"]
wire["wire step<br/>(webapp id)"]
created["cache created<br/>(cache id)"]
login["/cache/ login<br/>(password manager)"]
admin["webkey page<br/>/cache/ + key in fragment"]
public["/public/username<br/>(anyone)"]
search["/public/username?q=…&in=…<br/>search, date windows"]
home -->|create| connect
connect -->|"POST /_mint (cookie)"| wire
home -->|"POST /_wire (webapp id)"| created
wire -->|"POST /_wire"| created
created -->|"POST /_publish (cache id)"| created
created -->|"open this cache"| admin
home -->|"open a cache"| login
login -->|"cache id"| admin
home -->|"dump: POST / (cache id + page)"| home
admin -->|"api.cache(key) …"| admin
created -->|"link (public mode)"| public
public -->|"GET form"| search
search -->|"GET form"| search
```
Updated 2026-10-14. There's no edge from home to public: once the created page is gone, you reach your public page only by typing its URL.
| action | where | transport | authority |
|---|---|---|---|
| mint the diigo session | `/_connect` | HTTP `POST /_mint` (relays webapp's form) | the cookie |
| wire a cache (private/public) | wire step, home | HTTP `POST /_wire` | webapp id |
| save the ids | created page | browser (copy, password manager) | — |
| publish later | created page | HTTP `POST /_publish` ⚠ | cache id |
| dump a page (raw rows) | home | HTTP `POST /` ⚠ | cache id |
| fingerprint, has-public | webkey page | RPC `fingerprint()`, `hasPublic()` | cache key |
| fill / stop / status | webkey page | RPC `startFill()`, `stopFill()`, `fillStatus()` | cache key |
| …of the public companion | webkey page | RPC `publicCache().…` | cache key |
| invalidate the last N days | webkey page | RPC `invalidateRecent(days)` | cache key |
| read public bookmarks | `/public/<u>` | HTTP GET (HTML or JSON) ⚠ | none |
| search, date windows (1d) | `/public/<u>` | HTTP GET `q`, `days`, `in`, `after`, `before`, `by` | none |
| find your public page | — ⚠ | — | none (the username index knows it) |
| search private bookmarks | — ⚠ | — | cache key |
| bulk dump for another worker | — | service binding `DiigoBridge.dumpNdjson` | worker config |
⚠ misalignments:
- publish and dump are admin actions held by the cache key, but live on
HTTP form routes rather than the RPC facet the webkey page uses
- ~~the public page can write~~ — resolved: it reads only through the
read-only `viewer()` facet; unfetched pages say so
- the webkey page has no dump or publish; the home page has no fill
- (2026-10-14, first use on bldbox) nothing links to `/public/<u>`: home doesn't list the username index, and the webkey page doesn't link its public companion's page
- search exists only on the public page; the private cache, which holds every item, has the raw page dump and nothing else. Private search belongs on the webkey page, held by the cache key (an RPC over the same `items` query `viewer()` runs)
## Native-plugin wiring (the part that took a while)
`emdash()`'s `plugins: []` takes **descriptors**, not plugin objects — the Astro
integration needs a module specifier it can statically import at build time:
```js
// astro.config.mjs
plugins: [{ id: "diigo-bookmarks", version: "0.1.0", entrypoint: "diigo-bookmarks" }]
```
The generated runtime module does `import { createPlugin } from "diigo-bookmarks"`
and calls it. `definePlugin(...)` results have no `entrypoint` and are rejected
with a build-time error. An in-config factory call also fails ("has no entrypoint").
Key facts verified from emdash source:
- `PluginContext` has **no `env`**. Worker secrets are read via dynamic
`import("virtual:emdash/env")` (generated module re-exports `cloudflare:workers`
`env` under @astrojs/cloudflare; `undefined` on other adapters).
- GET plugin routes get query params in `ctx.input` (a `PluginRouteQuery` record),
not `ctx.query` or `ctx.request.url` parsing.
- Admin (Block Kit) route: the admin frontend POSTs JSON
`{ type: "page_load", page: "<declared page path>" }` and button clicks as
`{ type: "block_action", action_id, page }` to `/_emdash/api/plugins/<id>/admin`;
the handler returns `{ blocks, toast? }`. CSRF requires the `X-EmDash-Request: 1`
header (the frontend sends it; curl must add it explicitly).
- Admin pages/widgets for **native** plugins must be declared in the plugin's own
`definePlugin({ admin: { pages: [...] } })` — the build descriptor's
`adminPages` is NOT merged into the manifest; the admin sidebar reads
`plugin.admin.pages` from the entrypoint's ResolvedPlugin. With `admin.pages`
set, the manifest reports `adminMode: "blocks"` and the sidebar gains
Plugins → Diigo Sync at `/_emdash/admin/plugins/diigo-bookmarks/sync`.
- `ctx.cron.schedule()` upserts, so calling it on every sync is a safe bootstrap
for configured plugins (which don't get a `plugin:activate` run by default).
- Local `.pnpm` hardlinks mean source edits reach the site only after a full
dev-server restart; if you delete a stale `node_modules/.vite/deps_ssr/*.js`
by hand the server 500s until `rm -rf node_modules/.vite` + full restart.
## Where the Diigo credentials go
The credential story moved twice; [the goal tree](capsite-checklist.md) is
authoritative. Current shape: the session cookie lives only in the webapp
DO's storage; `madmode/.dev.vars` still holds placeholder
`DIIGO_API_KEY` / `DIIGO_USERNAME` for the (dead) API-key path — both
documented schemes return 401 unconditionally, verified against both known
real keys (opencode session ses_eec320fe4ffehaMAn44U1nTKJU: `key=` param,
`key`+`user=`, and HTTP Basic, on both /api/v2/bookmarks and /api/v2/notes,
though the same creds downloaded 13.5k bookmarks in 2024–2025; diigo
evidently revoked v2 key auth). Deployed secrets: `cd madmode && pnpm
wrangler secret put <NAME>`; the sync rides the cookie path since the API
path died.
`EMDASH_ENCRYPTION_KEY` (in `madmode/.env` locally) is only needed for sandboxed
plugins' secret settings; the native plugin doesn't use it, but keep it backed up
for the site.
## How to run it
```bash
cd madmode
pnpm dev # → http://localhost:4321, admin at /_emdash/admin
# one-time auth helper (skips passkey):
# http://localhost:4321/_emdash/api/setup/dev-bypass?redirect=/_emdash/admin
```
- Admin page: `/_emdash/admin` → plugins → Diigo Sync → "Sync now"
- Public JSON: `/_emdash/api/plugins/diigo-bookmarks/bookmarks?limit=20`
- Site page: `/bookmarks`
- Sync also self-schedules via cron (`0 */6 * * *`), stored in `_emdash_cron_tasks`.
Note: private Diigo bookmarks need the session-cookie channel (which is what
the sync will use after goal 2; the API-key path is dead).
## Plugin dev loop
```bash
cd diigo-bookmarks
pnpm typecheck # tsc --noEmit
```
Then restart `pnpm dev` in `madmode/` (full stop + start; config/plugin changes
are not hot-reloaded through the .pnpm hardlink path).
-95
View File
@@ -1,95 +0,0 @@
#!/usr/bin/env node
/**
* @file Call the Counter canister over OCapN.
*/
const HELP = `usage: counter.mjs HOST CANISTER_ID KEY_FILE init NAME
counter.mjs HOST CANISTER_ID KEY_FILE use NAME [VERB...]
Open a CapTP session to the canister as the principal whose Ed25519 seed is
in KEY_FILE (32 bytes, made if missing), then:
init NAME make a counter, count on it (incr incr decr), and keep it in
your home under NAME
use NAME get the counter kept under NAME and send it each VERB
(incr, decr, value; default: incr value)
Each run's sends are pipelined: one update call after the handshake, plus
one for init. HOST is the replica, e.g. http://127.0.0.1:4960, or
https://icp-api.io.`;
import { readFile, writeFile } from 'node:fs/promises';
import { HttpAgent, Actor } from '@icp-sdk/core/agent';
import { Ed25519KeyIdentity } from '@icp-sdk/core/identity';
import { openPeer } from './peer.js';
/** The Candid interface in counter.did. */
const idlFactory = ({ IDL }) => {
const Frames = IDL.Vec(IDL.Nat8);
return IDL.Service({
start: IDL.Func([Frames], [Frames], []),
deliver: IDL.Func([Frames], [Frames], []),
});
};
/** The seed in `path`, or a fresh one written there. */
const keySeed = async path => {
try {
return new Uint8Array(await readFile(path));
} catch (err) {
if (err.code !== 'ENOENT') throw err;
const seed = crypto.getRandomValues(new Uint8Array(32));
await writeFile(path, seed, { mode: 0o600, flag: 'wx' });
return seed;
}
};
const main = async ([host, canisterId, keyFile, command, name, ...verbs]) => {
if (!name || !['init', 'use'].includes(command)) {
console.error(HELP);
process.exitCode = 2;
return;
}
const { hostname } = new URL(host);
const agent = await HttpAgent.create({
host,
identity: Ed25519KeyIdentity.generate(await keySeed(keyFile)),
// A local replica's root key is its own; mainnet's is built in.
shouldFetchRootKey: hostname === '127.0.0.1' || hostname === 'localhost',
});
const actor = Actor.createActor(idlFactory, { agent, canisterId });
const carry = async (method, frames) => {
const t0 = performance.now();
const reply = await actor[method](frames);
console.error(` ${method} ${frames.length}B -> ${reply.length}B in ${Math.round(performance.now() - t0)}ms`);
return reply;
};
const module = await WebAssembly.compile(
await readFile(new URL('../zig-out/bin/client.wasm', import.meta.url)),
);
const seed = crypto.getRandomValues(new Uint8Array(64));
const peer = await openPeer({ module, seed, carry }, canisterId);
console.log('session open');
const home = peer.fetch('home');
/** Send each verb without waiting, then print each answer. */
const countOn = async (counter, sends) => {
const answers = sends.map(verb => [verb, peer.send(counter, verb)]);
await peer.flush();
for (const [verb, answer] of answers) console.log(verb, peer.valueOf(answer));
};
if (command === 'init') {
const counter = peer.send(peer.fetch('makeCounter'), 'make');
await countOn(counter, ['incr', 'incr', 'decr']);
const kept = peer.send(home, 'init', name, counter);
await peer.flush();
peer.valueOf(kept);
console.log(`kept as ${name}`);
} else {
await countOn(peer.send(home, 'get', name), verbs.length ? verbs : ['incr', 'value']);
}
};
main(process.argv.slice(2)).catch(err => {
console.error(err);
process.exitCode = 1;
});
-227
View File
@@ -1,227 +0,0 @@
{
"name": "icp-ocapn-counter-client",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "icp-ocapn-counter-client",
"dependencies": {
"@icp-sdk/core": "6.1.1"
},
"devDependencies": {
"@icp-sdk/icp-cli": "1.8.0"
}
},
"node_modules/@dfinity/cbor": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/@dfinity/cbor/-/cbor-0.2.3.tgz",
"integrity": "sha512-5GX+9tAf29r94Pxv8nCzrv2/t+AkOfem/c/G61+FA2Wadq7THvc5cvr/AVLH0LpukVfNSWRRHvl1fkCdiB9MMQ==",
"license": "Apache-2.0"
},
"node_modules/@icp-sdk/core": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/@icp-sdk/core/-/core-6.1.1.tgz",
"integrity": "sha512-bMRKAJg0zwJyd53feg8D6Qd+ikoxrxzsVrvzmyjxgSwn7znKxBVyCN8GR/NEQ+dYaE+yWuXV0O3C8AiHL2JUqg==",
"license": "Apache-2.0",
"dependencies": {
"@dfinity/cbor": "^0.2.3",
"@noble/curves": "^2.2.0",
"@noble/hashes": "^2.2.0",
"@scure/bip32": "^2.2.0",
"@scure/bip39": "^2.2.0",
"asn1js": "^3.0.7"
}
},
"node_modules/@icp-sdk/icp-cli": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli/-/icp-cli-1.8.0.tgz",
"integrity": "sha512-5wdTxakBoYKqCVvApwlEgZZat9Y0qPxvrPVO31eAem2IO3+Xu3gn/k4EAHb9K9DTfCKyJ+Ll2O8Nm5GEPUldpQ==",
"dev": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"bin": {
"icp": "bin/icp.js"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"@icp-sdk/icp-cli-darwin-arm64": "1.8.0",
"@icp-sdk/icp-cli-darwin-x64": "1.8.0",
"@icp-sdk/icp-cli-linux-arm64": "1.8.0",
"@icp-sdk/icp-cli-linux-x64": "1.8.0",
"@icp-sdk/icp-cli-win32-x64": "1.8.0"
}
},
"node_modules/@icp-sdk/icp-cli-darwin-arm64": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-darwin-arm64/-/icp-cli-darwin-arm64-1.8.0.tgz",
"integrity": "sha512-4RO/r1p1h74wuePwat0vMPfYagzFO2CiYmAR33ZnrPfo22aGVcdwldpePZYBV8egjq7BMnI2LPY3UVLVHnSing==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/@icp-sdk/icp-cli-darwin-x64": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-darwin-x64/-/icp-cli-darwin-x64-1.8.0.tgz",
"integrity": "sha512-+/MDaDmleZ43kY14dvMHGxxSIW7Z+brccSqy6Vr+CwvRWqJcDG6QzwYXqk+owgLcmTrF11vufMhZbWN7n/yv0g==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/@icp-sdk/icp-cli-linux-arm64": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-linux-arm64/-/icp-cli-linux-arm64-1.8.0.tgz",
"integrity": "sha512-E/unBg0Kh8jfdf9IWVdbTP5FeMMtnQSDo1Cw+qb1WfX0lYYsFndS6bLW4KujKloETPKBwUPrH9gGc2AjDDhlKQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@icp-sdk/icp-cli-linux-x64": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-linux-x64/-/icp-cli-linux-x64-1.8.0.tgz",
"integrity": "sha512-f6NSdFIrr2eSmNe0JjQWedaiRkJWqCTbaS6GjZFbPtRnd52Eb+Ichrom2zmx/4CZ/DW71BfU9iE8D+OFTDsyow==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@icp-sdk/icp-cli-win32-x64": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@icp-sdk/icp-cli-win32-x64/-/icp-cli-win32-x64-1.8.0.tgz",
"integrity": "sha512-4x3JZwLljFNK67c3ClYDbluE2Lw98q5pE+Jomn0wq8MqGV/UqtQHdKeWqB73NWdeaeuGar3Hl15i81gxJJXAGg==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"win32"
]
},
"node_modules/@noble/curves": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz",
"integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==",
"license": "MIT",
"dependencies": {
"@noble/hashes": "2.4.0"
},
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",
"integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",
"license": "MIT",
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@scure/base": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@scure/base/-/base-2.4.0.tgz",
"integrity": "sha512-thZ1TuJwFwBblOhgsjDKvvGirBxNp+wSvY/DR6tJBJOTDhdAAcHJ8Vbr2eFnqaxeca4+t0i9KBf+uHYGWwZORg==",
"license": "MIT",
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@scure/bip32": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-2.4.0.tgz",
"integrity": "sha512-i3DS0CptAocyvqE4n3SUkpzeQK4vJMFwWLofTwRiiKo2aWojBOfyMCgfKw9HVpO6fSY5AK86sHS/Uzn8kK9Few==",
"license": "MIT",
"dependencies": {
"@noble/curves": "2.4.0",
"@noble/hashes": "2.4.0",
"@scure/base": "2.4.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@scure/bip39": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-2.4.0.tgz",
"integrity": "sha512-82dxFbZUYboyOf0AXiydsQrFQ5Q4h9mX+O2UkE91ROYmsc0BKMGZLwDmy96Jpa2+vrtoxomjUhy1RPIgH/r2nA==",
"license": "MIT",
"dependencies": {
"@noble/hashes": "2.4.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/asn1js": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz",
"integrity": "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==",
"license": "BSD-3-Clause",
"dependencies": {
"pvtsutils": "^1.3.6",
"pvutils": "^1.2.0",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/pvtsutils": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.8.1"
}
},
"node_modules/pvutils": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
"integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
"license": "MIT",
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/tslib": {
"version": "2.9.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
"integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
"license": "0BSD"
}
}
}
-11
View File
@@ -1,11 +0,0 @@
{
"name": "icp-ocapn-counter-client",
"private": true,
"type": "module",
"dependencies": {
"@icp-sdk/core": "6.1.1"
},
"devDependencies": {
"@icp-sdk/icp-cli": "1.8.0"
}
}
-119
View File
@@ -1,119 +0,0 @@
/**
* @file The client peer (`zig-out/bin/client.wasm`) driven over a canister's
* `start` and `deliver` update calls.
*/
const { freeze } = Object;
const decoder = new TextDecoder();
const encoder = new TextEncoder();
/**
* @typedef {(method: 'start' | 'deliver', frames: Uint8Array) => Promise<Uint8Array>} Carry
* one update call: the frames out, the frames in the reply
*/
/**
* Instantiate the client peer and open a session to `canisterId`.
*
* @param {object} io
* @param {WebAssembly.Module} io.module the compiled client.wasm
* @param {Uint8Array} io.seed 64 bytes of fresh entropy
* @param {Carry} io.carry
* @param {string} canisterId the canister's principal, as text
*/
export const openPeer = async ({ module, seed, carry }, canisterId) => {
const { exports: wasm } = await WebAssembly.instantiate(module, {
env: { report: (ptr, len) => console.error(readText(ptr, len)) },
});
const memory = () => new Uint8Array(wasm.memory.buffer);
const readText = (ptr, len) => decoder.decode(memory().slice(ptr, ptr + len));
/** Copy `bytes` into wasm memory for the length of `fn`. */
const withBytes = (bytes, fn) => {
const ptr = wasm.client_alloc(bytes.length || 1);
memory().set(bytes, ptr);
try {
return fn(ptr, bytes.length);
} finally {
wasm.client_free(ptr, bytes.length || 1);
}
};
const staged = () => memory().slice(wasm.client_out_ptr(), wasm.client_out_ptr() + wasm.client_out_len());
const check = (status, what) => {
if (status !== 0) throw Error(`${what}: ${decoder.decode(staged())}`);
};
/**
* Carry staged frames until the canister has nothing more to say. The
* first call of a session is `start`.
*/
let method = 'start';
const pump = async () => {
for (;;) {
const frames = staged();
if (frames.length === 0) return;
const reply = await carry(method, frames);
method = 'deliver';
check(withBytes(reply, wasm.client_feed), 'feed');
check(wasm.client_outbound(), 'outbound');
}
};
check(withBytes(seed, wasm.client_init), 'init');
check(withBytes(encoder.encode(canisterId), wasm.client_dial), 'dial');
await pump();
if (!wasm.client_session_open()) throw Error('session did not open');
const slotOf = (status, what) => {
if (status < 0) throw Error(`${what}: ${decoder.decode(staged())}`);
return status;
};
/** Stage what the Host queued, then carry it until the canister is quiet. */
const flush = async () => {
check(wasm.client_outbound(), 'outbound');
await pump();
};
/** Read a settled answer, or throw. */
const valueOf = slot => {
const kind = wasm.client_result_kind(slot);
if (kind === 0) throw Error(`answer ${slot} still pending after the canister went quiet`);
if (kind === 3) throw Error(`answer ${slot} broke`);
if (kind === 4) return undefined;
return kind === 2 ? Number(wasm.client_result_integer(slot)) : { slot };
};
/**
* An answer: what `fetch` or `send` will settle to. Sends can target one
* before it settles; nothing crosses the wire until `flush`.
*
* @typedef {{ slot: number }} Answer
*/
return freeze({
/** @returns {Answer} the capability published as `name` */
fetch: name => ({ slot: slotOf(withBytes(encoder.encode(name), (p, n) => wasm.client_fetch(p, n)), 'fetch') }),
/**
* Send `verb` to `target` with the arguments in `args`: at most one
* string, then at most one settled reference.
*
* @param {Answer} target
* @param {string} verb
* @param {...(string | Answer)} args
* @returns {Answer} `target`'s answer
*/
send: (target, verb, ...args) => {
const text = args.find(arg => typeof arg === 'string');
const object = args.find(arg => typeof arg === 'object');
const status = withBytes(encoder.encode(verb), (verbPtr, verbLen) =>
withBytes(encoder.encode(text ?? ''), (textPtr, textLen) =>
wasm.client_send(target.slot, verbPtr, verbLen, textPtr, text === undefined ? -1 : textLen, object ? object.slot : -1),
),
);
return { slot: slotOf(status, 'send') };
},
flush,
/** @param {Answer} answer */
valueOf: answer => valueOf(answer.slot),
});
};
-8
View File
@@ -1,8 +0,0 @@
// Each blob of frames is CapTP frames in Syrup byte-string envelopes.
// Install with 32 bytes of fresh entropy.
service : (entropy : blob) -> {
// Open the caller's session with its `op:start-session`.
start : (frames : blob) -> (blob);
// Carry later frames on the caller's session.
deliver : (frames : blob) -> (blob);
}
-14
View File
@@ -1,14 +0,0 @@
{
"version": 1,
"canisters": {
"counter": {
"type": "custom",
"build": "zig build canister",
"wasm": "zig-out/bin/counter.wasm",
"candid": "counter.did"
}
},
"networks": {
"local": { "bind": "127.0.0.1:4959", "type": "ephemeral" }
}
}
+49
View File
@@ -0,0 +1,49 @@
# diigo-bookmarks
A **native** plugin for [EmDash CMS](https://emdashcms.com) (converted from
the sandboxed scaffold; wired via the `plugins: []` descriptor list in the
site's astro.config — see [the capsite notes](../capsite-notes.md)).
Note: this README's Develop/Publish sections below are inherited from the
sandboxed scaffold and do not match the native wiring.
## Develop
```sh
pnpm install
pnpm run validate
pnpm run typecheck
pnpm run test
pnpm run build
```
To test against a running EmDash site, run `pnpm run dev` in this
directory (rebuilds on save) and `pnpm add file:../path/to/this`
in the site. Then `import diigoBookmarks from "diigo-bookmarks"` and pass
it into `emdash({ sandboxed: [diigoBookmarks] })`.
`pnpm run test` builds the plugin and runs its tests through Worker Loader using
EmDash's production sandbox wrapper and host bridge.
## Publish
```sh
pnpm run login -- alice.example.com
pnpm run publish # builds and uploads artifacts to your PDS
```
To publish from GitHub Actions, run `pnpm run release:setup`. The command
creates one shared workflow at the Git repository root.
## Version bumps
Bump `version` in `package.json` when you ship a release. The
scaffold's `emdash-plugin.jsonc` deliberately omits `version` —
the build pipeline reads it from `package.json` so there's a single
source of truth. **Bump major** for breaking changes, **bump minor**
for new routes or hooks, **bump patch** for fixes.
You MUST bump version whenever you change `capabilities`, `allowedHosts`,
or `storage` in the manifest. Installed users have consented to the
old trust contract; a change without a version bump would let new
behaviour slip past consent.
+1
View File
@@ -0,0 +1 @@
CONTRIBUTING.md
+72
View File
@@ -0,0 +1,72 @@
# Contributing to diigo-cache
diigo-cache is a Cloudflare Worker cache over [the webapp factory](../webapp/README.md): session-cookie reads of diigo bookmarks, cached in Durable-Object SQLite storage. Evolved from the diigo-dump worker (provenance: [mm-diigo `projects/diigo-bak/`](https://github.com/dckc/mm-diigo)); the static API-key path is dead (see [the capsite checklist](../capsite-checklist.md), goal 2 preamble).
## What it holds
- **The create flow, on one port**: `/_connect` renders webapp's own mint form (diigo-prefilled, cookie blank) — wrangler multi-config dev doesn't serve aux workers' HTTP, so `/_mint` relays the form opaquely into the WEBAPP binding (the cookie crosses; nothing on this side opens or logs it). Mint → `/_wire` (webapp id pre-filled, mode public|private) → the created page, where the user saves the ids.
- **Two independent page caches** (`src/cache.ts`), one behavior: a page hit is served from storage with no diigo call; a miss asks the webapp instance in the cache's wiring and etches the page.
- `DiigoCache` (binding `CACHE_DO`): every item. Addressed by its cache id.
- `PublicCache` (binding `PUBLIC_DO`): shared items only — private rows are dropped *before* etching (`publicOnly`), so its storage holds nothing private. Same cookie webapp as the private cache. Public page n is diigo page n, filtered (may show fewer than `PAGE_SIZE`, 100: diigo's cap). `/public/<username>` resolves through the `idFromName("index")` registry, and reads through `viewer()`, a read-only facet: it shows stored pages and fill progress, and can't fetch from diigo or write.
- **Storage**: SQL lives in `src/cache-read.sql` (selects only) and `src/cache-write.sql`; `src/store.ts` turns them into a reader and a writer facet, so the cache logic holds no SQL text.
- **Pages**: home's dump form (cache id + page number, POST) shows raw dump rows; `/public/<username>?page=n` shows an HTML list with a page form (JSON for `Accept: application/json`). Both say `cache: HIT` or `MISS`; every page read also logs `{event: "cache", kind, page, outcome}`.
- **Filters on the public page** (`src/query.ts`): `days`, `after`, `before`, `in` (`2026`, `2026-03`, `2026-Q1`, `2026-W41`), `by=updated|created`, and `q` (words, `"phrases"`, `#tag`, `-` negation, gmail/Slack/GitHub date operators). UTC, half-open windows. The same fields work as a dev-side spec (`toQuery({ days: 7 })`). A filter queries the stored `items` table through `viewer()`, never diigo: results are as fresh as the cache, and JSON says `complete` when every diigo page is stored.
- **Publish later**: `POST /_publish` (cache id in the body) wires a public companion to a private-only cache.
- **The webkey page and Cap'n Web**: `/cache/#<cache id>` is a skeleton page, the same for every key; its script reads the key from the fragment and trades it in-band for a capability over [Cap'n Web](https://github.com/cloudflare/capnweb) at `/api` (`CacheApi.cache(key)` → a `CacheCap` facet: fill, status, the public companion; `src/api.ts`). The worker serves capnweb's browser build itself at `/_capnweb.js`.
- **Fill job**: walks every diigo page into a cache in the background — DO alarms, a few pages per step, progress stored in the DO (`startFill`/`fillStatus`/`stopFill`), driven from the webkey page; the public page shows progress. "Invalidate the last N days" there drops the cached pages holding anything updated that recently (`invalidateRecent`), so the next fill refetches them.
- The `DiigoBridge` entrypoint for other workers (its cache-id source is the goal-2 wiring TODO).
## State surface
Ids are **webkeys** ([the pattern](../docs/webkeys.md)): 256-bit bearer secrets that never ride a query string or path. The webkey page carries the cache id in the URL fragment (never sent to the server) and passes it in-band over Cap'n Web; forms carry ids in POST bodies; logs and pages show only a fingerprint (a prefix of the id's one-way hash).
- **The cache id**: the cache's read capability (bearer; not logged). Held by the user — saved to the password manager under a petname they choose (the username field; never sent to the server) — and passed per POST.
- **The webapp instance id**: the diigo-read capability; lives in each cache DO's wiring, arrives from the mint step.
- **The cookie**: lives **only in webapp's DO storage**; crosses the wire once, at mint time, as an opaque relay.
- **The public cache**: no capability — `/public/<username>` is public by design (a guessable URL; hiding the link doesn't hide the page).
Stored state is meant to be durable: see the breaking-change rule in [capsite AGENTS.md](../AGENTS.md).
## Deployment concern: rate-limit `/api`
Public pages only read storage, so strangers can't make the cache spend your diigo session. `/api` is keyed (a cache id is needed), but Cap'n Web pipelining makes calls cheap to send. Before exposing a deployment:
- rate-limit `/api` (and `/public/*`, which reads storage) — on Cloudflare, the [Workers rate-limit binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/) (keyed by client and/or username); on other workerd hosts, a rate limit in the proxy in front;
- run the fill job (goal 1e): public pages show only what's stored.
## RPC use (from another worker, same account)
```jsonc
// wrangler.jsonc of the caller
"services": [{ "binding": "DIIGO", "service": "diigo-cache", "entrypoint": "DiigoBridge" }]
```
```ts
// cache ids ride goal-2's wiring; see the capsite checklist
const ndjson = await env.DIIGO.dumpNdjson(4); // 4 pages of PAGE_SIZE
```
## Test
pnpm types # regenerate worker-configuration.d.ts (after wrangler.jsonc changes)
pnpm lint # fails if those types are stale; tsc over src/ and tests/
pnpm test # vitest
Tests run the real worker and both DOs in the vitest pool, with `WEBAPP` bound to [a fake webapp](tests/fake-webapp.js) serving diigo-shaped items (`wrangler.tests.jsonc`).
## Run
[The README](README.md) gets a cache going in dev. The same create flow from a terminal:
wid=$(curl -s -X POST http://localhost:8787/_mint --data-urlencode \
'url=https://www.diigo.com/interact_api/' --data-urlencode \
'headers={"user-agent":"Mozilla/5.0","x-requested-with":"XMLHttpRequest","cookie":"<paste>"}' \
--data-urlencode 'msPerCall=500' -D - -o /dev/null | grep -i x-webapp-id)
curl -s -X POST http://localhost:8787/_wire -H 'content-type: application/json' \
-d "{\"webappId\":\"<from $wid>\",\"mode\":\"private\"}"
Check a filled cache against a diigo RSS export: `node scripts/compare-export.ts <cache.sqlite> <export.xml> <out-dir>`.
## Deploy
On bldbox, tailnet only, via [the flake](flake.nix): see [the operator docs](doc/README.md). Cloudflare is out while diigo binds the cookie to the IP it was issued to ([open issue 1](doc/open-issues.md#-1-how-does-diigo-see-the-cookie-come-from-the-ip-it-was-issued-to)).
+26
View File
@@ -0,0 +1,26 @@
# diigo-cache
Your diigo bookmarks, cached in a [workerd](https://github.com/cloudflare/workerd) worker, with a public page you can filter by week: `/public/<you>?in=2026-W41`. Your diigo session cookie is stored in one Durable Object and nowhere else.
## Getting started
```sh
pnpm install
pnpm dev # → http://localhost:8787/
```
Then, in the browser:
1. **mint the diigo session at webapp**: paste the `Cookie` header from diigo.com (devtools, any logged-in request).
2. **wire** it, mode **public**. Save the cache id it shows (the password-manager button does this).
3. **open this cache** → **fill**, and watch it walk your bookmarks.
4. Visit `/public/<your diigo username>?days=7`.
## Bookmarks you hold, a page anyone can read
- **Filter by date and search:** `?days=7`, `?in=2026-W41` (ISO week, UTC), `?after=2026-01-01&before=2026-02-01`, `?by=created`, and `?q=` with words, `"phrases"`, `#tags`, `-negation`, and gmail-style `newer_than:7d`. Add `Accept: application/json` for JSON.
- **Private stays private:** the public cache drops private bookmarks before storing anything, so it never holds them.
- **Ids are capabilities:** the cache id is a bearer key you keep in your password manager. It rides URL fragments and POST bodies, never a path or query string, so it stays out of logs and history.
- **Cheap to read:** pages come from Durable Object SQLite storage, and a fill job in the background fetches each diigo page once.
Design and tests: [CONTRIBUTING](CONTRIBUTING.md). Running it on bldbox: [the operator docs](doc/README.md).
+19
View File
@@ -0,0 +1,19 @@
# Operating diigo-cache on bldbox
diigo-cache and [webapp](../../webapp/README.md) run together in one workerd on bldbox, reachable only over the tailnet at `https://bldbox.tail09e44.ts.net/`. Cloudflare doesn't work: diigo binds the session cookie to the IP address it was issued to, and Cloudflare's egress IPs aren't that address (see [open issue 1](open-issues.md#-1-how-does-diigo-see-the-cookie-come-from-the-ip-it-was-issued-to)).
```
browser on the tailnet
→ tailscale serve (HTTPS, bldbox.tail09e44.ts.net:443)
→ diigo-cache.socket (127.0.0.1:8790)
→ diigo-cache.service: workerd, DynamicUser
diigo-cache worker → state in /var/lib/diigo-cache/cache
webapp worker → state in /var/lib/diigo-cache/webapp (holds the cookie)
→ diigo.com
```
- [Install, upgrade, roll back](install.md)
- [Day to day: create a cache, logs, backups](operate.md)
- [Open issues](open-issues.md), in IBIS style
The build is [the flake](../flake.nix): wrangler bundles each worker as `wrangler deploy` would, [gen-config.sh](../nix/gen-config.sh) fills [the workerd config](../nix/config.capnp.in), and the [socket](../nix/diigo-cache.socket) and [service](../nix/diigo-cache.service) units ship in the package. workerd comes from nixpkgs' `wrangler`, which bundles a patched one; nixpkgs has no standalone `workerd`.
+81
View File
@@ -0,0 +1,81 @@
# Install, upgrade, roll back
Everything below runs on bldbox. Neither unit has been run under the system manager yet; the flake's smoke check runs the same build under workerd directly.
## Once: tailnet HTTPS
In the [Tailscale admin console DNS page](https://login.tailscale.com/admin/dns), enable MagicDNS (on) and **HTTPS Certificates** (off as of 2026-10-14: `tailscale status --json | jq .CertDomains` is `null`). HTTPS matters: the "save to password manager" button uses `PasswordCredential`, which browsers offer only in a secure context.
## Build and check
```sh
cd ~/oros-bots/capsite/diigo-cache
nix flake check # builds, then serves the home page and mints a webapp instance
out=$(nix build --no-link --print-out-paths .#)
nix/probe-unit.sh "$out" # serves it under the unit's syscall filter: "probe: ok"
```
The probe catches what the smoke check can't: the nix sandbox has no systemd, so it doesn't apply the unit's `SystemCallFilter`. The flake only sees files git tracks: `git add` new files before building.
## Install
The service runs whatever `/nix/var/nix/profiles/diigo-cache` points at, so the profile is also the GC root and the rollback history.
nix-env is spelled out in full because sudo's `secure_path` leaves out nix's profile.
```sh
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --set "$out"
sudo systemctl link /nix/var/nix/profiles/diigo-cache/lib/systemd/system/diigo-cache.{socket,service}
sudo systemctl enable --now diigo-cache.socket diigo-cache.service
sudo tailscale serve --bg --https=443 http://127.0.0.1:8790
```
`tailscale serve --bg` persists across reboots in tailscaled's state; `tailscale serve status` shows it.
## Verify
```sh
curl -sf https://bldbox.tail09e44.ts.net/ | grep -c _connect # 1+; first request starts workerd
systemctl status diigo-cache.service
```
On a 502, make sure `tailscale serve` finds something on 8790: `curl -sI http://127.0.0.1:8790/`. (The cache also answers 502 when it can't load a page from diigo; its body then says `could not load page`.) If workerd crashes on start, systemd stops retrying, then fails the socket too (`Result: service-start-limit-hit` in `systemctl status diigo-cache.socket`). After fixing the cause:
```sh
sudo systemctl reset-failed diigo-cache.socket diigo-cache.service
sudo systemctl start diigo-cache.socket
```
From another tailnet device, open `https://bldbox.tail09e44.ts.net/`. From off the tailnet, the name doesn't resolve and `100.89.146.23` doesn't route.
## Upgrade
```sh
out=$(nix build --no-link --print-out-paths .#)
nix/probe-unit.sh "$out"
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --set "$out"
sudo systemctl daemon-reload # in case the units changed
sudo systemctl restart diigo-cache.service
```
Durable Object state outlives the code: an upgrade whose schema change existing state can't read is a breaking change (see [capsite AGENTS.md](../../AGENTS.md#durable-state-be-loud-and-conservative-about-breaking-changes)). Back up first ([operate](operate.md#backups)).
## Roll back
```sh
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --list-generations
sudo /nix/var/nix/profiles/default/bin/nix-env -p /nix/var/nix/profiles/diigo-cache --rollback
sudo systemctl restart diigo-cache.service
```
## Update nixpkgs
`nix flake update` moves wrangler, and with it workerd. The flake names workerd's version (`version` in [flake.nix](../flake.nix)); if nixpkgs' wrangler bundles a different one, the build fails with `no workerd <version>`. Set it to the bundled version, which must be no older than the workers' `compatibility_date`.
## Remove
```sh
sudo tailscale serve --https=443 off
sudo systemctl disable --now diigo-cache.socket diigo-cache.service
sudo rm /nix/var/nix/profiles/diigo-cache* # state in /var/lib/private/diigo-cache stays
```
+173
View File
@@ -0,0 +1,173 @@
# Open issues
In [IBIS](https://github.com/dckc/vattr97/wiki/IBIS) notation: `?` issue, `?!` resolved, `?~` open with a fallback; `:` position, `:+` accepted, `:-` rejected, `:~+` fallback; `+` pro, `-` con; `!` to-do; `.` comment. Append; don't renumber.
### ?! 1. How does diigo see the cookie come from the IP it was issued to?
```
?! 1. How does diigo see the cookie come from the IP it was issued to?
. observed: minted from the browser, the cookie failed from Cloudflare
. unverified that IP is the only binding; the mint sends user-agent
"Mozilla/5.0", not the browser's, and that works in dev
: 1a. log in to diigo from a browser that shares bldbox's public IP
(same LAN, same NAT)
+ no setup if that's where the browser already is
- breaks when the browser roams (phone, laptop away from home)
! compare: curl https://ifconfig.me on bldbox and in the browser
: 1b. advertise bldbox as a tailnet exit node; route the browser through
it while logging in to diigo and copying the cookie
+ bldbox's IP by construction, from anywhere on the tailnet
- bldbox isn't an exit node (ExitNodeOption false, 2026-10-14);
needs `tailscale set --advertise-exit-node` and admin approval
:+ 1c. run the browser on bldbox
+ worked 2026-10-14: a cookie copied from Brave's devtools on bldbox
minted, wired public, and filled 168 pages
:- 1d. deploy to Cloudflare
- its egress IPs aren't the browser's (the failure that prompted this)
```
### ?~ 2. How is diigo-cache reachable only from the tailnet?
```
?~ 2. How is diigo-cache reachable only from the tailnet?
:~+ 2a. workerd on 127.0.0.1:8790; tailscale serve proxies
https://bldbox.tail09e44.ts.net/ to it
+ HTTPS with a real cert: PasswordCredential needs a secure context
+ tailscaled owns the tailnet address; no start-order dependency
- needs HTTPS certificates on in the tailnet (off as of 2026-10-14)
! enable in the admin console (install.md)
- every local user and process on bldbox reaches 127.0.0.1:8790 (see 3)
+ the cache id is still needed for anything private
: 2b. listen on 100.89.146.23 directly (ListenStream, FreeBind=yes)
- plain HTTP: the password-manager button fails
: 2c. tailscale serve to a unix socket only it can open
+ no loopback port
- unverified that tailscale 1.90.9 serve takes a unix socket target
? 2d. Which tailnet devices may reach it?
. today: every device on the tailnet (m5x, penguin, pixel-7, tiny-jwc)
: 2d-i. restrict to some devices with a tailnet ACL grant on bldbox:443
```
### ?~ 3. What account does the service run as?
```
?~ 3. What account does the service run as?
:~+ 3a. a system unit with DynamicUser=yes
+ the cookie's state is 0700 to a uid nothing else runs as; agents
and bots running as connolly can't read it
+ full sandboxing (systemd-analyze security: 2.2 OK)
- install and upgrade need sudo
: 3b. a user unit under connolly, with lingering
+ no sudo for upgrade; a ~/.local profile
- the cookie sits in connolly's files, readable by every process
connolly runs, Discord and opencode bots included
- Ubuntu's AppArmor userns restriction weakens user-manager sandboxing
- tailscale serve needs root (or `tailscale set --operator`) anyway
```
### ? 4. Does /api need a rate limit on the tailnet?
```
? 4. Does /api need a rate limit on the tailnet?
. CONTRIBUTING asks for one "before exposing a deployment"
:~+ 4a. not while only tailnet devices reach it (see 2)
: 4b. a rate limit in front of workerd before any funnel (see 5)
```
### ? 5. How does the weekly roundup read the public page?
```
? 5. How does the weekly roundup read the public page?
. the madmode blog build needs /public/<username>; where does it run?
: 5a. build on a tailnet device
: 5b. join CI to the tailnet (Tailscale's GitHub Action)
: 5c. tailscale funnel just /public/ to the internet
+ public pages are public by design
- exposes a guessable URL; needs 4b
```
### ? 6. How is state backed up?
```
? 6. How is state backed up?
:~+ 6a. by hand, service stopped (operate.md)
: 6b. a systemd timer
- backups hold the cookie: where do they go, encrypted how?
: 6c. none: the cache is a cache
- the ids people saved point at objects that would be gone
```
### ? 7. How does a cache get a fresh cookie?
```
? 7. How does a cache get a fresh cookie?
. a wired cache refuses a different webapp id
:~+ 7a. mint a fresh webapp instance and wire a new cache
- a new cache id to save
+ wiring public re-registers the username, so the public URL stays
: 7b. let webapp replace the cookie in an existing instance
+ cache ids stay put
```
### ? 8. Should `wrangler dev` state move to bldbox?
```
? 8. Should `wrangler dev` state move to bldbox?
. Durable Object unique keys follow miniflare's `<script>-<class>`,
so the per-object files may carry over; untested
:~+ 8a. start fresh on bldbox
+ dev cookies were minted for wherever dev ran (see 1)
: 8b. copy .wrangler/state/v3/do/<script>-<class>/ into the state dirs
```
### ? 9. What should we be able to observe, and how?
```
? 9. What should we be able to observe, and how?
. today: each worker console.logs objects ({event, ...}); workerd's
structuredLogging puts them in the journal (operate.md)
. gap: webapp logs only mint; a diigo request shows up only as the
cache's account of it ({event: "cache", outcome: "miss" | "refetch"}),
so no status, latency, or failure before the cache sees it
. the refresh (every 3h) is seen only by reading the journal
! survey practice before choosing: logs vs metrics vs traces, what to
alert on; Workers observability docs as a start
: 9a. log each diigo request in webapp: path, status, ms; no query
values or headers, so the cookie never appears
? 9b. how does anyone notice a refresh failing (expired cookie)?
```
### ? 10. Do we need to store diigo page numbers?
```
? 10. Do we need to store diigo page numbers?
. pages come from load_user_items with sort=updated, newest first; each
new or edited bookmark shifts the rest down one slot, a deletion up one
. only page 1 is refetched (every 3h, refetchThrough 1), so pages 2 and
on are snapshots from the first fill (2026-10-14)
. items are keyed by item_id; page_members records each page's positions
. consequences, seen 2026-10-29:
. k new bookmarks leave k items on no page: a gap in paged views
. an edited bookmark is listed on page 1 and at its stale position
. summing logged page items (16,767 private) counts snapshots, not items
. a deletion is never noticed; its row stays
. week views (?days=, ?in=) query items by date, so they're unaffected
: 10a. keep pages as stored snapshots (today)
+ read-through: viewing a page not yet filled fetches it
- the drift above
: 10b. store only items; a page number is just the fill's cursor
. each page-table read has a replacement:
. refresh depth (deepestPageSince): items updated since the cutoff,
/ 100, rounded up, + 1 page of slack for shifts
. invalidateRecent: not needed
. knownTotal: keep diigo's latest total as one kv value
. completeness (pagesThrough): a "full pass done" flag on the fill job
. paged public view: items order by updated desc, limit/offset
. page dump (HIT/MISS): fetch live; it's a debugging tool
+ paged views get no gaps or duplicates
+ last_seen per item: after a full pass, items not seen were deleted
or made private on diigo
+ fetched_at per item says more than pages.etched_at
- views past the filled part come back short until the fill gets there
- a schema migration
```
+48
View File
@@ -0,0 +1,48 @@
# Day to day
## Create a cache
As in [the README](../README.md#getting-started), at `https://bldbox.tail09e44.ts.net/` instead of localhost: mint, wire, save the ids, fill. Copy the cookie from a browser running on bldbox: diigo accepts it only from the IP it was issued to (see [issue 1](open-issues.md#-1-how-does-diigo-see-the-cookie-come-from-the-ip-it-was-issued-to)).
The public page is then `https://bldbox.tail09e44.ts.net/public/<diigo username>?days=7`, on the tailnet only.
## Logs
```sh
journalctl -u diigo-cache.service -f -o cat |
jq -Rr 'fromjson? | "\(.timestamp / 1000 | todate) \(.level) \(.message | gsub("\\s*\\n\\s*"; " "))"'
```
`fromjson?` skips lines that aren't JSON: systemd's own ("Started …") and entries from before `structuredLogging`.
workerd runs with `structuredLogging`: each entry is one line of JSON, `{timestamp, level, message}`. `message` is the logged object as `console.log` prints it, not JSON: on Cloudflare, Workers Logs indexes the fields of a logged object, so the workers log objects rather than strings.
workerd logs the workers' `console.*` output: `{event: "cache", kind, page, outcome}` per page read, `{event: "fill", state, …}` per fill step (a refresh logs `refetchThrough`), `{event: "mint"}`. Ids show only as fingerprints; the cookie never appears.
## State
With `DynamicUser=yes`, systemd keeps the state in `/var/lib/private/diigo-cache/` (`/var/lib/diigo-cache` is a symlink to it), mode 0700, owned by a uid that exists only while the service runs:
| Dir | Holds | Secret? |
| :--- | :--- | :--- |
| `cache/diigo-cache-DiigoCache/` | private caches: every bookmark | yes |
| `cache/diigo-cache-PublicCache/` | public caches and the username index | no |
| `webapp/webapp-WebAppDo/` | webapp instances: the diigo cookie | yes, a credential |
Each Durable Object is one `<id hash>.sqlite`. Read one with the service stopped, or copy it first: `sudo sqlite3 -readonly <file> .tables`.
## Backups
The private caches are refillable from diigo; the cookie can be re-minted. What's lost with the state is the binding from the ids people saved to these objects. Backups hold the cookie, so treat them as secret.
```sh
sudo systemctl stop diigo-cache.socket diigo-cache.service # the socket would restart it
sudo tar -C /var/lib/private -czf diigo-cache-$(date +%F).tgz diigo-cache
sudo systemctl start diigo-cache.socket
```
No backup is scheduled (see [open issue 6](open-issues.md#-6-how-is-state-backed-up)).
## The cookie expires
When fills log `{event: "fill", state: "failed"}` with a diigo auth error, mint a fresh webapp instance and wire a new cache. A wired cache refuses a different webapp id (`setup` in [cache.ts](../src/cache.ts)) (see [open issue 7](open-issues.md#-7-how-does-a-cache-get-a-fresh-cookie)).
+5 -5
View File
@@ -2,15 +2,15 @@
"nodes": { "nodes": {
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1794890597, "lastModified": 1791734076,
"narHash": "sha256-lME2lHoDHAaSHP3/okgiVoJ0icVEvsQH8LeU3We7tcc=", "narHash": "sha256-i5qk1kLiit98rRbh1AXmWBNT9QXC/y4l5Wk/u5EdpDQ=",
"owner": "nixos", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "04906337b6d53e8bb0eaf0470ae9f070a4d4eb55", "rev": "7fd4004d0511991fff3a0524856a9be09e28c5f0",
"type": "github" "type": "github"
}, },
"original": { "original": {
"owner": "nixos", "owner": "NixOS",
"ref": "nixos-unstable", "ref": "nixos-unstable",
"repo": "nixpkgs", "repo": "nixpkgs",
"type": "github" "type": "github"
+134
View File
@@ -0,0 +1,134 @@
{
description = "diigo-cache and webapp on workerd, outside Cloudflare";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
outputs =
{ self, nixpkgs }:
let
system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system};
inherit (pkgs) lib;
# the commit a build came from; a dirty tree's ends in -dirty
shortRev = self.shortRev or self.dirtyShortRev or "unknown";
# a clean tree's commit, whose source anyone can read; systemctl
# status lists it under Docs:
sourceUrl = lib.optionalString (self ? rev) "https://git.inference.coop/dckc/captoys/src/commit/${self.rev}/diigo-cache";
# nixpkgs has no workerd of its own; wrangler carries a patched one
workerd =
pkgs.runCommand "workerd-${version}" { } ''
bin=${pkgs.wrangler}/lib/node_modules/.pnpm/@cloudflare+workerd-linux-64@${version}/node_modules/@cloudflare/workerd-linux-64/bin/workerd
test -x $bin || { echo "no workerd ${version} in ${pkgs.wrangler}" >&2; exit 1; }
mkdir -p $out/bin
ln -s $bin $out/bin/workerd
'';
# the workerd that nixpkgs' wrangler bundles; must be at least the
# workers' compatibility_date
version = "1.20261006.1";
# the flake's source is all of capsite; take what the two workers need
src = lib.fileset.toSource {
root = ./..;
fileset = lib.fileset.unions [
./package.json
./pnpm-lock.yaml
./wrangler.jsonc
./tsconfig.json
./src
../webapp/wrangler.jsonc
../webapp/tsconfig.json
../webapp/src
];
};
diigo-cache = pkgs.stdenv.mkDerivation (finalAttrs: {
pname = "diigo-cache";
version = "0.0.0-${shortRev}";
inherit src;
sourceRoot = "${finalAttrs.src.name}/diigo-cache";
nativeBuildInputs = [
pkgs.nodejs
pkgs.pnpm_10
pkgs.pnpmConfigHook
pkgs.wrangler
];
pnpmDeps = pkgs.fetchPnpmDeps {
inherit (finalAttrs) pname src sourceRoot;
# not the rev: the deps don't change with each commit
version = "0.0.0";
pnpm = pkgs.pnpm_10;
fetcherVersion = 3;
hash = "sha256-sn/juOL2mhyy3i57GCUKA2X8SPyR9FwY4KoxdkgZa0M=";
};
buildPhase = ''
runHook preBuild
export HOME=$TMPDIR WRANGLER_SEND_METRICS=false
# wrangler writes .wrangler/tmp beside each config
chmod -R u+w ../webapp
wrangler deploy --dry-run --outdir $PWD/dist/cache -c wrangler.jsonc
wrangler deploy --dry-run --outdir $PWD/dist/webapp -c ../webapp/wrangler.jsonc
bash ${./nix/gen-config.sh} dist ${./nix/config.capnp.in} \
"$(sed -n 's/.*"compatibility_date": *"\([^"]*\)".*/\1/p' wrangler.jsonc)" \
"$(sed -n 's/.*"compatibility_date": *"\([^"]*\)".*/\1/p' ../webapp/wrangler.jsonc)" \
> dist/config.capnp
runHook postBuild
'';
installPhase = ''
runHook preInstall
share=$out/share/diigo-cache
mkdir -p $share $out/bin $out/lib/systemd/system
cp -r dist/cache dist/webapp dist/config.capnp $share/
rm -f $share/*/README.md $share/*/*.map
cat > $out/bin/diigo-cache-serve <<EOF
#!${pkgs.runtimeShell}
exec ${workerd}/bin/workerd serve $share/config.capnp "\$@"
EOF
chmod +x $out/bin/diigo-cache-serve
cp ${./nix/diigo-cache.socket} $out/lib/systemd/system/diigo-cache.socket
substitute ${./nix/diigo-cache.service} $out/lib/systemd/system/diigo-cache.service \
--replace-fail '@source@' '${sourceUrl}'
# the docs, at a path the profile keeps across upgrades
doc=$out/share/doc/diigo-cache
mkdir -p $doc
cp ${./README.md} $doc/README.md
cp ${./CONTRIBUTING.md} $doc/CONTRIBUTING.md
cp -r ${./doc} $doc/doc
echo ${self.rev or self.dirtyRev or "unknown"} > $doc/REVISION
runHook postInstall
'';
});
in
{
packages.${system} = {
default = diigo-cache;
inherit diigo-cache workerd;
};
# the built config serves the home page, and mints a webapp instance
# through the WEBAPP binding into webapp's Durable Object storage;
# each log entry is one line of JSON
checks.${system}.smoke = pkgs.runCommand "diigo-cache-smoke" { nativeBuildInputs = [ pkgs.curl pkgs.jq ]; } ''
mkdir -p cache webapp
${diigo-cache}/bin/diigo-cache-serve -s http=127.0.0.1:18790 \
-d cache-state=$PWD/cache -d webapp-state=$PWD/webapp > log 2>&1 &
pid=$!
for i in $(seq 50); do curl -sf http://127.0.0.1:18790/ -o home.html && break; sleep 0.2; done
grep -q '/_connect' home.html
curl -sf -X POST http://127.0.0.1:18790/_mint \
--data-urlencode url=https://diigo.invalid/ --data-urlencode cookie=x \
-D headers -o /dev/null
grep -qi '^x-webapp-id: [A-Za-z0-9-]' headers
ls webapp/*/*.sqlite
kill $pid; wait $pid || true
cat log
grep -q "event: 'mint'" log
jq -e . log > /dev/null
touch $out
'';
};
}
+60
View File
@@ -0,0 +1,60 @@
# diigo-cache and the webapp it reads diigo through, in one workerd.
#
# The listening socket has no address here: systemd hands it in
# (-S http=3), so holding the socket is the authority to reach the cache.
# State directories likewise come from the command line:
# -d cache-state=<dir> -d webapp-state=<dir>.
#
# Durable Object unique keys follow miniflare's `<script>-<class>`, so a
# `wrangler dev` state directory names its objects the same way.
using Workerd = import "/workerd/workerd.capnp";
const config :Workerd.Config = (
services = [
(name = "diigo-cache", worker = .cache),
(name = "webapp", worker = .webapp),
(name = "nowhere", network = (allow = [])),
(name = "cache-state", disk = (path = "cache-state", writable = true)),
(name = "webapp-state", disk = (path = "webapp-state", writable = true)),
],
sockets = [
(name = "http", http = (), service = "diigo-cache"),
],
# one JSON object per line, console.* included: journald keeps an
# object in one entry rather than one entry per line of it
structuredLogging = true,
);
const cache :Workerd.Worker = (
compatibilityDate = "@CACHE_DATE@",
modules = [
@CACHE_MODULES@
],
durableObjectNamespaces = [
(className = "DiigoCache", uniqueKey = "diigo-cache-DiigoCache", enableSql = true),
(className = "PublicCache", uniqueKey = "diigo-cache-PublicCache", enableSql = true),
],
durableObjectStorage = (localDisk = "cache-state"),
bindings = [
(name = "CACHE_DO", durableObjectNamespace = "DiigoCache"),
(name = "PUBLIC_DO", durableObjectNamespace = "PublicCache"),
(name = "WEBAPP", service = (name = "webapp", entrypoint = "WebAppFactory")),
],
# diigo is reached only through WEBAPP
globalOutbound = "nowhere",
);
const webapp :Workerd.Worker = (
compatibilityDate = "@WEBAPP_DATE@",
modules = [
@WEBAPP_MODULES@
],
durableObjectNamespaces = [
(className = "WebAppDo", uniqueKey = "webapp-WebAppDo", enableSql = true),
],
durableObjectStorage = (localDisk = "webapp-state"),
bindings = [
(name = "WEBAPP_DO", durableObjectNamespace = "WebAppDo"),
],
# globalOutbound: workerd's default "internet", public addresses only
);
+33
View File
@@ -0,0 +1,33 @@
[Unit]
Description=diigo-cache and webapp (workerd)
# the profile's README, and the commit's source (a clean build's only)
Documentation=file:///nix/var/nix/profiles/diigo-cache/share/doc/diigo-cache/README.md @source@
Requires=diigo-cache.socket
[Service]
# the profile path survives upgrades; see doc/install.md
ExecStart=/nix/var/nix/profiles/diigo-cache/bin/diigo-cache-serve -S http=3 -d cache-state=/var/lib/diigo-cache/cache -d webapp-state=/var/lib/diigo-cache/webapp
DynamicUser=yes
StateDirectory=diigo-cache diigo-cache/cache diigo-cache/webapp
StateDirectoryMode=0700
# webapp fetches diigo.com; nothing else needs the network
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictNamespaces=yes
LockPersonality=yes
CapabilityBoundingSet=
SystemCallFilter=@system-service
# V8 uses memory protection keys; without these, SIGSYS at startup
SystemCallFilter=pkey_alloc pkey_mprotect pkey_free
# not MemoryDenyWriteExecute: V8's JIT needs W+X
[Install]
# started at boot, not only on the first request: workerd runs the
# caches' refresh alarms only while it is up
WantedBy=multi-user.target
+9
View File
@@ -0,0 +1,9 @@
[Unit]
Description=diigo-cache: loopback port behind tailscale serve
[Socket]
# tailscale serve proxies https://bldbox.<tailnet>.ts.net/ here
ListenStream=127.0.0.1:8790
[Install]
WantedBy=sockets.target
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env bash
# Fill config.capnp.in from `wrangler deploy --dry-run` outdirs.
# usage: gen-config.sh <dist> <template> <cache-date> <webapp-date> > config.capnp
# <dist>/cache and <dist>/webapp each hold index.js plus the text modules
# wrangler.jsonc's rules name (*.sql, capnweb's browser build); embed
# paths are relative to the config, which sits beside them.
set -euo pipefail
dist=$1 template=$2 cache_date=$3 webapp_date=$4
modules() {
local dir=$1
if [[ ! -f $dist/$dir/index.js ]]; then
echo "gen-config: $dist/$dir/index.js: missing" >&2
exit 1
fi
echo " (name = \"index.js\", esModule = embed \"$dir/index.js\"),"
for f in "$dist/$dir"/*; do
local name=${f##*/}
case $name in
index.js | README.md | *.map) ;;
*.sql | *-index.js) echo " (name = \"$name\", text = embed \"$dir/$name\")," ;;
*)
echo "gen-config: $dir/$name: no module type rule" >&2
exit 1
;;
esac
done
}
cache_modules=$(modules cache)
webapp_modules=$(modules webapp)
while IFS= read -r line; do
case $line in
@CACHE_MODULES@) echo "$cache_modules" ;;
@WEBAPP_MODULES@) echo "$webapp_modules" ;;
*)
line=${line//@CACHE_DATE@/$cache_date}
echo "${line//@WEBAPP_DATE@/$webapp_date}"
;;
esac
done <"$template"
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
# Serve a built package under the service unit's syscall filter, as a
# transient user unit, on a scratch port and state; check the home page.
# The flake's smoke check can't: the nix sandbox has no systemd.
# usage: probe-unit.sh <package out path>
set -euo pipefail
out=$1
state=$(mktemp -d)
trap 'systemctl --user stop diigo-cache-probe 2>/dev/null; rm -rf "$state"' EXIT
mkdir "$state/cache" "$state/webapp"
props=()
while IFS= read -r line; do props+=(-p "$line"); done \
< <(grep '^SystemCallFilter=' "$out/lib/systemd/system/diigo-cache.service")
systemd-run --user -q --collect --unit=diigo-cache-probe "${props[@]}" \
"$out/bin/diigo-cache-serve" -s http=127.0.0.1:18791 \
-d cache-state="$state/cache" -d webapp-state="$state/webapp"
for _ in $(seq 30); do
if curl -sf -m 2 http://127.0.0.1:18791/ | grep -q _connect; then
echo "probe: ok"
exit 0
fi
sleep 0.3
done
echo "probe: no home page; see journalctl --user -u diigo-cache-probe and journalctl -k | grep syscall=" >&2
exit 1
+22
View File
@@ -0,0 +1,22 @@
{
"name": "diigo-cache",
"private": true,
"type": "module",
"scripts": {
"dev": "wrangler dev -c wrangler.jsonc -c ../webapp/wrangler.jsonc",
"types": "wrangler types",
"lint": "wrangler types --check && tsc -p tsconfig.json && tsc -p tests/tsconfig.json && tsc -p scripts/tsconfig.json",
"test": "vitest run"
},
"devDependencies": {
"@cloudflare/vitest-plugin": "1.3.6",
"@types/node": "^22",
"microformats-parser": "^2.0.6",
"typescript": "^5.9.0",
"vitest": "4.1.11",
"wrangler": "^4.148.0"
},
"dependencies": {
"capnweb": "^0.12.0"
}
}
+1737
View File
File diff suppressed because it is too large. Load diff
+171
View File
@@ -0,0 +1,171 @@
#!/usr/bin/env node
/** @file Does a cache hold everything in a diigo RSS export? See {@link HELP}. */
/** printed on bad usage */
const HELP = `usage: node scripts/compare-export.ts <cache.sqlite> <export.xml> <out-dir>
Generates RSS from the cache's items (src/rss.ts) and compares it with the
export, keyed on link: title, tags, description, highlights and sticky
notes. Prints counts to stdout; writes <out-dir>/from-cache.rss and
<out-dir>/report.json (mismatched links, by category).
`;
import * as nodeFs from "node:fs/promises";
import { basename, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { itemDescription, toRss } from "../src/rss.ts";
type Item = Record<string, unknown>;
/**
* the exit status for incorrect usage (invalid options, missing
* arguments): the shell's convention
*
* @see https://www.gnu.org/software/bash/manual/html_node/Exit-Status.html
*/
const BAD_USAGE = 2;
/** one export item, as read */
type Exported = { title: string; link: string; description: string };
/** a new object with each value mapped; keys kept (as `objectMap` in
* @endo/common) */
export function objectMap<V, W>(original: Record<string, V>, mapFn: (value: V, key: string) => W): Record<string, W> {
return Object.fromEntries(Object.entries(original).map(([k, v]) => [k, mapFn(v, k)]));
}
const FORBIDDEN = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g;
const clean = (s: string) => s.replace(FORBIDDEN, "");
/** diigo's RSS export, read leniently item by item (it isn't well-formed
* XML: it carries characters XML forbids) */
export function parseExport(xml: string): Exported[] {
const field = (it: string, name: string) =>
it.match(new RegExp(`<${name}><!\\[CDATA\\[([\\s\\S]*?)\\]\\]></${name}>`))?.[1] ?? "";
return [...xml.matchAll(/<item>([\s\S]*?)<\/item>/g)].map((m) => ({
title: clean(field(m[1], "title")),
link: clean(field(m[1], "link")),
description: clean(field(m[1], "description")),
}));
}
const PARTS = /^Tags:([\s\S]*?);Description:([\s\S]*?);Annotations and Sticky notes:([\s\S]*)$/;
/** what's wrong with `ours` as a rendering of `theirs` (empty: nothing) */
function problems(o: Item, t: Exported): string[] {
const found: string[] = [];
const title = clean(String(o.title ?? ""));
// the export cuts titles at 255
if (title !== t.title && !(t.title.length === 255 && title.startsWith(t.title))) found.push("title differs");
const mine = clean(itemDescription(o)).match(PARTS);
const yours = t.description.match(PARTS);
if (!mine || !yours) return [...found, "description unparsed"];
if (mine[1] !== yours[1]) found.push("tags differ");
if (mine[2] !== yours[2]) found.push("description differs");
if (mine[3] !== yours[3]) found.push("annotations differ");
return found;
}
/**
* compare cached items with an export, keyed on link: each export item
* is complete, missing, or has problems by category; cached links absent
* from the export are reported too. Links only, never contents.
*/
export function compare(ours: Item[], theirs: Exported[]): { complete: number; report: Record<string, string[]> } {
const byUrl = new Map<string, Item[]>();
for (const it of ours) {
const url = String(it.url ?? "");
byUrl.set(url, [...(byUrl.get(url) ?? []), it]);
}
const report: Record<string, string[]> = {};
const note = (category: string, link: string) => (report[category] ??= []).push(link);
let complete = 0;
for (const t of theirs) {
const candidates = byUrl.get(t.link);
if (!candidates) {
note("missing from cache", t.link);
continue;
}
// a link bookmarked twice: the best-matching candidate counts
const best = candidates.map((o) => problems(o, t)).reduce((a, b) => (b.length < a.length ? b : a));
if (best.length === 0) complete += 1;
for (const p of best) note(p, t.link);
}
const exportLinks = new Set(theirs.map((t) => t.link));
for (const url of byUrl.keys()) if (!exportLinks.has(url)) note("in cache, not in export", url);
return { complete, report };
}
/** read-only access to one cache's items: attenuates a database */
export function cacheItems(db: { prepare(sql: string): { all(): unknown[] } }) {
return {
/** every item, newest update first */
all: (): Item[] =>
(db.prepare("select json from items order by updated desc").all() as { json: string }[]).map(
(r) => JSON.parse(r.json) as Item,
),
};
}
/** write access to files directly inside one directory: attenuates fs */
export function outDir(fs: Pick<typeof nodeFs, "writeFile">, dir: string) {
return {
async write(name: string, text: string): Promise<void> {
if (basename(name) !== name) throw new Error(`not a plain file name: ${name}`);
await fs.writeFile(join(dir, name), text);
},
};
}
/**
* Run the comparison. Every power it uses comes in as a default argument
* and is narrowed here — the database to {@link cacheItems}, the output
* directory to {@link outDir} — before anything else uses it.
*/
export async function main(
argv = process.argv.slice(2),
{
fs = nodeFs,
// node:sqlite has only a synchronous API; one read of a local file
connect = (path: string) => new DatabaseSync(path, { readOnly: true }),
now = () => new Date(),
stdout = process.stdout,
stderr = process.stderr,
exit = (code: number) => {
process.exitCode = code;
},
}: {
fs?: Pick<typeof nodeFs, "readFile" | "writeFile">;
connect?: (path: string) => { prepare(sql: string): { all(): unknown[] } };
now?: () => Date;
stdout?: { write(text: string): unknown };
stderr?: { write(text: string): unknown };
exit?: (code: number) => void;
} = {},
): Promise<void> {
const [dbPath, exportPath, outPath] = argv;
if (!dbPath || !exportPath || !outPath) {
stderr.write(HELP);
return exit(BAD_USAGE);
}
const cache = cacheItems(connect(dbPath));
const out = outDir(fs, outPath);
const exportXml = await fs.readFile(exportPath, "utf8");
const ours = cache.all();
await out.write("from-cache.rss", toRss(ours, { title: "from the cache", pubDate: now().toUTCString() }));
const theirs = parseExport(exportXml);
const { complete, report } = compare(ours, theirs);
await out.write("report.json", JSON.stringify(report, null, 1));
const counts = {
export: theirs.length,
cache: ours.length,
complete,
...objectMap(report, (links) => links.length),
};
stdout.write(`${JSON.stringify(counts, null, 1)}\n`);
exit(0);
}
// run only as a program, not when imported (e.g. by a test)
if (import.meta.main) await main();
+11
View File
@@ -0,0 +1,11 @@
{
// program scripts run under node (type stripping), so they get node's
// types; the worker's own tsconfig keeps them out
"extends": "../tsconfig.json",
"compilerOptions": {
"types": ["node"],
"lib": ["ES2022", "ESNext.Disposable"],
"allowImportingTsExtensions": true
},
"include": ["./**/*.ts", "../src/rss.ts", "../src/items.ts"]
}
+132
View File
@@ -0,0 +1,132 @@
/** @file the Cap'n Web API at /api: trade a cache's webkey for a capability. */
import { RpcTarget } from "capnweb";
import type { DiigoCacheLogic, FillStatus, PublicCacheLogic } from "./cache.js";
import { idFromWebkey, isWebkey, shashKey } from "./webkeys.js";
/** the bindings the API reaches (structural) */
export type ApiEnv = {
CACHE_DO: DurableObjectNamespace<DiigoCacheLogic>;
PUBLIC_DO: DurableObjectNamespace<PublicCacheLogic>;
};
/** the fill-job surface of one cache (private or public) */
type Fillable = {
startFill(opts?: { pagesPerStep?: number }): Promise<FillStatus>;
fillStatus(): Promise<FillStatus | undefined>;
stopFill(): Promise<FillStatus>;
invalidateRecent(days: number): Promise<{ pages: number }>;
};
/** a cache's fill job and page invalidation, and nothing else */
export class FillCap extends RpcTarget {
#cache: Fillable;
constructor(cache: Fillable) {
super();
this.#cache = cache;
}
/** start (or rejoin) the job; `pagesPerStep` 1–50 */
async startFill(opts: unknown = {}): Promise<FillStatus> {
const step = (opts as { pagesPerStep?: unknown } | null)?.pagesPerStep;
if (step !== undefined && typeof step !== "number") throw new Error("pagesPerStep: expected a number");
return this.#cache.startFill(step === undefined ? {} : { pagesPerStep: step });
}
/** the job's progress, or undefined if none was started */
async fillStatus(): Promise<FillStatus | undefined> {
return this.#cache.fillStatus();
}
/** stop the job; cached pages stay */
async stopFill(): Promise<FillStatus> {
return this.#cache.stopFill();
}
/** drop the cached pages holding anything updated in the last `days`
* days (1–3650), so they refetch */
async invalidateRecent(days: unknown): Promise<{ pages: number }> {
if (typeof days !== "number") throw new Error("days: expected a number");
return this.#cache.invalidateRecent(days);
}
}
/** what the holder of a private cache's key may do */
export class CacheCap extends FillCap {
#key: string;
#publicId: string | undefined;
#env: ApiEnv;
constructor(env: ApiEnv, key: string, cache: Fillable, publicId: string | undefined) {
super(cache);
this.#env = env;
this.#key = key;
this.#publicId = publicId;
}
/** a prefix of the key's one-way hash: names it without granting it */
async fingerprint(): Promise<string> {
return (await shashKey(this.#key)).slice(0, 8);
}
/** whether a public companion exists (see {@link publicCache}) */
hasPublic(): boolean {
return this.#publicId !== undefined;
}
/** the public companion's fill job; refused if never published (a
* stub, not a maybe-null, so calls on it pipeline) */
publicCache(): FillCap {
if (!this.#publicId) throw new Error("no public cache: publish this cache first");
const ns = this.#env.PUBLIC_DO;
return new FillCap(ns.get(ns.idFromString(idFromWebkey(this.#publicId))));
}
}
/**
* the main interface at /api. The browser holds a cache's key in a URL
* fragment (`/cache/#<key>`, docs/webkeys.md), so it never reaches the
* server in a URL; the webkey page passes it *in-band* to {@link cache}
* and gets back a {@link CacheCap}. With authorization in-band,
* cross-origin calls are safe (capnweb's note on `newWorkersRpcResponse`);
* arguments are checked at runtime, since types are erased on the wire.
*
* @see https://github.com/cloudflare/capnweb
*/
export class CacheApi extends RpcTarget {
#env: ApiEnv;
constructor(env: ApiEnv) {
super();
this.#env = env;
}
/**
* trade a cache's webkey for its capability. Refused keys get one
* message for malformed and unknown alike, which never echoes the key.
*/
async cache(key: unknown): Promise<CacheCap> {
const refused = () => new Error("no such cache");
if (typeof key !== "string" || !isWebkey(key, 256)) {
console.log({ event: "api", refused: "cache", reason: "malformed key" });
throw refused();
}
const ns = this.#env.CACHE_DO;
let stub;
try {
// a well-formed id from another namespace throws here
stub = ns.get(ns.idFromString(idFromWebkey(key)));
} catch (err) {
// the key is never logged: it is the bearer secret
console.log({ event: "api", refused: "cache", reason: String(err) });
throw refused();
}
const wiring = await stub.wiring();
if (!wiring) {
console.log({ event: "api", refused: "cache", reason: "not wired" });
throw refused();
}
return new CacheCap(this.#env, key, stub, wiring.publicId);
}
}
+130
View File
@@ -0,0 +1,130 @@
/** @file the webkey page at /cache/: a skeleton the key's holder drives over /api. */
/**
* the webkey page, identical for every key (docs/webkeys.md): the key
* rides the URL fragment, which browsers never send to the server or in a
* Referer. Its script reads it, trades it for a capability
* (`api.cache(key)`, Cap'n Web over /api, in-band), and drives the fill
* job. Each round trip is its own HTTP batch session.
*
* Without a fragment it is a login form a password manager fills
* (petname as username, cache id as password). The inputs have no
* `name`, so a native submit (script failed) sends nothing; the key stays
* in memory, out of the address bar and history.
*/
export const CACHE_PAGE_HTML = `<!doctype html>
<html><head><meta charset="utf-8"><meta name="referrer" content="no-referrer">
<title>diigo cache</title></head>
<body>
<h1>diigo cache <code id="fingerprint"></code></h1>
<p id="problem" hidden></p>
<form id="login" hidden>
<p><label>petname <input id="login-petname" autocomplete="username" size="24"></label></p>
<p><label>cache id <input id="login-key" type="password" autocomplete="current-password" size="24" required></label></p>
<p><button type="submit">open</button></p>
</form>
<section id="private" hidden>
<h2>private cache</h2>
<p id="private-status">no fill job yet</p>
<button type="button" data-target="private" data-action="start">fill</button>
<button type="button" data-target="private" data-action="stop">stop</button>
<p><label>invalidate the last <input type="number" id="private-days" min="1" max="3650" value="7" size="5"> days</label>
<button type="button" data-target="private" data-action="invalidate">invalidate</button>
<span id="private-invalidated"></span></p>
</section>
<section id="public" hidden>
<h2>public cache</h2>
<p id="public-status">no fill job yet</p>
<button type="button" data-target="public" data-action="start">fill</button>
<button type="button" data-target="public" data-action="stop">stop</button>
<p><label>invalidate the last <input type="number" id="public-days" min="1" max="3650" value="7" size="5"> days</label>
<button type="button" data-target="public" data-action="invalidate">invalidate</button>
<span id="public-invalidated"></span></p>
</section>
<p><a href="/">← home</a></p>
<script type="module">
import { newHttpBatchRpcSession } from "/_capnweb.js";
let key = location.hash.slice(1);
const $ = (id) => document.getElementById(id);
const problem = (text) => {
$("problem").textContent = text;
$("problem").hidden = false;
};
/** a fresh batch session, traded for this key's capability */
const cap = () => newHttpBatchRpcSession("/api").cache(key);
/** the fill-job stub for a target */
const job = (target) => (target === "public" ? cap().publicCache() : cap());
const describe = (s) => {
if (!s) return "no fill job yet";
const of = Math.max(0, s.nextPage - 1) + " of " + (s.pages ?? "?") + " pages";
return {
running: "filling: " + of,
done: "filled: " + of,
stopped: "fill stopped: " + of,
failed: "fill failed at page " + s.nextPage + ": " + (s.error ?? "unknown error"),
}[s.state];
};
let polling = false;
async function refresh(hasPublic) {
const targets = hasPublic ? ["private", "public"] : ["private"];
const statuses = await Promise.all(targets.map((t) => job(t).fillStatus()));
targets.forEach((t, i) => ($(t + "-status").textContent = describe(statuses[i])));
const running = statuses.some((s) => s?.state === "running");
if (running && !polling) {
polling = true;
setTimeout(() => {
polling = false;
refresh(hasPublic).catch(report);
}, 3000);
}
}
function report(err) {
console.error({ event: "cache-page", error: String(err) });
problem(String(err));
}
/** no fragment: ask for the key (the password manager fills it in) */
function login() {
const form = $("login");
form.hidden = false;
form.addEventListener("submit", (event) => {
event.preventDefault();
key = $("login-key").value.trim();
if (!key) return;
form.hidden = true;
main().catch(report);
});
}
async function main() {
if (!key) return login();
const c = cap();
const [fingerprint, hasPublic] = await Promise.all([c.fingerprint(), c.hasPublic()]);
$("fingerprint").textContent = fingerprint;
$("private").hidden = false;
$("public").hidden = !hasPublic;
for (const button of document.querySelectorAll("button[data-target]")) {
button.addEventListener("click", () => {
const { target, action } = button.dataset;
const j = job(target);
if (action === "invalidate") {
const days = Number($(target + "-days").value);
j.invalidateRecent(days)
.then((r) => ($(target + "-invalidated").textContent = "dropped " + r.pages + " cached pages; fill to refetch"))
.catch(report);
return;
}
(action === "start" ? j.startFill() : j.stopFill())
.then(() => refresh(hasPublic))
.catch(report);
});
}
await refresh(hasPublic);
}
main().catch(report);
</script>
</body></html>`;
+32
View File
@@ -0,0 +1,32 @@
-- pageHeader:
select total, etched_at from pages where page_num = ? and count = ?;
-- pageItems:
select items.json
from page_members
join items on items.item_id = page_members.item_id
where page_members.page_num = ?
order by page_members.pos;
-- knownTotal:
select total from pages where total > 0 order by etched_at desc limit 1;
-- deepestPageSince:
select max(page_members.page_num) as last
from page_members
join items on items.item_id = page_members.item_id
where cast(items.updated as integer) >= ?;
-- pagesThrough:
select count(*) as n from pages where page_num <= ?;
-- itemsByUpdated:
select json from items
where cast(updated as integer) >= ? and cast(updated as integer) < ?
order by cast(updated as integer) desc, item_id;
-- itemsByCreated:
select json from items
where cast(json_extract(json, '$.created_at') as integer) >= ?
and cast(json_extract(json, '$.created_at') as integer) < ?
order by cast(json_extract(json, '$.created_at') as integer) desc, item_id;
+51
View File
@@ -0,0 +1,51 @@
-- schemaV1:
create table if not exists items (
item_id text primary key,
url text not null,
title text not null,
private integer not null,
json text not null,
updated text not null
);
create table if not exists pages (
page_num integer primary key,
count integer not null,
total integer,
etched_at text not null
);
create table if not exists page_members (
page_num integer not null,
pos integer not null,
item_id text not null,
primary key (page_num, pos)
);
-- renumberV2:
update page_members set page_num = -(page_num + 1);
update page_members set page_num = -page_num;
update pages set page_num = -(page_num + 1);
update pages set page_num = -page_num;
-- clearPageMembers:
delete from page_members where page_num = ?;
-- upsertItem:
insert into items (item_id, url, title, private, json, updated)
values (?, ?, ?, ?, ?, ?)
on conflict(item_id) do update set
url = excluded.url, title = excluded.title, private = excluded.private,
json = excluded.json, updated = excluded.updated;
-- insertPageMember:
insert into page_members (page_num, pos, item_id) values (?, ?, ?);
-- upsertPage:
insert into pages (page_num, count, total, etched_at) values (?, ?, ?, ?)
on conflict(page_num) do update set
count = excluded.count, total = excluded.total, etched_at = excluded.etched_at;
-- dropPageMembersThrough:
delete from page_members where page_num <= ?;
-- dropPagesThrough:
delete from pages where page_num <= ?;
+565
View File
@@ -0,0 +1,565 @@
/**
* @file the cache Durable Objects' logic: a private and a public page cache.
* The runtime classes are made at the edge (src/index.ts).
*/
import { DurableObject, RpcTarget } from "cloudflare:workers";
import type { PagedGet } from "./diigo.js";
import { publicOnly, toRows } from "./items.js";
import { matches } from "./query.js";
import type { Query } from "./query.js";
import { makeReader, makeWriter, SCHEMA_VERSION } from "./store.js";
import type { Reader, Writer } from "./store.js";
import type { Item, ItemRow } from "./items.js";
export type { Item };
/** one cached page, raw: `items` are the dump rows (JSON strings), ready
* to re-join with newlines */
export type CachePage = {
total: number;
items: string[];
/** true when answered from storage (no diigo call) */
cached: boolean;
/** when the page was stored (absent on a fresh fetch) */
etchedAt?: string;
};
const MS_PER_CALL = 500;
/**
* items per diigo page — the one size the worker asks for everywhere
* (fill, public pages, dumps), so a cache never mixes sizes. Pages are
* cached by (page number, size): changing this turns every cached page
* into a miss (items survive; pages refetch), and fails any fill job
* counting in the old size. 100 is diigo's cap: asked for 128, it
* returned 100 (observed 2026-10-07).
*/
export const PAGE_SIZE = 100;
/** the size fill jobs counted in before FillStatus recorded it */
const LEGACY_FILL_PAGE_SIZE = 24;
/** the pause before each fill step's alarm: a step already paces its
* pages at MS_PER_CALL; this keeps steps from running back to back */
const FILL_STEP_DELAY_MS = 1000;
/** how long after a fill ends (done or failed) a refresh starts: a fill
* that refetches the recent pages, then ends and schedules the next */
const REFRESH_INTERVAL_MS = 3 * 60 * 60 * 1000;
/** a refresh refetches the pages holding anything updated this recently
* (and every page before them; page 1 at least, for new bookmarks) */
const REFRESH_DAYS = 2;
/**
* a fill job's progress (goal 1e; tests/fill.test.ts). Stored in the DO
* (new state, additive), so it survives eviction; advanced by alarms.
*/
export type FillStatus = {
state: "running" | "done" | "stopped" | "failed";
/** the next diigo page to fetch (pages already cached are skipped) */
nextPage: number;
/** diigo's page count, known after page 1 */
pages: number | null;
/** the page size `nextPage` and `pages` count in; absent on jobs
* saved before this field existed (they counted in 24s) */
pageSize?: number;
/** the page numbering `nextPage` counts in: 2 since diigo's 0-based
* page_num is translated; absent on jobs that sent it unchanged */
numbering?: number;
/** pages fetched from diigo by this job (cache hits not counted) */
fetched: number;
startedAt: string;
updatedAt: string;
/** why it failed: safe to show and log (no ids, no header values) */
error?: string;
/** pages numbered this or lower are fetched even when cached (a
* refresh); absent on plain fills */
refetchThrough?: number;
};
/** the page size a fill job counts in (old jobs didn't record it) */
function fillPageSize(status: FillStatus): number {
return status.pageSize ?? LEGACY_FILL_PAGE_SIZE;
}
/** does a stored fill job count pages the way this code does? */
function fillCountsAsNow(status: FillStatus): boolean {
return fillPageSize(status) === PAGE_SIZE && status.numbering === SCHEMA_VERSION;
}
/** release an RPC stub, if it is one (plain objects are left alone) */
function disposeStub(stub: unknown): void {
const dispose = (stub as { [Symbol.dispose]?: () => void } | null)?.[Symbol.dispose];
if (typeof dispose === "function") dispose.call(stub);
}
/** the clock authority a cache uses: reading time, and waiting. Passed
* in (ocap discipline), so tests can interpose a fixed clock. */
export type Clock = {
/** epoch milliseconds */
now(): number;
sleep(ms: number): Promise<void>;
};
/** a cache's wiring: the webapp instance it asks on a miss, plus (private
* cache only) the public companion's id, recorded once published */
type Wiring = { webappId: string; publicId?: string | undefined };
/** the diigo-cache DO's bindings (structural; `at` mirrors webapp's
* WebAppFactory) */
export type CacheEnv = {
WEBAPP: {
at(id: string): Promise<PagedGet>;
};
};
/**
* the shared page-cache behavior; {@link DiigoCacheLogic} and
* {@link PublicCacheLogic} are independent and differ only in what they
* `keep` of a fetched page (the public one drops private rows before
* storing, {@link publicOnly}). Pages are the unit of caching: a hit is
* served from storage with no diigo call; a miss asks the webapp instance
* in the cache's wiring and stores the page.
*
* The webapp id in the wiring authorizes diigo reads (the cookie rides in
* that DO's storage); the id this DO is addressed by authorizes cache
* reads. Neither is logged. The {@link Clock} is required: time comes from
* the edge that constructs the DO.
*/
abstract class PagedCache extends DurableObject<CacheEnv> {
#step = 0;
#pause?: Promise<void>;
#clock: Clock;
/** `clock` is required: time comes from the edge that constructs us
* (src/index.ts in the worker, tests/test-worker.ts in tests) */
#reader: Reader;
#writer: Writer;
constructor(ctx: DurableObjectState, env: CacheEnv, clock: Clock) {
super(ctx, env);
this.#clock = clock;
this.#reader = makeReader(ctx.storage.sql);
this.#writer = makeWriter(ctx.storage);
// tables exist (and old storage is migrated) before any request, so
// a read-only viewer never meets a missing table
void ctx.blockConcurrencyWhile(async () => {
await null; // let the subclass constructor finish: `kind` is its field
const from = this.#writer.migrate();
if (from < SCHEMA_VERSION) console.log({ event: "schema", kind: this.kind, from, to: SCHEMA_VERSION });
// a fill that ended before refreshes existed has no alarm yet
const fill = await ctx.storage.get<FillStatus>("fill");
if (fill && fill.state !== "running" && fill.state !== "stopped" && (await ctx.storage.getAlarm()) === null) {
await ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
}
});
}
/** now, as an ISO timestamp */
#iso(): string {
return new Date(this.#clock.now()).toISOString();
}
/** one-shot wiring. Idempotent; different values are refused (mint a
* new cache instead). */
async setup(init: Wiring): Promise<void> {
const stored = await this.ctx.storage.get<Wiring>("init");
if (stored) {
if (stored.webappId !== init.webappId || stored.publicId !== init.publicId) {
throw new Error("already wired to different ids; mint a new cache instead");
}
return;
}
await this.ctx.storage.put("init", init);
}
/** the stored wiring */
async wiring(): Promise<Wiring | undefined> {
return this.ctx.storage.get<Wiring>("init");
}
/** which rows of a fetched page this cache stores */
protected abstract keep(rows: ItemRow[]): ItemRow[];
/** which cache this is, for logs (never the id: that's the bearer key) */
protected abstract readonly kind: "private" | "public";
/**
* start (or rejoin) the fill job: walk every diigo page into this
* cache, `pagesPerStep` per alarm (default 20, 1–50). Starting while a
* job runs returns that job unchanged; a finished, stopped, or failed
* job is replaced by a fresh one (cached pages are skipped anyway).
* Once the job ends, a refresh follows every REFRESH_INTERVAL_MS until
* stopped.
*/
async startFill(opts: { pagesPerStep?: number } = {}): Promise<FillStatus> {
const current = await this.fillStatus();
if (current?.state === "running" && fillCountsAsNow(current)) return current;
const step = Math.trunc(opts.pagesPerStep ?? 20);
if (!(step >= 1 && step <= 50)) throw new Error("pagesPerStep: expected 1–50");
return this.#startJob(step);
}
/** a fresh fill job, first step in FILL_STEP_DELAY_MS; `refetchThrough`
* makes it a refresh */
async #startJob(step: number, refetchThrough?: number): Promise<FillStatus> {
const now = this.#iso();
const status: FillStatus = {
state: "running",
nextPage: 1,
pages: this.#knownPages(),
pageSize: PAGE_SIZE,
numbering: SCHEMA_VERSION,
fetched: 0,
startedAt: now,
updatedAt: now,
...(refetchThrough === undefined ? {} : { refetchThrough }),
};
await this.ctx.storage.put({ fill: status, fillStep: step });
await this.ctx.storage.setAlarm(this.#clock.now() + FILL_STEP_DELAY_MS);
console.log({ event: "fill", kind: this.kind, state: status.state, pagesPerStep: step, refetchThrough });
return status;
}
/** start a refresh: a fill that refetches the pages holding anything
* updated in the last REFRESH_DAYS days. Fetching overwrites a page in
* place, so a refresh that fails leaves the cache as it was. */
async #refresh(step: number): Promise<void> {
const cutoff = Math.floor(this.#clock.now() / 1000) - REFRESH_DAYS * 24 * 60 * 60;
await this.#startJob(step, Math.max(1, this.#reader.deepestPageSince(cutoff) ?? 1));
}
/** the fill job's progress, or undefined if none was ever started;
* the page count comes from any cached page until the job learns it */
async fillStatus(): Promise<FillStatus | undefined> {
const fill = await this.ctx.storage.get<FillStatus>("fill");
return fill && fill.pages === null ? { ...fill, pages: this.#knownPages() } : fill;
}
/** stop the fill job after its current step, and its refreshes;
* cached pages stay */
async stopFill(): Promise<FillStatus> {
const current = await this.fillStatus();
if (!current) throw new Error("no fill job to stop");
if (current.state === "stopped") return current;
const stopped: FillStatus = { ...current, state: "stopped", updatedAt: this.#iso() };
await this.ctx.storage.put("fill", stopped);
await this.ctx.storage.deleteAlarm();
console.log({ event: "fill", kind: this.kind, state: "stopped", nextPage: stopped.nextPage, pages: stopped.pages });
return stopped;
}
/**
* drop the cached pages holding anything diigo updated in the last
* `days` days, and every page before them (newer still; and new
* updates push items back), so the next read or fill refetches them.
* Item rows stay. Returns how many pages were dropped.
*/
async invalidateRecent(days: number): Promise<{ pages: number }> {
if (!Number.isInteger(days) || days < 1 || days > 3650) throw new Error("days: expected a whole number from 1 to 3650");
const cutoff = Math.floor(this.#clock.now() / 1000) - days * 24 * 60 * 60;
const deepest = this.#reader.deepestPageSince(cutoff);
if (!deepest) {
console.log({ event: "cache", kind: this.kind, outcome: "invalidated", days, pages: 0 });
return { pages: 0 };
}
const pages = this.#reader.pagesThrough(deepest);
this.#writer.dropPagesThrough(deepest);
console.log({ event: "cache", kind: this.kind, outcome: "invalidated", days, pages });
return { pages };
}
/** one fill step: up to `fillStep` pages, progress saved after each,
* then the next step is scheduled (or the job ends, and the next
* refresh is). On a job that has ended, the refresh starts. */
async alarm(): Promise<void> {
const step = (await this.ctx.storage.get<number>("fillStep")) ?? 20;
let status = await this.fillStatus();
if (status?.state === "done" || status?.state === "failed") {
await this.#refresh(step);
return;
}
// a job saved under another page size or numbering counts its pages
// differently: resuming it would skip or repeat items, so it fails
if (status?.state === "running" && !fillCountsAsNow(status)) {
const error =
fillPageSize(status) !== PAGE_SIZE
? `page size changed (from ${fillPageSize(status)} to ${PAGE_SIZE}); start the fill again`
: "page numbering changed (diigo counts pages from 0); start the fill again";
status = { ...status, state: "failed", error, updatedAt: this.#iso() };
console.error({ event: "fill", kind: this.kind, state: "failed", error });
await this.ctx.storage.put("fill", status);
await this.ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
return;
}
for (let i = 0; i < step && status?.state === "running"; i += 1) {
if (status.pages !== null && status.nextPage > status.pages) {
status = { ...status, state: "done" };
break;
}
try {
const page = await this.#load(status.nextPage, PAGE_SIZE, status.nextPage <= (status.refetchThrough ?? 0));
const fetched = status.fetched + (page.cached ? 0 : 1);
// a page whose own total says the data ended before it (diigo
// answers total 0 past the end) ends the walk; the count is the
// last page with items. Judged by total, not by items: the
// public cache may keep none of a page that isn't the end.
if (page.total <= (status.nextPage - 1) * PAGE_SIZE) {
status = { ...status, state: "done", pages: status.nextPage - 1, fetched, updatedAt: this.#iso() };
break;
}
status = {
...status,
nextPage: status.nextPage + 1,
pages: Math.ceil(page.total / PAGE_SIZE),
fetched,
updatedAt: this.#iso(),
};
} catch (err) {
status = { ...status, state: "failed", error: String(err), updatedAt: this.#iso() };
console.error({ event: "fill", kind: this.kind, state: "failed", page: status.nextPage, error: status.error });
}
// a stop that landed mid-step wins
if ((await this.fillStatus())?.state === "stopped") return;
await this.ctx.storage.put("fill", status);
}
if (!status) return;
if (status.state === "running" && status.pages !== null && status.nextPage > status.pages) {
status = { ...status, state: "done", updatedAt: this.#iso() };
}
await this.ctx.storage.put("fill", status);
console.log({ event: "fill", kind: this.kind, state: status.state, nextPage: status.nextPage, pages: status.pages, fetched: status.fetched });
if (status.state === "running") await this.ctx.storage.setAlarm(this.#clock.now() + FILL_STEP_DELAY_MS);
else await this.ctx.storage.setAlarm(this.#clock.now() + REFRESH_INTERVAL_MS);
}
/** diigo's page count, if any cached page recorded `total` (pages past
* the end record 0, so they don't count) */
#knownPages(): number | null {
const total = this.#reader.knownTotal();
return total === null ? null : Math.max(1, Math.ceil(total / PAGE_SIZE));
}
/**
* read page `pageNum` (`count` per page, diigo's updated-desc order):
* storage first; on miss, fetch that one page through the webapp
* instance (every page carries `total`) and etch. Cache provenance
* rides in the result (`cached`).
*/
async page(pageNum: number, count: number): Promise<CachePage> {
return this.#load(pageNum, count, false);
}
/** {@link page}, or with `fresh`, fetch even if cached (overwriting
* the stored page) */
async #load(pageNum: number, count: number, fresh: boolean): Promise<CachePage> {
const init = await this.wiring();
if (!init) throw new Error("not wired: this cache id was never set up");
const hit = fresh ? null : await this.#pageFromStorage(pageNum, count);
if (hit) {
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: hit.items.length });
return hit;
}
// a miss calls diigo: one call path at a time, min spacing
// MS_PER_CALL (webapp's Gate pattern; per activation). Hits above
// never wait.
let before;
do {
before = this.#step;
if (this.#pause) await this.#pause;
} while (before !== this.#step);
this.#step += 1;
this.#pause = this.#clock.sleep(MS_PER_CALL);
// a request ahead of us at the gate may have etched this page
const late = fresh ? null : await this.#pageFromStorage(pageNum, count);
if (late) {
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "hit", items: late.items.length });
return late;
}
// RPC stubs (the app and each pipelined step) are disposed once the
// page is in hand: undisposed stubs keep this DO from being evicted
const data = await this.#fetchPage(init.webappId, pageNum, count);
// diigo may cap the page size below what we asked: a short page that
// isn't the last would silently skip items. If `total` ever
// overstated what diigo returns, the true last page would look short
// too. The next page tells them apart: empty means the data ends
// here; anything else means items would be skipped — refuse loudly.
const lastPage = Math.max(1, Math.ceil(data.total / count));
if (data.items.length < count && pageNum < lastPage) {
await this.#clock.sleep(MS_PER_CALL);
const next = await this.#fetchPage(init.webappId, pageNum + 1, count);
if (next.items.length > 0) {
const error = `diigo returned ${data.items.length} items for page ${pageNum} of ${lastPage} (asked for ${count}), then ${next.items.length} for page ${pageNum + 1}: page size not honored?`;
console.error({ event: "cache", kind: this.kind, page: pageNum, outcome: "short-page", fetched: data.items.length, asked: count, nextFetched: next.items.length });
throw new Error(error);
}
const actual = (pageNum - 1) * count + data.items.length;
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: "total-overstated", total: data.total, actual });
}
const kept = this.keep(toRows(data.items, console));
// fetched vs kept: the public cache's drop of private rows shows here
console.log({ event: "cache", kind: this.kind, page: pageNum, outcome: fresh ? "refetch" : "miss", fetched: data.items.length, kept: kept.length });
return this.#etch(pageNum, count, data.total, kept);
}
/** one diigo page, raw, through the webapp instance; the RPC stubs (the
* app and each pipelined step) are disposed once the page is in hand —
* undisposed stubs keep this DO from being evicted */
async #fetchPage(webappId: string, pageNum: number, count: number): Promise<{ total: number; items: Item[] }> {
const app = await this.env.WEBAPP.at(webappId);
const joined = app.pathjoin("load_user_items");
// diigo's page_num counts from 0; ours from 1
const queried = joined.query({ sort: "updated", count, page_num: pageNum - 1 });
try {
return JSON.parse(await queried.get()) as { total: number; items: Item[] };
} finally {
for (const stub of [queried, joined, app]) disposeStub(stub);
}
}
/** etch a page (one transaction): upsert items, mark the page, keep
* the fetch-time order; returns the cache-page shape */
#etch(pageNum: number, count: number, total: number, rows: ItemRow[]): CachePage {
this.#writer.etch(pageNum, count, total, rows, this.#iso());
return { total, items: rows.map((r) => r.json), cached: false };
}
/** storage-backed page read; null = cache miss. Replay order comes
* from `page_members`. */
async #pageFromStorage(pageNum: number, count: number): Promise<CachePage | null> {
const stored = this.#reader.page(pageNum, count);
return stored && { ...stored, cached: true };
}
/**
* a read-only view of this cache, for pages anyone may read (the public
* page): stored pages and fill progress, from the reader facet only —
* it cannot fetch from diigo or change storage
*/
viewer(): PageViewer {
return new PageViewer(this.#reader, () => this.fillStatus());
}
}
/** one page of a filter's matches over stored items */
export type QueryPage = {
/** the matches on this page, raw dump rows (JSON strings) */
items: string[];
/** matches in all */
matched: number;
/** true when every diigo page is stored, so no match can be missing */
complete: boolean;
};
/** what anyone may see of a cache: stored pages, stored items by filter,
* and fill progress */
export class PageViewer extends RpcTarget {
#reader: Reader;
#fillStatus: () => Promise<FillStatus | undefined>;
constructor(reader: Reader, fillStatus: () => Promise<FillStatus | undefined>) {
super();
this.#reader = reader;
this.#fillStatus = fillStatus;
}
/** a stored page, or null if it hasn't been fetched (at this size) */
page(pageNum: number, count: number): CachePage | null {
const stored = this.#reader.page(pageNum, count);
return stored && { ...stored, cached: true };
}
/**
* page `pageNum` (`count` per page) of the stored items matching
* `query`, newest first by its date. The window narrows in SQL; terms
* are checked per item. Reads storage only: items not yet stored can't
* match, which `complete` reports.
*/
query(query: Query, pageNum: number, count: number): QueryPage {
const from = query.after ? Math.ceil(query.after.getTime() / 1000) : Number.MIN_SAFE_INTEGER;
const to = query.before ? Math.ceil(query.before.getTime() / 1000) : Number.MAX_SAFE_INTEGER;
const hits = this.#reader.itemsIn(query.by, from, to).filter((json) => matches(JSON.parse(json) as Item, query));
const total = this.#reader.knownTotal();
const pages = total === null ? null : Math.max(1, Math.ceil(total / PAGE_SIZE));
return {
items: hits.slice((pageNum - 1) * count, pageNum * count),
matched: hits.length,
complete: pages !== null && this.#reader.pagesThrough(pages) >= pages,
};
}
/** diigo's total, as last stored, or null if nothing is stored */
knownTotal(): number | null {
return this.#reader.knownTotal();
}
/** the cache's fill job, if any */
fillStatus(): Promise<FillStatus | undefined> {
return this.#fillStatus();
}
}
/**
* the private cache's logic (exported to the runtime as `DiigoCache` by
* src/index.ts): public+private items, addressed by its cache id (a
* webkey, held by the user).
*/
export class DiigoCacheLogic extends PagedCache {
protected readonly kind = "private";
protected keep(rows: ItemRow[]): ItemRow[] {
return rows;
}
/** one-way addition of the public companion (private → public
* publishable later; once set, immutable). The webapp id already in
* the wiring is what makes this work without re-minting. */
async addPublic(publicId: string): Promise<void> {
const stored = await this.ctx.storage.get<Wiring>("init");
if (!stored) throw new Error("not wired");
if (stored.publicId) {
if (stored.publicId !== publicId) {
throw new Error("already has a public cache");
}
return;
}
await this.ctx.storage.put("init", { ...stored, publicId });
}
}
/**
* the public cache: shared items only — {@link publicOnly} drops private
* rows before they are stored, so this DO's storage holds nothing
* private. Widely shared: addressed by diigo username in the worker's
* route path (`/public/<username>`). It does hold the webapp id (the same
* cookie session the private cache uses), so it *could* read private
* items; it keeps none. Public page n is diigo page n, filtered: it may
* hold fewer than `count` items. Doubles as the username→instance index
* (the idFromName("index") instance holds the kv mapping and is never
* wired).
*/
export class PublicCacheLogic extends PagedCache {
protected readonly kind = "public";
protected keep(rows: ItemRow[]): ItemRow[] {
return publicOnly(rows);
}
/** register/replace the username → this-instance mapping (called on
* the idFromName("index") instance) */
async register(username: string, publicId: string): Promise<void> {
this.ctx.storage.kv.put(`user:${username}`, publicId);
}
/** resolve a username to a public-cache instance id (index role);
* undefined = not registered */
async lookup(username: string): Promise<string | undefined> {
return this.ctx.storage.kv.get<string>(`user:${username}`);
}
}
+10
View File
@@ -0,0 +1,10 @@
/** @file capnweb's browser build, as text, for the worker to serve. */
// @ts-expect-error: a Text-rule import (wrangler.jsonc "rules"), not code
import source from "../node_modules/capnweb/dist/index.js";
/**
* capnweb's browser build (a self-contained ES module), served at
* /_capnweb.js; wrangler's Text rule makes the import a string.
* Self-hosted: no third-party script on a page that holds a bearer key.
*/
export const CAPNWEB_BROWSER_JS: string = source;
+44
View File
@@ -0,0 +1,44 @@
/** @file the diigo bookmark generator over a fluent handle (not used by the worker today). */
export type PagedGet = {
pathjoin(ref: string): PagedGet;
query(params: Record<string, string | number>): PagedGet;
get(): Promise<string>;
};
export type DumpOptions = {
/** fluent handle for the diigo account, cookie attached upstream */
diigoAPI: PagedGet;
pages?: number;
count?: number;
log?: (event: Record<string, unknown>) => void;
};
/** yield diigo bookmarks, most-recently-updated first, `pages * count` at
* most. `diigoAPI` is attenuated authority; over RPC the generator runs in
* the caller's address space against a stub. */
export async function* dumpBookmarks({
diigoAPI,
pages = 2,
count = 24,
log = () => {},
}: DumpOptions): AsyncGenerator<Record<string, unknown>> {
const getUserItems = (page: number) =>
diigoAPI
.pathjoin("load_user_items")
.query({ sort: "updated", count, page_num: page })
.get()
.then(JSON.parse) as Promise<{ total: number; items: Record<string, unknown>[] }>;
const first = await getUserItems(1);
const totalPages = Math.ceil(first.total / count);
log({ event: "start", total: first.total, pages, totalPages });
let got = 0;
for (let page = 1; page <= Math.min(pages, totalPages); page += 1) {
const data = page === 1 ? first : await getUserItems(page);
yield* data.items;
got += data.items.length;
log({ event: "page", page, of: pages, got });
}
}
+709
View File
@@ -0,0 +1,709 @@
/**
* @file diigo-cache worker: the create flow, the webkey page and its API,
* and public pages. See the default export for its routes.
*/
import { WorkerEntrypoint } from "cloudflare:workers";
import { newWorkersRpcResponse } from "capnweb";
import { CacheApi } from "./api.js";
import { CAPNWEB_BROWSER_JS } from "./capnweb-browser.js";
import { CACHE_PAGE_HTML } from "./cache-page.js";
import { DiigoCacheLogic, PublicCacheLogic } from "./cache.js";
import { PAGE_SIZE } from "./cache.js";
import type { CacheEnv, Clock, FillStatus, QueryPage } from "./cache.js";
import type { Item } from "./cache.js";
import { usernameOf } from "./items.js";
import { dateOf, isEmpty, parseQuery } from "./query.js";
import type { Query } from "./query.js";
import { toWebkey, idFromWebkey, isWebkey, shashKey } from "./webkeys.js";
import { pmSave } from "./pm-save.js";
/** the live clock: the worker's entry module reads ambient time and hands
* it to the cache logic, which uses only the clock it is given */
function liveClock(): Clock {
return { now: () => Date.now(), sleep: (ms) => new Promise((r) => setTimeout(r, ms)) };
}
/**
* the private cache, as the runtime constructs it. DO classes must be
* exports of the main module, and the runtime passes only (ctx, env): a
* Cloudflare constraint, met here at the edge by supplying the live clock.
*/
export class DiigoCache extends DiigoCacheLogic {
constructor(ctx: DurableObjectState, env: CacheEnv) {
super(ctx, env, liveClock());
}
}
/** the public cache, as the runtime constructs it (see {@link DiigoCache}) */
export class PublicCache extends PublicCacheLogic {
constructor(ctx: DurableObjectState, env: CacheEnv) {
super(ctx, env, liveClock());
}
}
/** worker bindings (structural until wrangler types regenerates) */
type Env = {
WEBAPP: {
fetch(request: Request): Promise<Response>;
};
CACHE_DO: DurableObjectNamespace<DiigoCache>;
PUBLIC_DO: DurableObjectNamespace<PublicCache>;
DIIGO_CACHE_ID?: string;
};
const UA = "Mozilla/5.0 (X11; Linux x86_64) Gecko/20100101 Firefox/141.0";
const DIIGO_INTERACT = "https://www.diigo.com/interact_api/";
/** the diigo export (DiigoBridge lives on; the dumpNdjson cache-id source
* is TODO(2-i): ride the create form's handoff instead of a worker secret) */
export class DiigoBridge extends WorkerEntrypoint {
/** bulk dump from the caller's address space: `pages * count` bookmarks
* through the cache (cache-hits are storage reads) */
async dumpNdjson(pages: number, count = PAGE_SIZE): Promise<string> {
const ns = (this.env as unknown as Env).CACHE_DO;
const cacheId = (this.env as unknown as Env).DIIGO_CACHE_ID;
if (!cacheId) throw new Error("no cache id supplied (caller config error)");
const cache = ns.get(ns.idFromString(idFromWebkey(cacheId)));
const lines: string[] = [];
for (let p = 1; p <= pages; p += 1) {
const page = await cache.page(p, count);
lines.push(...(p === 1 ? page.items.slice(0, count) : page.items));
}
return lines.join("\n");
}
}
/**
* the worker's routes:
*
* - `GET /`: home ({@link home}); `POST /`: dump a page by cache id ({@link dump})
* - `GET /_connect`: webapp's mint form, relayed ({@link mintPage});
* `POST /_mint`: the mint ({@link proxyMint})
* - `POST /_wire`: wire a cache to a webapp id ({@link wire});
* `POST /_publish`: add a public companion later ({@link publishCache})
* - `GET /cache/`: the webkey page ({@link CACHE_PAGE_HTML});
* `/api`: its Cap'n Web API ({@link CacheApi}); `GET /_capnweb.js`
* - `GET /public/<username>`: public pages, read-only ({@link publicPage})
*
* Cache ids are webkeys (docs/webkeys.md): they ride POST bodies and URL
* fragments, never query strings or paths.
*/
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const pub = url.pathname.match(/^\/public\/([A-Za-z0-9_-]+)$/);
if (pub) return publicPage(request, env, pub[1]);
if (url.pathname === "/_connect" && request.method === "GET") {
return mintPage(env);
}
if (url.pathname === "/_mint" && request.method === "POST") {
return proxyMint(request, env);
}
if (url.pathname === "/_wire" && request.method === "POST") {
return wire(request, env);
}
if (url.pathname === "/_publish" && request.method === "POST") {
return publishCache(request, env);
}
if (url.pathname === "/cache/" && request.method === "GET") {
return new Response(CACHE_PAGE_HTML, { headers: { "content-type": "text/html;charset=utf-8" } });
}
if (url.pathname === "/_capnweb.js" && request.method === "GET") {
return new Response(CAPNWEB_BROWSER_JS, { headers: { "content-type": "text/javascript;charset=utf-8" } });
}
if (url.pathname === "/api") {
return newWorkersRpcResponse(request, new CacheApi(env));
}
if (url.pathname !== "/") return new Response("not found", { status: 404 });
if (request.method === "POST") {
return dump(request, env);
}
// GET is inert: a cache id never rides a query string
return home(env, { error: "GET is inert: dumps happen on POST submits" }, null);
},
};
/**
* the connect page: webapp's own mint form HTML, fetched over the service
* binding with diigo's prefill (base URL, UA headers) and its action
* rewritten to our relay. Served here because wrangler's multi-config dev
* doesn't serve an aux worker's HTTP. diigo-cache authors no fields of its
* own; the init params stay editable, webapp's.
*/
async function mintPage(env: Env): Promise<Response> {
const prefill =
`?render=1&title=${encodeURIComponent("diigo cache: mint the session")}` +
`&url=${encodeURIComponent(DIIGO_INTERACT)}` +
`&headers=${encodeURIComponent(JSON.stringify({ "user-agent": UA, "x-requested-with": "XMLHttpRequest" }))}` +
`&msPerCall=500`;
let html: string;
try {
// a plain fetch() from inside the worker goes to the internet, not
// to the service binding — binding calls need a Request handed to
// the stub (workerd's entrypoint-fetch protocol)
const res = await env.WEBAPP.fetch(
new Request(`https://form${prefill}`, { redirect: "manual" }),
);
html = await res.text();
html = html.replace('action="ACTION"', 'action="/_mint"');
} catch (err) {
console.error({ event: "mint-page", error: String(err) });
return home(env, { error: "mint form unreachable (webapp worker down?)" }, null);
}
return new Response(html, { headers: { "content-type": "text/html;charset=utf-8" } });
}
/** the mint relay: the raw form body passes through untouched into the
* WEBAPP entrypoint's HTTP surface (webapp parses its own fields; the
* cookie crosses browser→here→binding→webapp's DO and no code on this
* side opens it) — a true conduit */
async function proxyMint(request: Request, env: Env): Promise<Response> {
try {
const res = await env.WEBAPP.fetch(
new Request("https://mint/", {
method: "POST",
headers: request.headers,
body: await request.arrayBuffer(),
}),
);
if (!res.ok) {
const detail = (await res.text()).slice(0, 200);
return home(env, { error: `mint said ${res.status}: ${detail}` }, null);
}
// webapp answers {id} (+ x-webapp-id); the id rides the header, the
// wire page is ours
const id = res.headers.get("x-webapp-id");
if (!id) return home(env, { error: "mint produced no id" }, null);
return await wirePage(id);
} catch (err) {
console.error({ event: "mint", error: String(err) });
return home(env, { error: `mint failed: ${String(err)}` }, null);
}
}
/** the credential-save helper, once per page (see ./pm-save.ts) */
const PM_SAVE_JS = pmSave.toString();
/** the suggested petname gets the holder's local hh:mm (the worker only
* knows UTC), so two saves the same day are told apart at a glance */
const PETNAME_TIME_JS = `{
const p = document.getElementById("petname");
const d = new Date();
p.value += " " + String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0");
}`;
/** the onclick that hands pmSave its browser powers */
function pmSaveClick(value: string): string {
return `pmSave(this, ${JSON.stringify(value)}, { petname: document.getElementById("petname"), credentials: navigator.credentials, PasswordCredential: window.PasswordCredential, log: console })`;
}
/** the wire step, with the freshly-minted webapp id pre-filled */
async function wirePage(webappId: string): Promise<Response> {
const fingerprint = await nick(webappId);
const body = `<!doctype html>
<html><head><meta charset="utf-8"><title>diigo cache: step 2 — wire the cache</title></head>
<body>
<h1>step 2: wire the cache</h1>
<p>minted: webapp id, fingerprint <code>${esc(fingerprint)}</code>
<button type="button" onclick='navigator.clipboard.writeText(${JSON.stringify(webappId)}).then(() => this.textContent = "copied ✓")'>copy</button></p>
<p><label>your petname for it <input id="petname" autocomplete="off" size="30" value="${esc(`diigo webapp ${fingerprint}`)}"></label>
<small>(private to you: the password-manager username; never sent to the server)</small></p>
<script>${PETNAME_TIME_JS}</script>
<p><button type="button" onclick='${pmSaveClick(webappId)}'>save to password manager</button></p>
<p>choose the cache mode, then <b>wire</b> — the next page shows the
<b>cache id</b> (copy that too), after which you land back on home:</p>
<form method="post" action="/_wire">
<input type="hidden" name="webappId" value="${esc(webappId)}">
<p><label>mode <select name="mode"><option value="private">private</option><option value="public">public (serves /public/&lt;your-diigo-username&gt;)</option></select></label> <button type="submit">wire →</button></p>
</form>
<p>change your mind? <a href="/_connect">mint again</a> · <a href="/">home</a></p>
<script>${PM_SAVE_JS}</script>
</body></html>`;
return new Response(body, {
headers: {
"content-type": "text/html;charset=utf-8",
"x-webapp-id": webappId,
},
});
}
/**
* the wire step: a webapp id plus the public/private choice. The cache is
* minted, wired to {webappId, publicId}, and page 1 is stored. In public
* mode the diigo username is read from the fetched items (the cookie's
* own account, never form input), and the public cache is wired to the
* same webapp id and registered under it. No cookie arrives here.
*/
async function wire(request: Request, env: Env): Promise<Response> {
const ct = request.headers.get("content-type") ?? "";
let webappId = "";
let mode = "private";
let wantsJson = false;
try {
if (ct.includes("application/json")) {
const body = (await request.json()) as { webappId?: string; mode?: string };
webappId = String(body.webappId ?? "");
mode = String(body.mode ?? "private");
wantsJson = true;
} else {
const form = await request.formData();
webappId = String(form.get("webappId") || "");
mode = String(form.get("mode") || "private");
// a browser form POST stays on the html path; only explicit JSON
// (service callers) gets the bare-JSON response
wantsJson = false;
}
} catch (err) {
return bad(`bad input: ${String(err)}`);
}
if (!/^[A-Za-z0-9-]+$/.test(webappId)) return bad("no webapp id supplied");
const publicId = mode === "public" ? toWebkey(env.PUBLIC_DO.newUniqueId()) : undefined;
const cacheId = toWebkey(env.CACHE_DO.newUniqueId());
const cacheStub = env.CACHE_DO.get(env.CACHE_DO.idFromString(idFromWebkey(cacheId)));
await cacheStub.setup({ webappId, publicId });
const first = await cacheStub.page(1, PAGE_SIZE);
if (publicId) {
const firstItem = first.items[0] ? (JSON.parse(first.items[0]) as Item) : undefined;
const username = usernameOf(firstItem);
if (!username) {
// diagnostic context without item contents (privacy: items may
// carry URL/titles; the count + cached flag are safe)
console.error({
event: "wire",
stage: "username-derive",
// field names, not values: says which shape we got
itemFields: firstItem ? Object.keys(firstItem) : null,
itemsOnPage1: first.items.length,
total: first.total,
cached: first.cached,
});
return bad("could not read your diigo username (u_name) from the fetched items");
}
const index = env.PUBLIC_DO.get(env.PUBLIC_DO.idFromName("index"));
const pubStub = env.PUBLIC_DO.get(env.PUBLIC_DO.idFromString(idFromWebkey(publicId)));
await pubStub.setup({ webappId });
await index.register(username, publicId);
if (wantsJson) return Response.json({ cacheId, publicId, username });
return wiredPage(cacheId, `public cache live at <a href="/public/${esc(encodeURIComponent(username))}">/public/${esc(username)}</a>`, true);
}
if (wantsJson) {
return Response.json({
cacheId,
publishLater: { method: "POST", url: `${new URL(request.url).origin}/_publish`, body: { cacheId } },
});
}
return wiredPage(
cacheId,
`private-only for now — to add the public cache later:
<form method="post" action="/_publish" style="display:inline">
<input type="hidden" name="cacheId" value="${esc(cacheId)}">
<button type="submit">publish</button></form>
(or <code>POST /_publish</code> with <code>cacheId</code> in the body)`,
false,
);
}
/** the created-cache page: ids + save/copy buttons + the pointer home */
async function wiredPage(cacheId: string, note: string, hasPublic: boolean): Promise<Response> {
const fingerprint = await nick(cacheId);
const body = `<!doctype html>
<html><head><meta charset="utf-8"><title>diigo cache: created</title></head>
<body>
<h1>cache created</h1>
<p><b>cache id</b>, fingerprint <code>${esc(fingerprint)}</code>
<button type="button" onclick='navigator.clipboard.writeText(${JSON.stringify(cacheId)}).then(() => this.textContent = "copied ✓")'>copy</button></p>
<p><label>your petname for it <input id="petname" autocomplete="off" size="30" value="${esc(`diigo cache ${fingerprint}`)}"></label>
<small>(private to you: the password-manager username; never sent to the server)</small></p>
<script>${PETNAME_TIME_JS}</script>
<p><button type="button" onclick='${pmSaveClick(cacheId)}'>save to password manager</button></p>
<p>${note}</p>
<p><a href="/cache/#${esc(cacheId)}">open this cache</a> — its <b>webkey</b>
(bookmark it, or save the id above): fill it, watch progress${hasPublic ? ", fill its public companion" : ""}.</p>
<p>the cache id is the only way back to this cache — saved (above) it lives
with the rest of your credentials. it is a <b>webkey</b>: it never rides a
query string or path (those leak to history/Referer/logs). the link above
carries it in the fragment, which browsers never send; the dump POST
carries it in its body. the webapp id rides inside the cache's wiring;
hold it separately only if you want another cache off the same session.</p>
<a href="/">← home (paste the cache id into the dump form)</a>
<script>${PM_SAVE_JS}</script>
</body></html>`;
return new Response(body, { headers: { "content-type": "text/html;charset=utf-8" } });
}
/** a fill job's progress, as one line of page text */
function fillLine(fill: FillStatus): string {
const of = `${Math.max(0, fill.nextPage - 1)} of ${fill.pages ?? "?"} pages`;
const said = {
running: `filling: ${of}`,
done: `filled: ${of}`,
stopped: `fill stopped: ${of}`,
failed: `fill failed at page ${fill.nextPage}: ${fill.error ?? "unknown error"}`,
}[fill.state];
return `<p>${esc(said)}</p>`;
}
/**
* publish, later: adds a public companion to a cache wired private-only.
* Its wiring already holds the webapp id, so no re-mint; the username
* comes from the items already cached. The cache id rides the POST body.
*/
async function publishCache(request: Request, env: Env): Promise<Response> {
let cacheId = "";
try {
const ct = request.headers.get("content-type") ?? "";
if (ct.includes("application/json")) {
const body = (await request.json()) as { cacheId?: string };
cacheId = String(body.cacheId ?? "");
} else {
const form = await request.formData();
cacheId = String(form.get("cacheId") || "");
}
} catch (err) {
return bad(`bad input: ${String(err)}`);
}
if (!isWebkey(cacheId) && !/^[0-9a-fA-F]{64}$/.test(cacheId)) {
return bad("no cache id supplied (POST body: cacheId)");
}
try {
const ns = env.CACHE_DO;
const cache = ns.get(ns.idFromString(idFromWebkey(cacheId)));
const wiring = await cache.wiring();
if (!wiring) {
return Response.json({ error: "unknown cache id" }, { status: 404 });
}
if (wiring.publicId) {
return Response.json({ cacheId, publicId: wiring.publicId, status: "already published" });
}
// the username comes from the items: the cookie's own account
const firstPage = await cache.page(1, PAGE_SIZE);
const firstItem = firstPage.items[0] ? (JSON.parse(firstPage.items[0]) as Item) : undefined;
const username = usernameOf(firstItem);
if (!username) {
console.error({
event: "publish",
stage: "username-derive",
// field names, not values: says which shape we got
itemFields: firstItem ? Object.keys(firstItem) : null,
itemsOnPage1: firstPage.items.length,
total: firstPage.total,
cached: firstPage.cached,
});
return Response.json(
{ error: "could not read your diigo username (u_name) from the cached items" },
{ status: 400 },
);
}
const publicId = toWebkey(env.PUBLIC_DO.newUniqueId());
const pubStub = env.PUBLIC_DO.get(env.PUBLIC_DO.idFromString(idFromWebkey(publicId)));
await pubStub.setup({ webappId: wiring.webappId });
await cache.addPublic(publicId);
const index = env.PUBLIC_DO.get(env.PUBLIC_DO.idFromName("index"));
await index.register(username, publicId);
return Response.json({ cacheId, publicId, username, public: `/public/${username}` });
} catch (err) {
// no cacheId in the log: it is the bearer secret
console.error({ event: "publish", error: String(err) });
return Response.json({ error: `publish failed: ${String(err)}` }, { status: 400 });
}
}
function bad(message: string): Response {
return Response.json({ error: message }, { status: 400 });
}
/** the private dump POST: cache id from the (client-wired) form value */
async function dump(request: Request, env: Env): Promise<Response> {
const form = await request.formData();
const cacheId = String(form.get("cacheId") || "");
const raw = form.get("page");
const pageN = typeof raw === "string" ? Number.parseInt(raw, 10) : Number.NaN;
if (!isWebkey(cacheId) && !/^[0-9a-fA-F]{64}$/.test(cacheId)) {
return home(env, { error: "wire a cache id first (create flow, then copy/paste)" }, null);
}
if (Number.isNaN(pageN) || pageN < 1 || pageN > 10000) {
return home(env, { error: "enter a page number (1 = most recently updated)" }, null);
}
try {
const ns = env.CACHE_DO;
const cache = ns.get(ns.idFromString(idFromWebkey(cacheId)));
const page = await cache.page(pageN, PAGE_SIZE);
const data = `total: ${page.total}\nitems: ${page.items.length}\ncache: ${page.cached ? "HIT (from storage)" : "MISS (etched now)"}` +
`\n\n${page.items.join("\n")}`;
return home(env, null, data, cacheId);
} catch (err) {
console.error({ event: "dump", page: pageN, error: String(err) });
return home(env, null, String(err), cacheId);
}
}
const PUBLIC_PER_PAGE = PAGE_SIZE;
/** the public page's day presets */
const DAY_PRESETS = [7, 30, 90, 365];
/**
* the public page for a username: stored pages only, through the cache's
* read-only `viewer()` (it can't fetch or write). HTML with a filter form
* and a page-number form, or JSON for `Accept: application/json`. A
* filter (goal 1d: `days`, `after`, `before`, `in`, `by`, `q`; see
* {@link parseQuery}) lists the stored items that match, `page` counting
* matches; with none, `page` is diigo's page as stored. Query params are
* fine here: nothing on this page is secret.
*/
async function publicPage(request: Request, env: Env, username: string): Promise<Response> {
const index = env.PUBLIC_DO.get(env.PUBLIC_DO.idFromName("index"));
const publicId = await index.lookup(username);
if (!publicId) return new Response("no such public cache", { status: 404 });
const ns = env.PUBLIC_DO;
const cache = ns.get(ns.idFromString(idFromWebkey(publicId)));
const params = new URL(request.url).searchParams;
const accept = request.headers.get("accept") ?? "";
const wantsJson = accept.includes("application/json") && !accept.includes("text/html");
const here = `/public/${encodeURIComponent(username)}`;
const raw = params.get("page");
const pageN = raw === null ? 1 : Number.parseInt(raw, 10);
const valid = !Number.isNaN(pageN) && pageN >= 1 && pageN <= 10000;
const query = parseQuery(params, new Date());
if ("error" in query) {
console.log({ event: "notice", page: "public", text: "filter refused", error: query.error });
if (wantsJson) return Response.json({ error: query.error }, { status: 400 });
const body = publicFrame(username, `${filterForm(here, params)}
<p><em>${esc(query.error)}</em></p>`);
return new Response(body, { status: 400, headers: { "content-type": "text/html;charset=utf-8" } });
}
const viewer = await cache.viewer();
let page, fill, found;
let total: number | null = null;
try {
if (isEmpty(query)) {
page = await viewer.page(valid ? pageN : 1, PUBLIC_PER_PAGE);
total = page ? page.total : await viewer.knownTotal();
} else {
found = await viewer.query(query, valid ? pageN : 1, PUBLIC_PER_PAGE);
}
fill = await viewer.fillStatus();
} catch (err) {
console.error({ event: "public-page", page: pageN, error: String(err) });
return new Response(`could not load page ${valid ? pageN : 1}: ${String(err)}`, { status: 502 });
} finally {
viewer[Symbol.dispose]();
}
if (found) return filteredPage(username, here, params, query, found, valid ? pageN : 1, wantsJson, fill);
// total and pages count all of diigo's items: public page n is diigo
// page n with the private rows dropped
const pages = total === null ? 1 : Math.max(1, Math.ceil(total / PUBLIC_PER_PAGE));
const items = page ? page.items.map((j) => JSON.parse(j) as Item) : [];
if (wantsJson) {
return Response.json({ username, page: pageN, pages, total, stored: page !== null, etchedAt: page?.etchedAt ?? null, items });
}
let notice = "";
if (!valid || pageN > pages) {
console.log({ event: "notice", page: "public", text: "page out of range", pages });
notice = `<p><em>no page ${esc(String(raw))}: pages run 1–${pages}</em></p>`;
}
const nav = (n: number, label: string) =>
n >= 1 && n <= pages ? `<a rel="${n < pageN ? "prev" : "next"}" href="${here}?page=${n}">${label}</a>` : `<span>${label}</span>`;
const list = notice ? "" : itemList(items, "updated", here);
const body = publicFrame(
username,
`<p>${pages} page${pages === 1 ? "" : "s"} (diigo's, ${PUBLIC_PER_PAGE} bookmarks each; private ones are left out, so a page may show fewer).</p>
<p>${page ? `<strong>stored ${esc(page.etchedAt ?? "")}</strong> — page ${valid ? pageN : 1}, ${items.length} shared` : `<strong>not fetched yet</strong> — page ${valid ? pageN : 1}; the cache's owner fills it`}</p>
${fill ? fillLine(fill) : ""}
${filterForm(here, params)}
<form method="get" action="${here}">
<p>${nav(pageN - 1, "← prev")}
<label>page <input type="number" name="page" min="1" value="${Number.isNaN(pageN) ? 1 : pageN}"></label>
<button type="submit">go</button>
${nav(pageN + 1, "next →")}</p>
</form>
${notice}${list}`,
);
return new Response(body, { headers: { "content-type": "text/html;charset=utf-8" } });
}
/** a filter's matches, as the public page's HTML or JSON */
function filteredPage(
username: string,
here: string,
params: URLSearchParams,
query: Query,
found: QueryPage,
pageN: number,
wantsJson: boolean,
fill: FillStatus | undefined,
): Response {
const pages = Math.max(1, Math.ceil(found.matched / PUBLIC_PER_PAGE));
const items = found.items.map((j) => JSON.parse(j) as Item);
if (wantsJson) {
const { matched, complete } = found;
return Response.json({ username, filter: query, page: pageN, pages, matched, complete, items });
}
// links keep the filter: the request's own non-empty params, in order
const kept = [...params].filter(([k, v]) => k !== "page" && v !== "");
const href = (n: number) => `${here}?${new URLSearchParams([...kept, ["page", String(n)]])}`;
const nav = (n: number, label: string) =>
n >= 1 && n <= pages ? `<a rel="${n < pageN ? "prev" : "next"}" href="${esc(href(n))}">${label}</a>` : `<span>${label}</span>`;
const status = found.matched
? `${found.matched} match${found.matched === 1 ? "" : "es"}, page ${pageN} of ${pages}, newest ${query.by} first`
: "no matches";
const caveat = found.complete ? "" : " — not every diigo page is stored yet, so some matches may be missing";
const body = publicFrame(
username,
`<p><strong>${esc(status)}</strong>${caveat}</p>
${fill ? fillLine(fill) : ""}
${filterForm(here, params)}
<p>${nav(pageN - 1, "← prev")} ${nav(pageN + 1, "next →")} <a href="${here}">all, by diigo page</a></p>
${itemList(items, query.by, here)}`,
);
return new Response(body, { headers: { "content-type": "text/html;charset=utf-8" } });
}
/** the public page's frame: title and heading around `content` */
function publicFrame(username: string, content: string): string {
return `<!doctype html>
<html><head><meta charset="utf-8"><title>${esc(username)}'s shared bookmarks</title></head>
<body>
<h1>${esc(username)}'s shared bookmarks</h1>
${content}
</body></html>`;
}
/** the filter form, echoing the request's filter */
function filterForm(here: string, params: URLSearchParams): string {
const field = (name: string) => esc(params.get(name) ?? "");
const days = params.get("days") ?? "";
const presets = DAY_PRESETS.map(String);
if (days && !presets.includes(days)) presets.push(days);
const option = (value: string, label: string, current: string) =>
`<option value="${esc(value)}"${value === current ? " selected" : ""}>${esc(label)}</option>`;
return `<form method="get" action="${here}">
<p><label>last <select name="days">${option("", "any", days)}${presets.map((n) => option(n, `${n} days`, days)).join("")}</select></label>
<label>or after <input type="date" name="after" value="${field("after")}"></label>
<label>before <input type="date" name="before" value="${field("before")}"></label>
<label>or in <input name="in" size="9" placeholder="2026-W41" value="${field("in")}"></label>
<label>by <select name="by">${option("updated", "updated", params.get("by") ?? "")}${option("created", "created", params.get("by") ?? "")}</select></label></p>
<p><label>search <input type="search" name="q" size="40" value="${field("q")}"></label>
<button type="submit">filter</button></p>
<p><small>Dates and periods (2026, 2026-03, 2026-Q1, 2026-W41) are UTC. Search takes
words, "phrases", #tags, -negation, and after:, before:, newer_than:7d, during:2026-Q1, created:2026.</small></p>
</form>`;
}
/**
* bookmarks as a list, each led by its `by` date, marked up as
* microformats: an `h-feed` of `h-entry` bookmarks (`u-bookmark-of`,
* `p-name`, `p-summary`, `p-category` per tag, `dt-published` when
* bookmarked, `dt-updated` when last edited). This markup is the public
* page's API for other sites (tests/caches.test.ts pins it); tag links
* search this page (`here`) by tag.
*
* @see https://microformats.org/wiki/h-entry
* @see https://indieweb.org/bookmark
*/
function itemList(items: Item[], by: Query["by"], here: string): string {
const time = (it: Item, which: Query["by"], hidden: boolean) => {
const secs = dateOf(it, which);
if (secs === undefined) return hidden ? "" : "(no date)";
const when = new Date(secs * 1000).toISOString();
const cls = which === "created" ? "dt-published" : "dt-updated";
return hidden ? `<time class="${cls}" datetime="${when}" hidden></time>` : `<time class="${cls}" datetime="${when}">${when}</time>`;
};
return `<ol class="h-feed">
${items
.map((it) => {
const url = typeof it.url === "string" ? it.url : "";
const title = typeof it.title === "string" && it.title ? it.title : url;
const desc = typeof it.description === "string" && it.description ? `<br><small class="p-summary">${esc(it.description)}</small>` : "";
const href = /^https?:\/\//i.test(url) ? url : "#";
const tags = (typeof it.tags === "string" ? it.tags.split(",") : [])
.map((t) => t.trim())
.filter(Boolean)
.map((t) => ` <a class="p-category" href="${esc(`${here}?q=${encodeURIComponent(`#${t}`)}`)}">${esc(t)}</a>`)
.join("");
const other = by === "created" ? "updated" : "created";
return `<li class="h-entry">${time(it, by, false)} <a class="u-bookmark-of p-name" href="${esc(href)}">${esc(title)}</a>${tags}${desc}${time(it, other, true)}</li>`;
})
.join("\n")}
</ol>`;
}
/** home page: the connect link (webapp's cookie form, diigo-prefilled) +
* the wire step for an already-minted id + the dump form. `home` renders
* the error path too, so it takes env for the connect link. Notices (the
* inert-GET explainer, probe failures) log at info — exceptional errors
* log at error in their own handlers. */
async function home(env: Env, opts: { error?: string } | null, data: string | null, cacheId?: string): Promise<Response> {
if (opts?.error) {
console.log({ event: "notice", page: "home", text: opts.error });
}
const cacheState = cacheId
? `<p>cache id, fingerprint <code>${esc(await nick(cacheId))}</code></p>`
: `<p>no cache id wired yet — use the create flow below (or paste one).</p>`;
const dumpForm = `<form method="post" action="/">
${cacheId ? `<input type="hidden" name="cacheId" value="${esc(cacheId)}">` : `<p><label>petname <input autocomplete="username" size="24"></label>
<label>cache id <input type="password" name="cacheId" autocomplete="current-password" size="24"></label></p>`}
<p><label>page <input type="number" name="page" min="1"></label> <button type="submit">dump</button></p>
</form>`;
const result = data
? `<pre readonly style="white-space:pre-wrap;border:1px solid #ccc;padding:1rem;max-height:60vh;overflow:auto">${escapeHtml(data)}</pre>`
: opts && opts.error
? `<p><em>${escapeHtml(opts.error)}</em></p>`
: "";
return new Response(
`<!doctype html>
<html><head><meta charset="utf-8"><title>diigo cache</title></head>
<body>
<h1>diigo cache</h1>
${cacheState}
<h2>create (two steps)</h2>
<ol>
<li><a href="/_connect">mint the diigo session at webapp</a> — webapp's
own mint form (diigo-prefilled); paste the Cookie header there. The
cookie transits this worker only as an opaque relay into webapp's DO;
nobody here opens it. Mint lands you on the wire step, id pre-filled.</li>
<li>wire the id into a cache (mode: public|private):</li>
</ol>
<form method="post" action="/_wire">
<p><label>petname <input autocomplete="username" size="24"></label>
<label>webapp id <input type="password" name="webappId" size="24" autocomplete="current-password"></label>
<label>mode <select name="mode"><option value="private">private</option><option value="public">public (serves /public/&lt;your-diigo-username&gt;)</option></select></label></p>
<p><button type="submit">wire</button></p>
</form>
<p>the ids this mints are for <b>you</b>: copy them somewhere you control (password manager)</p>
<p><a href="/cache/">open a cache</a> — fill it, watch progress (your password manager can fill in the cache id)</p>
${dumpForm}
${result}
</body></html>`,
{ headers: { "content-type": "text/html;charset=utf-8" } },
);
}
/** a short display name for a bearer id: a prefix of its swissHash
* (identity without authority), so labels and pages never show any
* glyphs of the key itself */
async function nick(id: string): Promise<string> {
return (await shashKey(id)).slice(0, 8);
}
function esc(s: string): string {
return s
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
const escapeHtml = esc;
+74
View File
@@ -0,0 +1,74 @@
/**
* @file diigo interact_api items: the field-reading helpers (pure, so
* tests can feed them rows shaped like diigo's).
*/
/** one diigo item exactly as the interact_api returned it */
export type Item = Record<string, unknown>;
/** the fields stored per item (the raw row rides in `json`) */
export type ItemRow = {
itemId: string;
url: string;
title: string;
private: boolean;
/** the raw dump row, JSON-encoded */
json: string;
updated: string;
};
/** diigo's id for a bookmark (`link_id`), as text; "" when absent */
function linkIdOf(it: Item): string {
return typeof it.link_id === "number" || (typeof it.link_id === "string" && it.link_id !== "")
? String(it.link_id)
: "";
}
/**
* normalize one page of interact_api items into storable rows. Items
* that can't be stored (no url, no link_id) are logged and skipped —
* never merged under a made-up key. Logs name the fields present, not
* their values (items may be private).
*/
export function toRows(items: Item[], log: Pick<Console, "warn">): ItemRow[] {
const rows: ItemRow[] = [];
for (const it of items) {
const itemId = linkIdOf(it);
const url = typeof it.url === "string" ? it.url : "";
if (!itemId || !url) {
log.warn({ event: "item-skip", reason: !itemId ? "no link_id" : "no url", fields: Object.keys(it) });
continue;
}
rows.push({
itemId,
url,
title: String(it.title ?? url),
private: it.private !== undefined ? Boolean(it.private) : String(it.shared) !== "yes",
json: JSON.stringify(it),
updated: String(it.updated_at ?? it.created_at ?? ""),
});
}
return rows;
}
/** the diigo username an item belongs to (`u_name`; not `first_by`,
* who may be whoever bookmarked the URL first), or "" when the item
* carries none in the expected shape */
export function usernameOf(item: Item | undefined): string {
const username = typeof item?.u_name === "string" ? item.u_name : "";
return /^[A-Za-z0-9_-]{1,64}$/.test(username) ? username : "";
}
/** the public cache's filter: shared rows only. Applied before etching,
* so private rows never reach public storage. */
export function publicOnly(rows: ItemRow[]): ItemRow[] {
return rows.filter((r) => !r.private);
}
/** when diigo last updated the item, as `Date#toISOString()`, or "" when
* it carries no usable `updated_at` (diigo sends epoch *seconds*) */
export function updatedISO(item: Item): string {
const secs = item.updated_at;
if (typeof secs !== "number" || !Number.isFinite(secs)) return "";
return new Date(secs * 1000).toISOString();
}
+55
View File
@@ -0,0 +1,55 @@
/** @file the password-manager save, run in the browser (embedded via `pmSave.toString()`). */
/** the browser powers pmSave uses */
export type PmPowers = {
petname: { value: string };
credentials?: { store(credential: unknown): Promise<unknown> };
PasswordCredential?: new (init: { id: string; password: string }) => unknown;
log: Pick<Console, "info" | "warn" | "error">;
};
/** the button pmSave reports on */
export type PmButton = { textContent: string | null; disabled: boolean };
/**
* gesture-gated save of `value` under the holder's petname (the PM
* username). Ids reach the browser's storage only this way (or by copy),
* never localStorage/IndexedDB, which are ambient and XSS-reachable.
*
* Pages embed it with `pmSave.toString()`, so it must be self-contained:
* no imports, no closures, no inner named functions (wrangler's keepNames
* would wrap those in an `__name` helper the browser lacks). Its powers
* (petname field, credential store, console) are passed in, so tests can
* stand in for the browser.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/store
*/
export function pmSave(btn: PmButton, value: string, powers: PmPowers): Promise<void> {
const label = powers.petname.value.trim();
if (!label) {
btn.textContent = "give it a petname first";
return Promise.resolve();
}
btn.disabled = true;
if (!powers.PasswordCredential || !powers.credentials) {
powers.log.warn({ event: "pm-save", outcome: "unsupported", detail: "no PasswordCredential / navigator.credentials" });
btn.textContent = "browser has no credential store — copy instead";
btn.disabled = false;
return Promise.resolve();
}
return powers.credentials
.store(new powers.PasswordCredential({ id: label, password: value }))
.then(() => {
// store() resolves with undefined per spec, whether the holder
// accepted the browser's prompt or not (or no prompt showed):
// we can only say it was offered — the PM's own UI is the truth
powers.log.info({ event: "pm-save", outcome: "offered", label });
btn.textContent = "offered to the password manager ✓ (see its prompt)";
btn.disabled = false;
})
.catch((err) => {
powers.log.error({ event: "pm-save", error: String(err) });
btn.textContent = "save failed — copy instead";
btn.disabled = false;
});
}
+264
View File
@@ -0,0 +1,264 @@
/**
* @file the public page's filters: date windows and search over a cache's
* stored items (goal 1d; tests/query.test.ts).
*/
import type { Item } from "./items.js";
/**
* a filter as devs write it (`{ days: 7, q: "#weekly" }`); URL params map
* onto these fields one-to-one (strings, with "" meaning absent). Dates
* are `yyyy-mm-dd` (gmail's `yyyy/mm/dd` too); periods are `2025`,
* `2025-03`, `2025-Q1`, or ISO week `2025-W01`. Time is UTC throughout;
* ISO weeks start Monday, keeping a weekend together.
*/
export type FilterSpec = {
/** the last N days, counted back from now (1–3650) */
days?: number | string;
/** inclusive lower bound, from 00:00Z */
after?: string;
/** exclusive upper bound, at 00:00Z */
before?: string;
/** a named period: shorthand for its after/before pair */
in?: string;
/** which date the window, the listed date, and the sort use */
by?: "updated" | "created" | "";
/** words, phrases, tags, and operators */
q?: string;
};
/** one search term; `negated` for a leading `-` */
export type Term = { text: string; negated: boolean };
/** a parsed filter; an empty one (no window, no terms) filters nothing */
export type Query = {
/** which date the window, the listed date, and the sort use (default
* `updated`, diigo's own order) */
by: "updated" | "created";
/** inclusive lower bound */
after?: Date;
/** exclusive upper bound */
before?: Date;
/** words and phrases: each must appear in title, description, or url */
words: Term[];
/** tags: exact, case-insensitive match against the item's tags */
tags: Term[];
};
/** a refused filter: the message is safe to show and log */
export type QueryError = { error: string };
const DAY_MS = 24 * 60 * 60 * 1000;
/** thrown inside {@link toQuery}, returned as a {@link QueryError} */
class Refused extends Error {}
/** `yyyy-mm-dd` or `yyyy/mm/dd` as 00:00Z of that UTC day */
function parseDay(text: string, what: string): Date {
const m = /^(\d{4})([-/])(\d{2})\2(\d{2})$/.exec(text);
const d = m && new Date(Date.UTC(Number(m[1]), Number(m[3]) - 1, Number(m[4])));
if (!m || !d || d.getUTCMonth() !== Number(m[3]) - 1 || d.getUTCDate() !== Number(m[4])) {
throw new Refused(`${what}: expected a date as yyyy-mm-dd`);
}
return d;
}
/** Monday 00:00Z of ISO week 1 of `year` (the week holding January 4) */
function isoWeekOne(year: number): number {
const jan4 = Date.UTC(year, 0, 4);
const weekday = new Date(jan4).getUTCDay() || 7;
return jan4 - (weekday - 1) * DAY_MS;
}
/** a named period as its half-open [after, before) window */
function parsePeriod(text: string, what: string): [Date, Date] {
const refuse = () => new Refused(`${what}: expected a period as 2025, 2025-03, 2025-Q1, or 2025-W01`);
let m;
if ((m = /^(\d{4})$/.exec(text))) {
const y = Number(m[1]);
return [new Date(Date.UTC(y, 0, 1)), new Date(Date.UTC(y + 1, 0, 1))];
}
if ((m = /^(\d{4})-(\d{2})$/.exec(text))) {
const [y, mo] = [Number(m[1]), Number(m[2])];
if (mo < 1 || mo > 12) throw refuse();
return [new Date(Date.UTC(y, mo - 1, 1)), new Date(Date.UTC(y, mo, 1))];
}
if ((m = /^(\d{4})-Q([1-4])$/.exec(text))) {
const [y, q] = [Number(m[1]), Number(m[2])];
return [new Date(Date.UTC(y, 3 * (q - 1), 1)), new Date(Date.UTC(y, 3 * q, 1))];
}
if ((m = /^(\d{4})-W(\d{2})$/.exec(text))) {
const [y, w] = [Number(m[1]), Number(m[2])];
const weeks = (isoWeekOne(y + 1) - isoWeekOne(y)) / (7 * DAY_MS);
if (w < 1 || w > weeks) throw refuse();
const monday = isoWeekOne(y) + (w - 1) * 7 * DAY_MS;
return [new Date(monday), new Date(monday + 7 * DAY_MS)];
}
throw refuse();
}
/** gmail's `newer_than:` amount (`7d`, `2w`, `1m`, `1y`) counted back from
* `now`; months and years are calendar steps */
function parseNewerThan(text: string, now: Date): Date {
const m = /^(\d{1,4})([dwmy])$/.exec(text);
if (!m || Number(m[1]) < 1) throw new Refused("newer_than: expected an amount like 7d, 2w, 1m, or 1y");
const n = Number(m[1]);
const d = new Date(now.getTime());
if (m[2] === "d") d.setTime(now.getTime() - n * DAY_MS);
if (m[2] === "w") d.setTime(now.getTime() - 7 * n * DAY_MS);
if (m[2] === "m") d.setUTCMonth(d.getUTCMonth() - n);
if (m[2] === "y") d.setUTCFullYear(d.getUTCFullYear() - n);
return d;
}
/** `days` as a whole number from 1 to 3650 */
function parseDays(days: number | string): number {
const n = typeof days === "number" ? days : /^\d+$/.test(days) ? Number(days) : NaN;
if (!Number.isInteger(n) || n < 1 || n > 3650) throw new Refused("days: expected a whole number from 1 to 3650");
return n;
}
/**
* resolve a filter: fields and `q` operators combine; a bound given twice
* (by fields, operators, or both) is refused, as is an empty window.
*
* `q` takes the operators large audiences know: gmail's `after:`,
* `before:`, `newer_than:7d`; Slack's `during:` (alias `in:`); GitHub's
* `created:`/`updated:` with a period; plus words, `"phrases"`,
* `#tag`/`tag:tag`, and `-` negation. Every window is half-open: `after`
* inclusive from 00:00Z, `before` exclusive at 00:00Z (so no inclusive
* GitHub `a..b` ranges).
*
* @see https://mailmeteor.com/blog/search-gmail-by-date
* @see https://slack.com/help/articles/202528808
* @see https://docs.github.com/en/search-github/searching-on-github/searching-for-repositories
*
* @param now the clock `days`/`newer_than` count back from (passed in,
* not read ambiently, so tests pin it)
*/
export function toQuery(spec: FilterSpec, now: Date): Query | QueryError {
try {
return resolve(spec, now);
} catch (err) {
if (err instanceof Refused) return { error: err.message };
throw err;
}
}
function resolve(spec: FilterSpec, now: Date): Query {
const words: Term[] = [];
const tags: Term[] = [];
let by: { value: Query["by"]; from: string } | undefined;
let after: { value: Date; from: string } | undefined;
let before: { value: Date; from: string } | undefined;
const setBy = (value: Query["by"], from: string) => {
if (by && by.value !== value) throw new Refused(`${by.from} and ${from} name different dates`);
by = { value, from };
};
const setAfter = (value: Date, from: string) => {
if (after) throw new Refused(`${after.from} and ${from} both set where the window starts`);
after = { value, from };
};
const setBefore = (value: Date, from: string) => {
if (before) throw new Refused(`${before.from} and ${from} both set where the window ends`);
before = { value, from };
};
const setPeriod = ([lo, hi]: [Date, Date], from: string) => {
setAfter(lo, from);
setBefore(hi, from);
};
const present = (v: string | number | undefined) => v !== undefined && v !== "";
if (present(spec.by)) {
if (spec.by !== "updated" && spec.by !== "created") throw new Refused("by: expected updated or created");
setBy(spec.by, `by=${spec.by}`);
}
if (present(spec.days)) setAfter(new Date(now.getTime() - parseDays(spec.days!) * DAY_MS), "days");
if (present(spec.after)) setAfter(parseDay(spec.after!, "after"), "after");
if (present(spec.before)) setBefore(parseDay(spec.before!, "before"), "before");
if (present(spec.in)) setPeriod(parsePeriod(spec.in!, "in"), "in");
for (const m of (spec.q ?? "").matchAll(/(-?)"([^"]*)"|(\S+)/g)) {
if (m[2] !== undefined) {
if (m[2].trim()) words.push({ text: m[2].trim().toLowerCase(), negated: m[1] === "-" });
continue;
}
const token = m[3];
const negated = token.length > 1 && token.startsWith("-");
const body = negated ? token.slice(1) : token;
const op = /^([a-z_]+):(.+)$/i.exec(body);
const name = op?.[1].toLowerCase();
const arg = op?.[2] ?? "";
const windowOp = ["after", "before", "newer_than", "during", "in", "created", "updated"];
if (name && windowOp.includes(name) && negated) throw new Refused(`${name}: can't be negated`);
if (name === "after") setAfter(parseDay(arg, "after:"), "after:");
else if (name === "before") setBefore(parseDay(arg, "before:"), "before:");
else if (name === "newer_than") setAfter(parseNewerThan(arg, now), "newer_than:");
else if (name === "during" || name === "in") setPeriod(parsePeriod(arg, `${name}:`), `${name}:`);
else if (name === "created" || name === "updated") {
setBy(name, `${name}:`);
setPeriod(parsePeriod(arg, `${name}:`), `${name}:`);
} else if (name === "tag") tags.push({ text: arg.toLowerCase(), negated });
else if (body.length > 1 && body.startsWith("#")) tags.push({ text: body.slice(1).toLowerCase(), negated });
else words.push({ text: body.toLowerCase(), negated });
}
if (after && before && after.value.getTime() >= before.value.getTime()) {
throw new Refused(`the window is empty: ${after.from} is not earlier than ${before.from}`);
}
const query: Query = { by: by?.value ?? "updated", words, tags };
if (after) query.after = after.value;
if (before) query.before = before.value;
return query;
}
/** {@link toQuery} over the public page's URL params */
export function parseQuery(params: URLSearchParams, now: Date): Query | QueryError {
const field = (name: string) => params.get(name) ?? "";
const by = field("by");
return toQuery(
{
days: field("days"),
after: field("after"),
before: field("before"),
in: field("in"),
by: by as FilterSpec["by"],
q: field("q"),
},
now,
);
}
/** does the query filter anything? (an empty one lists diigo's pages as stored) */
export function isEmpty(query: Query): boolean {
return !query.after && !query.before && !query.words.length && !query.tags.length && query.by === "updated";
}
/** the item's date that `by` names, in epoch seconds (diigo's unit), or
* undefined when it carries none */
export function dateOf(item: Item, by: Query["by"]): number | undefined {
const secs = by === "created" ? item.created_at : item.updated_at;
return typeof secs === "number" && Number.isFinite(secs) ? secs : undefined;
}
/** does `item` fall in the window and satisfy every term? */
export function matches(item: Item, query: Query): boolean {
if (query.after || query.before) {
const secs = dateOf(item, query.by);
if (secs === undefined) return false;
if (query.after && secs * 1000 < query.after.getTime()) return false;
if (query.before && secs * 1000 >= query.before.getTime()) return false;
}
const text = (v: unknown) => (typeof v === "string" ? v : "");
// fields joined by newline, so a phrase never spans two of them
const haystack = [item.title, item.description, item.url].map(text).join("\n").toLowerCase();
if (!query.words.every((w) => haystack.includes(w.text) !== w.negated)) return false;
const itemTags = new Set(
text(item.tags)
.split(",")
.map((t) => t.trim().toLowerCase())
.filter(Boolean),
);
return query.tags.every((t) => itemTags.has(t.text) !== t.negated);
}
+59
View File
@@ -0,0 +1,59 @@
/** @file cached diigo items as RSS 2.0, in the shape of diigo's RSS export. */
import type { Item } from "./items.js";
/** characters XML 1.0 forbids (the C0 controls but tab, LF, CR);
* diigo's export carries some raw, so strict parsers reject it */
const XML_FORBIDDEN = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g;
/** text as one or more CDATA sections: forbidden characters dropped,
* a literal `]]>` split across two sections */
function cdata(text: string): string {
return `<![CDATA[${text.replace(XML_FORBIDDEN, "").replaceAll("]]>", "]]]]><![CDATA[>")}]]>`;
}
const str = (v: unknown): string => (typeof v === "string" ? v : "");
const list = (v: unknown): Record<string, unknown>[] => (Array.isArray(v) ? (v as Record<string, unknown>[]) : []);
/**
* the packed description diigo's export uses:
* `Tags:a,b;Description:…;Annotations and Sticky notes:…` — tags
* comma-separated (`no_tag` when none), then each highlight as
* `Highlight:<text>\n` followed by its sticky notes, one
* `Sticky notes:<text>\n` each (notes may span lines). A diigo *note*
* item's body (`note_content`) comes first, as a `Highlight:` line.
*/
export function itemDescription(item: Item): string {
const tags = str(item.tags) || "no_tag";
const body = str(item.note_content) ? `Highlight:${str(item.note_content)}\n` : "";
const notes = list(item.annotations)
.map((a) => `Highlight:${str(a.content)}\n${list(a.stickyNotes).map((n) => `Sticky notes:${str(n.content)}\n`).join("")}`)
.join("");
return `Tags:${tags};Description:${str(item.description)};Annotations and Sticky notes:${body}${notes}`;
}
/** one `<item>`: title, link, packed description. The title is whole
* (diigo's export cuts titles at 255 characters). */
export function rssItem(item: Item): string {
return `<item><title>${cdata(str(item.title))}</title><link>${cdata(str(item.url))}</link><description>${cdata(itemDescription(item))}</description></item>`;
}
/**
* a whole feed
*
* @param channel `pubDate` in RFC 822 form is the caller's to supply
* (no clock here)
*/
export function toRss(items: Item[], channel: { title: string; pubDate: string }): string {
return `<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>${cdata(channel.title)}</title>
<link></link>
<pubDate>${channel.pubDate}</pubDate>
<lastBuildDate>${channel.pubDate}</lastBuildDate>
${items.map(rssItem).join("\n")}
</channel>
</rss>
`;
}
+18
View File
@@ -0,0 +1,18 @@
/**
* named statements from a .sql file: each `-- name:` line starts one,
* running to the next (a trailing `;` dropped). As `sqlStatements` in
* finquick's brcal/src/gcbook.js.
*/
export function sqlStatements(text: string): Record<string, string> {
const byName: Record<string, string> = {};
const chop = (lo: number, hi: number) => text.substring(lo, hi).replace(/;\s*$/, "").trim();
let pos = 0;
let name: string | undefined;
for (const m of text.matchAll(/^-- (?<name>[^:\n]+):\n/gm)) {
if (name) byName[name] = chop(pos, m.index);
pos = m.index + m[0].length;
name = m.groups?.name;
}
if (name) byName[name] = chop(pos, text.length);
return byName;
}
+5
View File
@@ -0,0 +1,5 @@
/** .sql files import as their text (wrangler.jsonc "rules": Text) */
declare module "*.sql" {
const text: string;
export default text;
}
+107
View File
@@ -0,0 +1,107 @@
/** @file a cache DO's SQL storage as two facets: a reader and a writer. */
import readText from "./cache-read.sql";
import writeText from "./cache-write.sql";
import type { ItemRow } from "./items.js";
import { sqlStatements } from "./sql-statements.js";
const READ = sqlStatements(readText);
const WRITE = sqlStatements(writeText);
for (const [name, statement] of Object.entries(READ)) {
if (!/^(select|with)\b/i.test(statement)) throw new Error(`cache-read.sql: ${name} is not a select`);
}
/** the SQL surface the facets need (a DO's `ctx.storage.sql`) */
type Sql = Pick<SqlStorage, "exec">;
/** one cached page, raw: `items` are the dump rows (JSON strings) */
export type StoredPage = { total: number; items: string[]; etchedAt: string };
/**
* read-only access to a cache's pages and items: runs only the statements
* in cache-read.sql (all `select`s, checked when the module loads), so
* whoever holds only a reader cannot change storage
*/
export function makeReader(sql: Sql) {
const run = <T extends Record<string, SqlStorageValue>>(name: string, ...params: SqlStorageValue[]): T[] =>
sql.exec<T>(READ[name], ...params).toArray();
return Object.freeze({
/** a cached page in its fetch-time order, or null if not cached at this size */
page(pageNum: number, count: number): StoredPage | null {
const [header] = run<{ total: number | null; etched_at: string }>("pageHeader", pageNum, count);
if (!header) return null;
const rows = run<{ json: string }>("pageItems", pageNum);
return { total: header.total ?? -1, items: rows.map((r) => r.json), etchedAt: header.etched_at };
},
/** diigo's total, from the most recently cached page that had one */
knownTotal(): number | null {
return run<{ total: number }>("knownTotal")[0]?.total ?? null;
},
/** the deepest cached page holding an item updated at or after `cutoff` (epoch seconds) */
deepestPageSince(cutoff: number): number | null {
return run<{ last: number | null }>("deepestPageSince", cutoff)[0]?.last ?? null;
},
/** stored items whose `by` date (epoch seconds) is in [`from`, `to`),
* newest first; the raw dump rows (JSON strings) */
itemsIn(by: "updated" | "created", from: number, to: number): string[] {
const name = by === "created" ? "itemsByCreated" : "itemsByUpdated";
return run<{ json: string }>(name, from, to).map((r) => r.json);
},
/** how many cached pages are numbered `pageNum` or lower */
pagesThrough(pageNum: number): number {
return Number(run<{ n: number }>("pagesThrough", pageNum)[0]?.n ?? 0);
},
});
}
export type Reader = ReturnType<typeof makeReader>;
/** the schema version storage is at (kv key "schema") */
export const SCHEMA_VERSION = 2;
/** write access to a cache's pages and items (the statements in
* cache-write.sql), each change one transaction */
export function makeWriter(storage: {
sql: Sql;
kv: Pick<SyncKvStorage, "get" | "put">;
transactionSync<T>(fn: () => T): T;
}) {
const run = (name: string, ...params: SqlStorageValue[]) => {
storage.sql.exec(WRITE[name], ...params);
};
return Object.freeze({
/** create tables, and migrate older storage; returns the version
* migrated from (= SCHEMA_VERSION when nothing was to do) */
migrate(): number {
run("schemaV1");
const version = storage.kv.get<number>("schema") ?? 1;
if (version < 2) {
// V1 sent our 1-based page number as diigo's 0-based page_num,
// so a stored "page n" is really page n+1
storage.transactionSync(() => {
run("renumberV2");
storage.kv.put("schema", SCHEMA_VERSION);
});
}
return version;
},
/** store a fetched page: upsert its items, record their order */
etch(pageNum: number, count: number, total: number, rows: ItemRow[], at: string): void {
storage.transactionSync(() => {
run("clearPageMembers", pageNum);
rows.forEach((r, i) => {
run("upsertItem", r.itemId, r.url, r.title, r.private ? 1 : 0, r.json, r.updated);
run("insertPageMember", pageNum, i + 1, r.itemId);
});
run("upsertPage", pageNum, count, total, at);
});
},
/** drop pages numbered `pageNum` or lower (their items stay) */
dropPagesThrough(pageNum: number): void {
storage.transactionSync(() => {
run("dropPageMembersThrough", pageNum);
run("dropPagesThrough", pageNum);
});
},
});
}
export type Writer = ReturnType<typeof makeWriter>;
+192
View File
@@ -0,0 +1,192 @@
/** @file webkeys: URL-borne bearer keys, YURL32-encoded; see {@link toWebkey}. */
/** the YURL32 alphabet: `a–z` then `2–7` (32 glyphs, 5 bits each) */
const YURL32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567" as const;
/** encode bytes as YURL32 (`a–z2–7`, 5 bits/char; no padding, the tail
* byte's leftover bits shift-left, as `org.waterken.uri.Base32.encode`
* does) */
export function yurl32(bytes: Uint8Array): string {
let out = "";
let buffer = 0;
let bits = 0;
for (const byte of bytes) {
buffer = (buffer << 8) | byte;
bits += 8;
while (bits >= 5) {
out += YURL32_ALPHABET[(buffer >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) {
out += YURL32_ALPHABET[(buffer << (5 - bits)) & 31];
}
return out;
}
/** decode YURL32 back to bytes (inverse of {@link yurl32}); throws on
* any character outside the alphabet — a webkey is either a webkey or
* it is not */
export function unyurl32(text: string): Uint8Array {
let buffer = 0;
let bits = 0;
const out: number[] = [];
for (const ch of text) {
const v = YURL32_ALPHABET.indexOf(ch);
if (v < 0) throw new Error(`not a webkey: ${JSON.stringify(ch)} is not YURL32`);
buffer = (buffer << 5) | v;
bits += 5;
if (bits >= 8) {
out.push((buffer >>> (bits - 8)) & 0xff);
bits -= 8;
}
}
// leftover bits (<8) are the encoder's zero-padding: validate, don't
// carry them
if (bits > 0 && (buffer & ((1 << bits) - 1)) !== 0) {
throw new Error("not a webkey: non-zero tail bits");
}
return new Uint8Array(out);
}
/** parse a hexadecimal string to raw bytes */
export function hexToBytes(hex: string): Uint8Array {
const trimmed = hex.trim();
if (trimmed.length % 2 !== 0) throw new Error("invalid hex length");
const bytes = new Uint8Array(trimmed.length / 2);
for (let i = 0; i < bytes.length; i += 1) {
const val = Number.parseInt(trimmed.slice(i * 2, i * 2 + 2), 16);
if (Number.isNaN(val)) throw new Error(`invalid hex byte at offset ${i * 2}`);
bytes[i] = val;
}
return bytes;
}
/** encode raw bytes to a lowercase hexadecimal string */
export function bytesToHex(bytes: Uint8Array): string {
let hex = "";
for (const b of bytes) {
hex += b.toString(16).padStart(2, "0");
}
return hex;
}
export const BITS_PER_GLYPH = 5;
/** chars needed for n bits in YURL32 */
export function glyphsFor(bits: number): number {
return Math.ceil(bits / BITS_PER_GLYPH);
}
/** YURL32 glyphs → bytes recoverable via {@link unyurl32} */
export function bytesInGlyphs(glyphs: number): number {
return Math.floor((glyphs * BITS_PER_GLYPH) / 8);
}
/**
* Structural type for a Cloudflare Worker unique ID (such as `DurableObjectId`),
* matching `id.toString()` which returns the 64-hex string.
*/
export interface DurableObjectIdLike {
toString(): string;
equals?(other: unknown): boolean;
readonly name?: string;
}
/** A Worker unique ID input: a `DurableObjectId`, 64-char hex string, or raw bytes. */
export type WorkerUniqueId = DurableObjectIdLike | Uint8Array;
/**
* Convert a Worker unique ID (or raw bytes) to a YURL32 webkey string.
*
* A webkey separates secret from address. The secret bits are supplied by
* the caller (a `DurableObjectId` from `ns.newUniqueId()`, or raw bytes):
* these functions are pure, with no ambient RNG; the caller holds the
* minting authority. The encoding is YURL32: lowercase `a–z` + `2–7`,
* 5 bits per glyph, URL-safe by construction. A 256-bit `DurableObjectId`
* (64 hex characters) becomes 52 glyphs; {@link idFromWebkey} decodes it
* back for `ns.idFromString()`.
*
* Provenance: Tyler Close's web-key (IEEE W2SP 2008) and the Waterken code
* in `kpreid/e-on-java` (YURL32 = `org.waterken.uri.Base32`); the design
* abstract is docs/webkeys.md.
*
* @see https://waterken.sourceforge.net/web-key/
*
* @param id A `DurableObjectId` (from `ns.newUniqueId()`), a 64-char hex ID,
* or raw bytes (`Uint8Array`).
* @returns A YURL32 webkey string (52 glyphs for 256-bit `DurableObjectId`,
* 26 glyphs for 128-bit raw bytes).
*/
export function toWebkey(id: WorkerUniqueId | string): string {
if (id instanceof Uint8Array) {
return yurl32(id);
}
const str = typeof id === "string" ? id.trim() : id.toString();
if (/^[0-9a-fA-F]{64}$/.test(str)) {
return yurl32(hexToBytes(str));
}
if (isWebkey(str)) {
return str;
}
throw new Error("cannot convert ID to webkey: unrecognized format");
}
/**
* Convert a YURL32 webkey string back to the 64-character hex ID string
* expected by `DurableObjectNamespace.idFromString(hex)`.
*
* If the input is already a 64-character hex ID, it is validated and returned
* in lowercase for backwards compatibility.
*/
export function idFromWebkey(webkey: string): string {
const trimmed = webkey.trim();
if (/^[0-9a-fA-F]{64}$/.test(trimmed)) {
return trimmed.toLowerCase();
}
const bytes = unyurl32(trimmed);
if (bytes.length !== 32) {
throw new Error(
`expected 32 bytes (256 bits) for Worker unique ID, got ${bytes.length}`,
);
}
return bytesToHex(bytes);
}
/**
* Is `text` a well-formed webkey of the expected size?
*
* When `bits` is omitted, accepts standard 256-bit Worker unique ID webkeys
* (52 glyphs), 128-bit webkeys (26 glyphs), or 64-bit webkeys (13 glyphs).
*/
export function isWebkey(text: string, bits?: number): boolean {
if (bits !== undefined) {
if (text.length !== glyphsFor(bits)) return false;
try {
return unyurl32(text).length === Math.floor(bits / 8);
} catch {
return false;
}
}
if (text.length === 52 || text.length === 26 || text.length === 13) {
try {
const b = unyurl32(text);
return b.length === 32 || b.length === 16 || b.length === 8;
} catch {
return false;
}
}
return false;
}
/**
* The identity-without-authority twin (the swissHash discipline):
* SHA-256 hash of the webkey, YURL32-encoded (52 glyphs).
*
* Safe for logs/metrics/joins; never accepted as a credential.
*/
export async function shashKey(key: string | WorkerUniqueId): Promise<string> {
const text = typeof key === "string" ? key : toWebkey(key);
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
return yurl32(new Uint8Array(digest));
}
+450
View File
@@ -0,0 +1,450 @@
import { env } from "cloudflare:workers";
import { evictDurableObject, runInDurableObject } from "cloudflare:test";
import { describe, expect, it, vi } from "vitest";
import worker from "../src/index.js";
import { idFromWebkey, toWebkey } from "../src/webkeys.js";
import { PAGE_SIZE } from "../src/cache.js";
import { mf2 } from "microformats-parser";
// matches tests/fake-webapp.js: 30 items, every third private
const WEBAPP_ID = "fake-webapp-id";
type TestEnv = {
CACHE_DO: DurableObjectNamespace<import("../src/index.js").DiigoCache>;
PUBLIC_DO: DurableObjectNamespace<import("../src/index.js").PublicCache>;
CLOCKED_DO: DurableObjectNamespace<import("./test-worker.js").FixedClockCache>;
WEBAPP: { calls(): Promise<number> };
};
const testEnv = env as unknown as TestEnv;
const parse = (items: string[]) => items.map((j) => JSON.parse(j) as Record<string, unknown>);
describe("PublicCache", () => {
it("on a miss asks the webapp and keeps only shared items; a hit makes no call", async () => {
const stub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.newUniqueId());
await stub.setup({ webappId: WEBAPP_ID });
const before = await testEnv.WEBAPP.calls();
const miss = await stub.page(1, 24);
expect(miss.cached).toBe(false);
expect(miss.total).toBe(250);
// diigo page 1 = items 1..24, of which 8 are private
expect(parse(miss.items).map((i) => i.private)).toEqual(Array(16).fill(false));
const afterMiss = await testEnv.WEBAPP.calls();
expect(afterMiss).toBeGreaterThan(before);
const hit = await stub.page(1, 24);
expect(hit.cached).toBe(true);
expect(hit.items).toEqual(miss.items);
expect(await testEnv.WEBAPP.calls()).toBe(afterMiss);
});
it("logs each page read as a hit or a miss (fetched vs kept), without the cache id", async () => {
const spy = vi.spyOn(console, "log");
try {
const id = testEnv.PUBLIC_DO.newUniqueId();
const stub = testEnv.PUBLIC_DO.get(id);
await stub.setup({ webappId: WEBAPP_ID });
await stub.page(1, 24);
await stub.page(1, 24);
const cacheLogs = spy.mock.calls.map((c) => c[0]).filter((e) => e?.event === "cache");
expect(cacheLogs).toEqual([
{ event: "cache", kind: "public", page: 1, outcome: "miss", fetched: 24, kept: 16 },
{ event: "cache", kind: "public", page: 1, outcome: "hit", items: 16 },
]);
expect(JSON.stringify(spy.mock.calls)).not.toContain(id.toString());
} finally {
spy.mockRestore();
}
});
it("stores no private rows at all", async () => {
const stub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.newUniqueId());
await stub.setup({ webappId: WEBAPP_ID });
await stub.page(1, 24);
await stub.page(2, 24);
await runInDurableObject(stub, (_obj, state) => {
const rows = state.storage.sql.exec<{ n: number }>("select count(*) as n from items where private = 1").toArray();
expect(rows[0].n).toBe(0);
});
});
});
describe("page size", () => {
it("refuses, loudly, a short page that isn't the last (diigo capping the size would skip items)", async () => {
const spy = vi.spyOn(console, "error");
try {
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
await stub.setup({ webappId: "fake-capped-webapp" });
// settle the RPC promise ourselves: expect().rejects on a DO stub's
// promise leaves the rejection unhandled
const failure = () => stub.page(1, PAGE_SIZE).then(() => null, (e: unknown) => String(e));
expect(await failure()).toMatch(/returned 64 items for page 1 of 3 \(asked for 100\), then 64 for page 2/);
expect(spy.mock.calls.map((c) => c[0]).filter((e) => e?.outcome === "short-page")).toHaveLength(1);
// nothing was stored: asking again refuses again
expect(await failure()).toMatch(/page size not honored/);
} finally {
spy.mockRestore();
}
});
it("a short page whose next page is empty is the real end: an overstated total is noted, not refused", async () => {
const spy = vi.spyOn(console, "log");
try {
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
await stub.setup({ webappId: "fake-overstated-webapp" });
// 250 items claimed as 310: page 3 holds the last 50, "of 4"
const page = await stub.page(3, PAGE_SIZE);
expect(page.items).toHaveLength(50);
const notes = spy.mock.calls.map((c) => c[0]).filter((e) => e?.outcome === "total-overstated");
expect(notes).toEqual([expect.objectContaining({ page: 3, total: 310, actual: 250 })]);
} finally {
spy.mockRestore();
}
});
it("the last page may be short", async () => {
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
await stub.setup({ webappId: WEBAPP_ID });
expect((await stub.page(3, PAGE_SIZE)).items).toHaveLength(250 - 2 * PAGE_SIZE);
});
});
describe("pacing", () => {
it("paces diigo calls only: a cache hit doesn't wait", async () => {
const stub = testEnv.CLOCKED_DO.get(testEnv.CLOCKED_DO.newUniqueId());
await stub.setup({ webappId: WEBAPP_ID });
await stub.page(1, PAGE_SIZE);
const afterMiss = (await stub.sleeps()).length;
expect(afterMiss).toBeGreaterThan(0);
for (let i = 0; i < 3; i += 1) expect((await stub.page(1, PAGE_SIZE)).cached).toBe(true);
expect(await stub.sleeps()).toHaveLength(afterMiss);
});
});
describe("page numbering (schema v2)", () => {
it("asks diigo for page_num n-1: page 1 is the newest page", async () => {
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
await stub.setup({ webappId: WEBAPP_ID });
const first = (await stub.page(1, PAGE_SIZE)).items.map((j) => (JSON.parse(j) as { title: string }).title);
expect(first[0]).toBe("bookmark 1");
});
it("migrates v1 storage: a stored 'page n' was really page n+1, so it is renumbered, not refetched", async () => {
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
await stub.setup({ webappId: WEBAPP_ID });
// the shape v1 left: a page 1 holding what diigo's page_num=1
// returned (really page 2), and no schema marker; then a fresh
// activation, whose constructor migrates
await runInDurableObject(stub, (_obj, state) => {
const sql = state.storage.sql;
sql.exec("insert into items values ('a', 'https://a.example/', 'old page one, first', 0, '{\"title\":\"A\"}', '1')");
sql.exec("insert into items values ('b', 'https://b.example/', 'old page one, second', 0, '{\"title\":\"B\"}', '1')");
sql.exec("insert into pages values (1, 100, 250, '2026-10-07T00:00:00.000Z')");
sql.exec("insert into page_members values (1, 1, 'a'), (1, 2, 'b')");
state.storage.kv.delete("schema");
});
await evictDurableObject(stub);
const before = await testEnv.WEBAPP.calls();
const two = await stub.page(2, PAGE_SIZE);
expect(two.cached).toBe(true);
expect(two.items.map((j) => (JSON.parse(j) as { title: string }).title)).toEqual(["A", "B"]);
expect(await testEnv.WEBAPP.calls()).toBe(before);
// page 1 was never fetched under v1: now it is a miss
expect((await stub.page(1, PAGE_SIZE)).cached).toBe(false);
await runInDurableObject(stub, (_obj, state) => {
expect(state.storage.kv.get("schema")).toBe(2);
});
});
});
describe("invalidateRecent", () => {
it("drops the pages holding anything updated in the last N days, and only those", async () => {
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
// deep_dee: one bookmark a day, newest first; page 1 = days 0–99,
// page 2 = days 100–199, page 3 = days 200–299
await stub.setup({ webappId: "fake-deep-webapp" });
for (const n of [1, 2, 3]) await stub.page(n, PAGE_SIZE);
expect(await stub.invalidateRecent(150)).toEqual({ pages: 2 });
expect((await stub.page(3, PAGE_SIZE)).cached).toBe(true);
expect((await stub.page(2, PAGE_SIZE)).cached).toBe(false);
expect((await stub.page(1, PAGE_SIZE)).cached).toBe(false);
});
it("drops nothing when nothing cached is that recent, and refuses a bad day count", async () => {
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
await stub.setup({ webappId: WEBAPP_ID }); // the plain account's dates are in 2023
await stub.page(1, PAGE_SIZE);
expect(await stub.invalidateRecent(7)).toEqual({ pages: 0 });
expect((await stub.page(1, PAGE_SIZE)).cached).toBe(true);
const refused = await stub.invalidateRecent(0).then(() => "", (e: unknown) => String(e));
expect(refused).toMatch(/days/);
});
});
describe("eviction", () => {
it("a cache miss leaves no undisposed RPC stubs to block eviction", async () => {
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
await stub.setup({ webappId: WEBAPP_ID });
await stub.page(1, 24);
await evictDurableObject(stub);
expect((await stub.page(1, 24)).cached).toBe(true);
}, 3000);
});
describe("DiigoCache", () => {
it("keeps every item of a page, each under its own link_id", async () => {
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
await stub.setup({ webappId: WEBAPP_ID });
const page = await stub.page(1, 24);
const ids = parse(page.items).map((i) => i.link_id);
expect(ids).toHaveLength(24);
expect(new Set(ids).size).toBe(24);
expect(parse(page.items).filter((i) => i.private)).toHaveLength(8);
});
});
describe("page replay order", () => {
it("a hit replays diigo's fetch-time order (page_members), not a column sort", async () => {
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
await stub.setup({ webappId: WEBAPP_ID });
const titles = (items: string[]) => parse(items).map((i) => i.title);
const expected = Array.from({ length: 24 }, (_, k) => `bookmark ${k + 1}`);
const miss = await stub.page(1, 24);
expect(titles(miss.items)).toEqual(expected);
// page 2's etch upserts other rows; page 1's replay must not shift
await stub.page(2, 24);
const hit = await stub.page(1, 24);
expect(hit.cached).toBe(true);
expect(titles(hit.items)).toEqual(expected);
});
});
describe("worker routes", () => {
const call = (path: string, init?: RequestInit) =>
worker.fetch(new Request(`https://diigo-cache.test${path}`, init), env as never);
it("the public page only reads: an unfetched page says so; the owner's fill makes it appear", async () => {
const wired = await call("/_wire", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ webappId: WEBAPP_ID, mode: "public" }),
});
expect(wired.status).toBe(200);
const { username, publicId } = (await wired.json()) as { username: string; publicId: string };
expect(username).toBe("alice_99");
// page 2 was never fetched: the public page can't fetch it
const before = await testEnv.WEBAPP.calls();
const unfetched = await (await call(`/public/${username}?page=2`)).text();
expect(unfetched).toContain('<form method="get"');
expect(unfetched).toContain("<strong>not fetched yet</strong>");
expect(await testEnv.WEBAPP.calls()).toBe(before);
// the owner's side stores it (here, directly on the public cache)
const pub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.idFromString(idFromWebkey(publicId)));
await pub.page(2, PAGE_SIZE);
const html = await (await call(`/public/${username}?page=2`)).text();
expect(html).toMatch(/<strong>stored \d{4}-\d\d-\d\dT[\d:.]+Z<\/strong>/);
// PAGE_SIZE 100: page 2 is bookmarks 101..200
expect(html).toContain(">bookmark 130<");
// the date comes first, in toISOString() form
expect(html).toMatch(/<li class="h-entry"><time class="dt-updated" datetime="\d{4}-\d\d-\d\dT[\d:.]+Z">[^<]+<\/time> <a /);
expect(html).not.toContain(">bookmark 129<"); // private (129 % 3 === 0)
const json = (await (
await call(`/public/${username}?page=2`, { headers: { accept: "application/json" } })
).json()) as { pages: number; stored: boolean; items: unknown[] };
expect(json.pages).toBe(3);
expect(json.stored).toBe(true);
expect(json.items).toHaveLength(67); // 101..200 minus its 33 multiples of 3
});
it("publishes a private cache later, without the cache id in the URL", async () => {
const cacheId = toWebkey(testEnv.CACHE_DO.newUniqueId());
const res = await call("/_publish", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ cacheId }),
});
// never wired: refused, not crashed
expect(res.status).toBe(404);
});
});
/** `yyyy-Www` for the ISO 8601 week holding `d` (UTC) */
function isoWeek(d: Date): string {
const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
const day = t.getUTCDay() || 7;
t.setUTCDate(t.getUTCDate() + 4 - day); // the week's Thursday names its year
const year = t.getUTCFullYear();
const week = Math.ceil(((t.getTime() - Date.UTC(year, 0, 1)) / 86400000 + 1) / 7);
return `${year}-W${String(week).padStart(2, "0")}`;
}
describe("public page filters (goal 1d)", () => {
// the fake's dated account: "dated n" updated n-1 days + 1h ago;
// #weekly on every 7th; every 10th private; every 5th created 100
// days before it was updated. The public page only reads, so each
// test stores the pages it needs on the owner's side first.
const call = (path: string, init?: RequestInit) =>
worker.fetch(new Request(`https://diigo-cache.test${path}`, init), env as never);
/** wire a public cache to `webappId` and store diigo pages 1..`pages` */
const wireStored = async (webappId: string, pages: number) => {
const res = await call("/_wire", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ webappId, mode: "public" }),
});
expect(res.status).toBe(200);
const { username, publicId } = (await res.json()) as { username: string; publicId: string };
const pub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.idFromString(idFromWebkey(publicId)));
for (let n = 1; n <= pages; n += 1) await pub.page(n, PAGE_SIZE);
return { page: `/public/${username}`, pub };
};
const wireDated = async () => (await wireStored("fake-dated-webapp", 1)).page;
const titlesIn = (html: string) => [...html.matchAll(/>(dated \d+)<\/a>/g)].map((m) => m[1]);
const dated = (...ns: number[]) => ns.map((n) => `dated ${n}`);
it("?days=7 lists the last week", async () => {
const page = await wireDated();
const html = await (await call(`${page}?days=7`)).text();
expect(titlesIn(html)).toEqual(dated(1, 2, 3, 4, 5, 6, 7));
});
it("?by=created windows, lists, and dates by when it was bookmarked", async () => {
const page = await wireDated();
const html = await (await call(`${page}?days=7&by=created`)).text();
// 5 was updated this week but bookmarked 100 days earlier
expect(titlesIn(html)).toEqual(dated(1, 2, 3, 4, 6, 7));
const updated = await (await call(`${page}?days=7`)).text();
expect(titlesIn(updated)).toContain("dated 5");
});
it("?by=created over a longer window sorts by created, newest first", async () => {
const page = await wireDated();
const html = await (await call(`${page}?days=150&by=created&q=${encodeURIComponent("#weekly")}`)).text();
// weekly: 7,14,21,28,35,42,49,56; 35 was created ~134 days ago
// (100 days before its update), so it sorts after 56 (~55 days)
expect(titlesIn(html)).toEqual(dated(7, 14, 21, 28, 42, 49, 56, 35));
});
it("?days=300 pages the matches PAGE_SIZE at a time; links keep the filter", async () => {
const { page } = await wireStored("fake-deep-webapp", 3);
// deep_dee: one a day; days=300 holds 1..300, minus every 10th (private)
const want = Array.from({ length: 300 }, (_, k) => k + 1).filter((n) => n % 10 !== 0);
const first = await (await call(`${page}?days=300`)).text();
expect(titlesIn(first)).toEqual(dated(...want.slice(0, PAGE_SIZE)));
expect(first).toContain(`href="${page}?days=300&amp;page=2"`);
const second = await (await call(`${page}?days=300&page=2`)).text();
expect(titlesIn(second)).toEqual(dated(...want.slice(PAGE_SIZE, 2 * PAGE_SIZE)));
const third = await (await call(`${page}?days=300&page=3`)).text();
expect(titlesIn(third)).toEqual(dated(...want.slice(2 * PAGE_SIZE)));
});
it("?after=&before= selects a date range", async () => {
const page = await wireDated();
const day = (n: number) => new Date(Date.now() - (n - 1) * 24 * 60 * 60 * 1000 - 60 * 60 * 1000).toISOString().slice(0, 10);
// items are 24h apart, so each has its own UTC day: from dated 12's
// day (inclusive) up to dated 9's day (exclusive); 10 is private
const html = await (await call(`${page}?after=${day(12)}&before=${day(9)}`)).text();
expect(titlesIn(html)).toEqual(dated(11, 12));
});
it("?in= names an ISO week", async () => {
const { page } = await wireStored("fake-deep-webapp", 3);
const week = isoWeek(new Date(Date.now() - 100 * 24 * 60 * 60 * 1000));
const html = await (await call(`${page}?in=${week}`)).text();
// one a day; every 10th is private
expect(titlesIn(html).length).toBeGreaterThanOrEqual(6);
expect(titlesIn(html).length).toBeLessThanOrEqual(7);
});
it("?q=#weekly&days=60 filters by tag; private items stay out", async () => {
const page = await wireDated();
const html = await (await call(`${page}?days=60&q=${encodeURIComponent("#weekly")}`)).text();
expect(titlesIn(html)).toEqual(dated(7, 14, 21, 28, 35, 42, 49, 56));
});
it("?q= alone searches all time", async () => {
const page = await wireDated();
const html = await (await call(`${page}?q=fragments`)).text();
expect(titlesIn(html)).toEqual(dated(7, 14, 21, 28, 35, 42, 49, 56));
});
it("a filter reads only stored items, never diigo; results say whether storage is complete", async () => {
const { page, pub } = await wireStored("fake-deep-webapp", 1);
const json = async () =>
(await call(`${page}?days=300`, { headers: { accept: "application/json" } })).json() as Promise<{
matched: number;
complete: boolean;
}>;
const before = await testEnv.WEBAPP.calls();
// page 1 holds 1..100, minus 10 private
expect(await json()).toMatchObject({ matched: 90, complete: false });
expect(await (await call(`${page}?days=300`)).text()).toMatch(/some matches may be missing/);
expect(await testEnv.WEBAPP.calls()).toBe(before);
await pub.page(2, PAGE_SIZE);
await pub.page(3, PAGE_SIZE);
expect(await json()).toMatchObject({ matched: 270, complete: true });
});
it("the page is an h-feed of h-entry bookmarks: microformats are its API for other sites", async () => {
const page = await wireDated();
const html = await (await call(`${page}?days=7&by=created`)).text();
const base = `https://diigo-cache.test${page}`;
const { items, rels } = mf2(html, { baseUrl: base });
const feed = items.find((i) => i.type?.includes("h-feed"));
const entries = feed?.children ?? [];
expect(entries.map((e) => e.properties.name?.[0])).toEqual(dated(1, 2, 3, 4, 6, 7));
const seven = entries[5].properties;
expect(seven["bookmark-of"]).toEqual(["https://dated.example/7"]);
expect(seven.summary).toEqual(["a week of fragments"]);
expect(seven.category).toEqual(["ocap", "weekly"]);
const published = new Date(String(seven.published?.[0])).getTime();
const updated = new Date(String(seven.updated?.[0])).getTime();
// 7 isn't a 5: created when updated, 6 days + 1h ago
expect(published).toBe(updated);
expect(Date.now() - published).toBeGreaterThan(6 * 24 * 60 * 60 * 1000);
// one page of matches: no rel=next
expect(rels.next).toBeUndefined();
});
it("filtered pages link the next page with rel=next, keeping the filter", async () => {
const { page } = await wireStored("fake-deep-webapp", 3);
const html = await (await call(`${page}?days=300`)).text();
const { rels } = mf2(html, { baseUrl: `https://diigo-cache.test${page}?days=300` });
expect(rels.next).toEqual([`https://diigo-cache.test${page}?days=300&page=2`]);
});
it("JSON answers carry the canonical filter, so devs see what was understood", async () => {
const page = await wireDated();
const res = await call(`${page}?days=7&q=${encodeURIComponent("#Weekly")}`, { headers: { accept: "application/json" } });
expect(await res.json()).toMatchObject({
filter: { by: "updated", tags: [{ text: "weekly", negated: false }] },
complete: true,
});
});
it("a malformed filter is a 400 with a message, not an empty list", async () => {
const page = await wireDated();
const res = await call(`${page}?days=7x`);
expect(res.status).toBe(400);
expect(await res.text()).toMatch(/days/);
});
it("the form offers the day presets, date inputs, and search, echoing the current filter", async () => {
const page = await wireDated();
const html = await (await call(`${page}?days=30&q=ocap`)).text();
expect(html).toMatch(/<select name="days">/);
expect(html).toMatch(/<select name="by">/);
for (const n of [7, 30, 90, 365]) expect(html).toContain(`<option value="${n}"`);
expect(html).toContain('<option value="30" selected>');
expect(html).toMatch(/<input type="date" name="after"/);
expect(html).toMatch(/<input type="date" name="before"/);
expect(html).toMatch(/<input[^>]* name="q"[^>]* value="ocap"/);
// times are UTC, and the page says so
expect(html).toMatch(/UTC/);
});
});
+130
View File
@@ -0,0 +1,130 @@
/** @file a stand-in for webapp's `WebAppFactory`, serving diigo-shaped pages to tests. */
import { RpcTarget, WorkerEntrypoint } from "cloudflare:workers";
const KNOWN_WEBAPP = "fake-webapp-id";
const TOTAL = 250;
/** the plain account, capped below PAGE_SIZE (as diigo caps at 100) */
const CAPPED_WEBAPP = "fake-capped-webapp";
const CAP = 64;
/** the plain account, but its `total` claims 60 more items than it has
* (hypothetical: what looked like this on 2026-10-07 was the 0-based
* page_num, but the guard stays) */
const OVERSTATED_WEBAPP = "fake-overstated-webapp";
const OVERSTATEMENT = 60;
/** a second account, for date filters (goal 1d): 60 bookmarks, item n
* updated n-1 days + 1 hour before the call, in diigo's updated-desc
* order; tagged ocap, plus weekly every 7th; every 10th private; every
* 5th an old bookmark edited recently (created 100 days before updated) */
const DATED_WEBAPP = "fake-dated-webapp";
const DATED_TOTAL = 60;
/** the same shape, 300 deep (3 pages of 100): for paging matches */
const DEEP_WEBAPP = "fake-deep-webapp";
const DEEP_TOTAL = 300;
const HOUR = 60 * 60 * 1000;
function datedItem(n, now, user = "dated_dan") {
return {
link_id: 5000 + n,
url: `https://dated.example/${n}`,
title: `dated ${n}`,
description: n % 7 === 0 ? "a week of fragments" : "",
private: n % 10 === 0,
u_name: user,
user_id: 777,
tags: n % 7 === 0 ? "ocap,weekly" : "ocap",
created_at: Math.floor((now - (n - 1) * 24 * HOUR - HOUR - (n % 5 === 0 ? 100 * 24 * HOUR : 0)) / 1000),
updated_at: Math.floor((now - (n - 1) * 24 * HOUR - HOUR) / 1000),
};
}
/** item n (1-based, in diigo's order): diigo's field names, made-up
* values. link_id and updated_at are scrambled (distinct; 7 and 11 are
* coprime to 307, a prime above TOTAL), so neither column sorts back
* into diigo's order — a
* cache that replays by column rather than by fetch order is caught. */
function item(n) {
return {
link_id: 1000 + ((n * 7) % 307),
url: `https://example.com/${n}`,
title: `bookmark ${n}`,
description: "",
private: n % 3 === 0,
u_name: "alice_99",
first_by: "someone-else",
user_id: 4242,
tags: "",
created_at: 1700000000,
updated_at: 1700001000 + ((n * 11) % 307),
};
}
let calls = 0;
class FakeGet extends RpcTarget {
#path;
#params;
/** null (the plain account), "capped", "overstated", "dated", or "deep" */
#dated;
constructor(path, params, dated) {
super();
this.#path = path;
this.#params = params;
this.#dated = dated;
}
pathjoin(ref) {
return new FakeGet(ref, this.#params, this.#dated);
}
query(params) {
return new FakeGet(this.#path, { ...this.#params, ...params }, this.#dated);
}
async get() {
calls += 1;
if (this.#path !== "load_user_items") throw new Error(`fake webapp: no route ${this.#path}`);
const count = Math.min(Number(this.#params.count), this.#dated === "capped" ? CAP : Infinity);
const page = Number(this.#params.page_num);
const dated = this.#dated === "dated" || this.#dated === "deep";
const total = this.#dated === "deep" ? DEEP_TOTAL : dated ? DATED_TOTAL : TOTAL;
const now = Date.now();
const items = [];
// diigo's page_num counts from 0 (observed 2026-10-07: page_num=1
// skipped the newest page)
for (let n = page * count + 1; n <= Math.min((page + 1) * count, total); n += 1) {
items.push(dated ? datedItem(n, now, this.#dated === "deep" ? "deep_dee" : "dated_dan") : item(n));
}
// past the end, diigo answers no items and a total of 0 (observed
// 2026-10-07: the page after the last reported total ≤ 100)
if (items.length === 0) return JSON.stringify({ total: 0, items });
return JSON.stringify({ total: this.#dated === "overstated" ? total + OVERSTATEMENT : total, items });
}
}
/**
* webapp's `WebAppFactory` entrypoint, faked: an auxiliary worker (plain
* JS; the vitest pool doesn't transform aux workers) serving
* `load_user_items` pages for a few known webapp ids. Counts its diigo
* calls, so tests can tell a cache hit (no call) from a miss.
*/
export class WebAppFactory extends WorkerEntrypoint {
async at(id) {
const kind = {
[KNOWN_WEBAPP]: null,
[CAPPED_WEBAPP]: "capped",
[OVERSTATED_WEBAPP]: "overstated",
[DATED_WEBAPP]: "dated",
[DEEP_WEBAPP]: "deep",
}[id];
if (kind === undefined) throw new Error("fake webapp: unknown id");
return new FakeGet("", {}, kind);
}
/** how many diigo calls so far (test hook) */
async calls() {
return calls;
}
}
export default {
fetch() {
return new Response("fake webapp", { status: 404 });
},
};
+416
View File
@@ -0,0 +1,416 @@
import { env } from "cloudflare:workers";
import { evictDurableObject, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test";
import { describe, expect, it, vi } from "vitest";
import worker from "../src/index.js";
import { newHttpBatchRpcSession } from "capnweb";
import type { CacheApi } from "../src/api.js";
import { idFromWebkey, toWebkey } from "../src/webkeys.js";
import { FIXED_NOW } from "./test-worker.js";
import { PAGE_SIZE } from "../src/cache.js";
// goal 1e (capsite checklist): a job that grabs every page. Fake
// accounts: tests/fake-webapp.js ("fake-webapp-id": 250 items = 3 pages
// of PAGE_SIZE 100, every 3rd private).
type TestEnv = {
CACHE_DO: DurableObjectNamespace<import("../src/index.js").DiigoCache>;
CLOCKED_DO: DurableObjectNamespace<import("./test-worker.js").FixedClockCache>;
PUBLIC_DO: DurableObjectNamespace<import("../src/index.js").PublicCache>;
WEBAPP: { calls(): Promise<number> };
};
const testEnv = env as unknown as TestEnv;
const wired = async (webappId = "fake-webapp-id") => {
const stub = testEnv.CACHE_DO.get(testEnv.CACHE_DO.newUniqueId());
await stub.setup({ webappId });
return stub;
};
const HOUR = 60 * 60 * 1000;
/** run alarms until the job ends (bounded, so a runaway job fails); the
* refresh alarm an ended job leaves is not run */
const drain = async (stub: DurableObjectStub & { fillStatus(): Promise<{ state: string } | undefined> }, max = 20) => {
let ran = 0;
const running = async () => (await stub.fillStatus())?.state === "running";
while (ran < max && (await running()) && (await runDurableObjectAlarm(stub))) ran += 1;
expect(ran).toBeLessThan(max);
return ran;
};
describe("fill job (goal 1e)", () => {
it("fills every page; afterwards every page is a hit with no webapp call", async () => {
const stub = await wired();
const atStart = await testEnv.WEBAPP.calls();
expect((await stub.startFill()).state).toBe("running");
await drain(stub);
const status = await stub.fillStatus();
expect(status).toMatchObject({ state: "done", pages: 3, fetched: 3 });
// one diigo call per page fetched (no extra page-1 fetch per miss)
expect((await testEnv.WEBAPP.calls()) - atStart).toBe(3);
const before = await testEnv.WEBAPP.calls();
for (const n of [1, 2, 3]) expect((await stub.page(n, PAGE_SIZE)).cached).toBe(true);
expect(await testEnv.WEBAPP.calls()).toBe(before);
});
it("advances pagesPerStep pages per alarm, with progress readable between steps", async () => {
const stub = await wired();
await stub.startFill({ pagesPerStep: 1 });
expect(await runDurableObjectAlarm(stub)).toBe(true);
expect(await stub.fillStatus()).toMatchObject({ state: "running", nextPage: 2, pages: 3 });
await drain(stub);
expect((await stub.fillStatus())?.state).toBe("done");
});
it("survives eviction: progress is in storage, not memory", async () => {
const stub = await wired();
await stub.startFill({ pagesPerStep: 1 });
await runDurableObjectAlarm(stub);
await evictDurableObject(stub);
expect(await stub.fillStatus()).toMatchObject({ state: "running", nextPage: 2 });
await drain(stub);
expect((await stub.fillStatus())?.state).toBe("done");
});
it("starting again while running rejoins the same job", async () => {
const stub = await wired();
const first = await stub.startFill({ pagesPerStep: 1 });
await runDurableObjectAlarm(stub);
const again = await stub.startFill({ pagesPerStep: 1 });
expect(again.startedAt).toBe(first.startedAt);
expect(again.nextPage).toBe(2);
});
it("skips pages already cached", async () => {
const stub = await wired();
await stub.page(1, PAGE_SIZE);
await stub.startFill();
await drain(stub);
expect(await stub.fillStatus()).toMatchObject({ state: "done", fetched: 2 });
});
it("stops when asked; cached pages stay", async () => {
const stub = await wired();
await stub.startFill({ pagesPerStep: 1 });
await runDurableObjectAlarm(stub);
expect((await stub.stopFill()).state).toBe("stopped");
expect(await runDurableObjectAlarm(stub)).toBe(false);
expect((await stub.page(1, PAGE_SIZE)).cached).toBe(true);
});
it("a webapp failure fails the job loudly, once: status says why, the log too", async () => {
const spy = vi.spyOn(console, "error");
try {
const stub = await wired("no-such-webapp");
await stub.startFill();
await drain(stub);
const status = await stub.fillStatus();
expect(status?.state).toBe("failed");
expect(status?.error).toMatch(/unknown id/);
expect(spy.mock.calls.map((c) => c[0]).filter((e) => e?.event === "fill")).not.toHaveLength(0);
} finally {
spy.mockRestore();
}
});
it("reads time only through its clock: a fixed clock pins the timestamps and the alarm", async () => {
const stub = testEnv.CLOCKED_DO.get(testEnv.CLOCKED_DO.newUniqueId());
await stub.setup({ webappId: "fake-webapp-id" });
const at = new Date(FIXED_NOW).toISOString();
expect(await stub.startFill()).toMatchObject({ startedAt: at, updatedAt: at });
await runInDurableObject(stub, async (_obj, state) => {
expect(await state.storage.getAlarm()).toBe(FIXED_NOW + 1000);
});
await drain(stub);
expect(await stub.fillStatus()).toMatchObject({ state: "done", updatedAt: at });
await runInDurableObject(stub, async (_obj, state) => {
expect(await state.storage.getAlarm()).toBe(FIXED_NOW + 3 * HOUR);
});
});
it("a capped page size fails the fill with the reason, instead of skipping items", async () => {
const stub = await wired("fake-capped-webapp");
await stub.startFill();
await drain(stub);
const status = await stub.fillStatus();
expect(status?.state).toBe("failed");
expect(status?.error).toMatch(/page size not honored/);
});
it("fills to the real end if a total overstates the items", async () => {
const stub = await wired("fake-overstated-webapp");
await stub.startFill();
await drain(stub);
// 250 items claimed as 310: the walk reaches page 4 (empty, total 0)
// and ends there; the count is the last page with items, not 4, and
// not the empty page's ceil(0/100) = 1
const status = await stub.fillStatus();
expect(status).toMatchObject({ state: "done", nextPage: 4, pages: 3 });
expect((await stub.page(3, PAGE_SIZE)).items).toHaveLength(50);
});
it("a job saved under the old page numbering fails instead of resuming", async () => {
const stub = await wired();
await runInDurableObject(stub, async (_obj, state) => {
const at = new Date().toISOString();
await state.storage.put("fill", { state: "running", nextPage: 40, pages: 168, fetched: 39, pageSize: 100, startedAt: at, updatedAt: at });
await state.storage.setAlarm(Date.now() + 60_000);
});
await drain(stub);
expect((await stub.fillStatus())?.error).toMatch(/page numbering changed/);
expect(await stub.startFill()).toMatchObject({ state: "running", nextPage: 1, numbering: 2 });
});
it("a job saved under another page size fails instead of resuming; a new start replaces it", async () => {
const stub = await wired();
// the shape a 24-per-page job left in storage (no pageSize field)
await runInDurableObject(stub, async (_obj, state) => {
const at = new Date().toISOString();
await state.storage.put("fill", { state: "running", nextPage: 25, pages: 698, fetched: 23, startedAt: at, updatedAt: at });
await state.storage.setAlarm(Date.now() + 60_000);
});
await drain(stub);
const stale = await stub.fillStatus();
expect(stale?.state).toBe("failed");
expect(stale?.error).toMatch(/page size changed \(from 24 to 100\)/);
expect(await stub.startFill()).toMatchObject({ state: "running", nextPage: 1, pageSize: PAGE_SIZE });
});
it("refreshes 3 hours after a fill: refetches the pages updated in the last 2 days, skips the rest, then waits again", async () => {
// deep account: item n updated n-1 days + 1 hour ago, so items 1–2
// (both on page 1) are within 2 days
const stub = await wired("fake-deep-webapp");
await stub.startFill();
await drain(stub);
await runInDurableObject(stub, async (_obj, state) => {
const alarm = (await state.storage.getAlarm()) ?? 0;
expect(alarm - Date.now()).toBeGreaterThan(2.9 * HOUR);
expect(alarm - Date.now()).toBeLessThanOrEqual(3 * HOUR);
});
expect(await runDurableObjectAlarm(stub)).toBe(true);
expect(await stub.fillStatus()).toMatchObject({ state: "running", nextPage: 1, refetchThrough: 1 });
await drain(stub);
// fetched counts diigo calls; pages 2–3 were hits
expect(await stub.fillStatus()).toMatchObject({ state: "done", pages: 3, fetched: 1 });
await runInDurableObject(stub, async (_obj, state) => {
expect(await state.storage.getAlarm()).not.toBeNull();
});
});
it("a refresh refetches page 1 even when nothing cached is recent: new bookmarks land there", async () => {
const stub = await wired();
await stub.startFill();
await drain(stub);
await runDurableObjectAlarm(stub);
expect(await stub.fillStatus()).toMatchObject({ refetchThrough: 1 });
await drain(stub);
expect(await stub.fillStatus()).toMatchObject({ state: "done", fetched: 1 });
});
it("a failed fill is retried by the next refresh; a stopped one is not", async () => {
const failing = await wired("no-such-webapp");
await failing.startFill();
await drain(failing);
expect((await failing.fillStatus())?.state).toBe("failed");
expect(await runDurableObjectAlarm(failing)).toBe(true);
expect((await failing.fillStatus())?.state).toBe("running");
const stopped = await wired();
await stopped.startFill();
await drain(stopped);
expect((await stopped.stopFill()).state).toBe("stopped");
expect(await runDurableObjectAlarm(stopped)).toBe(false);
});
it("a fill that ended before refreshes existed gets one when the cache next wakes", async () => {
const stub = await wired();
await stub.startFill();
await drain(stub);
await runInDurableObject(stub, async (_obj, state) => {
await state.storage.deleteAlarm();
});
await evictDurableObject(stub);
await stub.fillStatus();
await runInDurableObject(stub, async (_obj, state) => {
expect(await state.storage.getAlarm()).not.toBeNull();
});
});
it("a public cache's fill stores no private rows", async () => {
const stub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.newUniqueId());
await stub.setup({ webappId: "fake-webapp-id" });
await stub.startFill();
await drain(stub);
await runInDurableObject(stub, (_obj, state) => {
const rows = state.storage.sql.exec<{ n: number }>("select count(*) as n from items where private = 1").toArray();
expect(rows[0].n).toBe(0);
});
});
});
describe("fill via webkey and Cap'n Web (goal 1e)", () => {
const ORIGIN = "https://diigo-cache.test";
const call = (path: string, init?: RequestInit) => worker.fetch(new Request(`${ORIGIN}${path}`, init), env as never);
/** a Cap'n Web batch session whose fetch goes to the worker; counts round trips */
const session = () => {
const trips = { n: 0 };
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => {
trips.n += 1;
return worker.fetch(new Request(input as RequestInfo, init), env as never);
});
const api = newHttpBatchRpcSession<CacheApi>(`${ORIGIN}/api`);
return { api, trips, done: () => fetchSpy.mockRestore() };
};
const wireJson = async (mode: "private" | "public") => {
const res = await call("/_wire", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ webappId: "fake-webapp-id", mode }),
});
return (await res.json()) as { cacheId: string; username?: string; publicId?: string };
};
it("trading the key and starting the fill pipeline into one round trip", async () => {
const { cacheId } = await wireJson("private");
const { api, trips, done } = session();
try {
const status = await api.cache(cacheId).startFill();
expect(status).toMatchObject({ state: "running" });
expect(trips.n).toBe(1);
} finally {
done();
}
});
it("the capability is a facet: fill and status, never the DO's wiring", async () => {
const { cacheId } = await wireJson("private");
const { api, done } = session();
try {
const cap = api.cache(cacheId) as unknown as Record<string, () => Promise<unknown>>;
await expect(cap.setup()).rejects.toThrow();
} finally {
done();
}
});
it("unknown and malformed keys get one refusal that never echoes the key", async () => {
const unknown = toWebkey(testEnv.CACHE_DO.newUniqueId());
for (const key of [unknown, "not-a-key", unknown.slice(0, 26)]) {
const { api, done } = session();
try {
const err = await api.cache(key).fillStatus().then(() => null, (e: unknown) => e);
expect(String(err)).toMatch(/no such cache/);
expect(String(err)).not.toContain(key);
} finally {
done();
}
}
});
it("publicCache() reaches the public companion's fill; refused when never published", async () => {
const pub = await wireJson("public");
const s1 = session();
try {
expect(await s1.api.cache(pub.cacheId).hasPublic()).toBe(true);
} finally {
s1.done();
}
const s2 = session();
try {
expect(await s2.api.cache(pub.cacheId).publicCache().startFill()).toMatchObject({ state: "running" });
} finally {
s2.done();
}
const s3 = session();
try {
expect(await s3.api.cache(pub.cacheId).publicCache().stopFill()).toMatchObject({ state: "stopped" });
} finally {
s3.done();
}
const priv = await wireJson("private");
const s4 = session();
try {
expect(await s4.api.cache(priv.cacheId).hasPublic()).toBe(false);
} finally {
s4.done();
}
// a batch session ends after its round trip: a fresh one per await
const s5 = session();
try {
await expect(s5.api.cache(priv.cacheId).publicCache().fillStatus()).rejects.toThrow(/no public cache/);
} finally {
s5.done();
}
});
it("the webkey page is a skeleton: the same for every key, which it reads from the fragment", async () => {
const res = await call("/cache/");
expect(res.status).toBe(200);
const html = await res.text();
expect(html).toContain("location.hash");
expect(html).toContain('from "/_capnweb.js"');
expect(html).toContain('newHttpBatchRpcSession("/api")');
expect(html).toContain('<meta name="referrer" content="no-referrer">');
});
it("without a fragment, the webkey page is a login form a password manager can fill, which posts nothing", async () => {
const html = await (await call("/cache/")).text();
const form = html.match(/<form id="login"[^]*?<\/form>/)?.[0] ?? "";
expect(form).toMatch(/<input[^>]* autocomplete="username"/);
expect(form).toMatch(/<input[^>]* type="password"[^>]* autocomplete="current-password"/);
// no name attributes: a native submit carries no key anywhere
expect(form).not.toMatch(/\bname=/);
expect(form).not.toMatch(/\baction=/);
expect(html).toContain("event.preventDefault()");
});
it("the capability can invalidate recent pages; the page offers it for each cache", async () => {
const { cacheId } = await wireJson("private");
const { api, done } = session();
try {
expect(await api.cache(cacheId).invalidateRecent(7)).toEqual({ pages: 0 });
} finally {
done();
}
const html = await (await call("/cache/")).text();
expect(html).toContain('id="private-days"');
expect(html).toContain('data-action="invalidate"');
expect(html).toContain("invalidateRecent(days)");
});
it("serves capnweb's browser build itself (no third-party script beside the key)", async () => {
const res = await call("/_capnweb.js");
expect(res.headers.get("content-type")).toMatch(/javascript/);
expect(await res.text()).toMatch(/export \{[^}]*newHttpBatchRpcSession/);
});
it("the created page links its webkey (key in the fragment); no cache id rides a form to /_fill", async () => {
const res = await call("/_wire", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ webappId: "fake-webapp-id", mode: "private" }),
});
const html = await res.text();
expect(html).toMatch(/<a href="\/cache\/#[a-z2-7]{52}">/);
expect(html).not.toContain("/_fill");
expect((await call("/_fill", { method: "POST" })).status).toBe(404);
});
it("the public page shows a fill's progress", async () => {
const { cacheId, username, publicId } = (await wireJson("public")) as { cacheId: string; username: string; publicId: string };
const { api, done } = session();
try {
await api.cache(cacheId).publicCache().startFill({ pagesPerStep: 1 });
} finally {
done();
}
// one step of the job: page 1 stored, so the page count is known
const pub = testEnv.PUBLIC_DO.get(testEnv.PUBLIC_DO.idFromString(idFromWebkey(publicId)));
await runDurableObjectAlarm(pub);
const html = await (await call(`/public/${username}`)).text();
expect(html).toMatch(/fill(ed|ing)[^<]*\d+ of \d+ pages/);
});
});
+83
View File
@@ -0,0 +1,83 @@
import { describe, expect, it } from "vitest";
import { publicOnly, toRows, updatedISO, usernameOf } from "../src/items.js";
import type { Item } from "../src/items.js";
/** a load_user_items row: diigo's actual field names (observed
* 2026-10-07), made-up values */
function diigoItem(linkId: number, url: string): Item {
return {
link_id: linkId,
url,
title: `title ${linkId}`,
description: "",
private: false,
u_name: "alice_99",
first_by: "bob-the-first",
user_id: 4242,
real_name: "Alice A.",
tags: "",
created_at: 1700000000,
updated_at: 1700000100 + linkId,
annotations: [],
comments: [],
};
}
function makeLog() {
const entries: { level: string; args: unknown[] }[] = [];
const at = (level: string) => (...args: unknown[]) => entries.push({ level, args });
return { log: { warn: at("warn") }, entries };
}
describe("toRows", () => {
it("keys each item on diigo's link_id, so a page of distinct items stays distinct", () => {
const { log } = makeLog();
const rows = toRows([diigoItem(11, "https://a.example/"), diigoItem(12, "https://b.example/")], log);
expect(rows.map((r) => r.itemId)).toEqual(["11", "12"]);
});
it("logs, rather than silently drops or merges, items it cannot key", () => {
const { log, entries } = makeLog();
const noId = diigoItem(13, "https://c.example/");
delete noId.link_id;
const noUrl = diigoItem(14, "");
const rows = toRows([noId, noUrl, diigoItem(15, "https://d.example/")], log);
expect(rows.map((r) => r.itemId)).toEqual(["15"]);
expect(entries.map((e) => e.level)).toEqual(["warn", "warn"]);
// diagnostics name the fields present, never their values
expect(JSON.stringify(entries)).not.toContain("https://c.example/");
});
});
describe("usernameOf", () => {
it("reads the owner's username from diigo's u_name", () => {
expect(usernameOf(diigoItem(1, "https://a.example/"))).toBe("alice_99");
});
it("answers empty for an item without one", () => {
expect(usernameOf(undefined)).toBe("");
expect(usernameOf({ u_name: "has spaces" })).toBe("");
});
});
describe("publicOnly", () => {
it("keeps shared rows and drops private ones, before anything is stored", () => {
const { log } = makeLog();
const shared = diigoItem(21, "https://shared.example/");
const secret = { ...diigoItem(22, "https://secret.example/"), private: true };
const rows = publicOnly(toRows([shared, secret], log));
expect(rows.map((r) => r.itemId)).toEqual(["21"]);
expect(JSON.stringify(rows)).not.toContain("secret.example");
});
});
describe("updatedISO", () => {
it("reads diigo's updated_at as epoch seconds", () => {
expect(updatedISO({ updated_at: 1700000000 })).toBe("2023-11-14T22:13:20.000Z");
});
it("answers empty when there is no usable date", () => {
expect(updatedISO({})).toBe("");
expect(updatedISO({ updated_at: "yesterday" })).toBe("");
});
});
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import { pmSave } from "../src/pm-save.js";
import type { PmPowers } from "../src/pm-save.js";
/** a fake console that records what was logged, by level */
function makeLog() {
const entries: { level: string; args: unknown[] }[] = [];
const at = (level: string) => (...args: unknown[]) => entries.push({ level, args });
return { log: { info: at("info"), warn: at("warn"), error: at("error") }, entries };
}
class FakeCredential {
constructor(readonly init: { id: string; password: string }) {}
}
function setup(store: (c: unknown) => Promise<unknown>, petname = "my cache") {
const { log, entries } = makeLog();
const stored: unknown[] = [];
const powers: PmPowers = {
petname: { value: petname },
credentials: { store: (c) => (stored.push(c), store(c)) },
PasswordCredential: FakeCredential,
log,
};
const btn = { textContent: "save to password manager", disabled: false };
return { powers, btn, entries, stored };
}
describe("pmSave", () => {
it("stores under the petname, and reports a spec-conformant resolve (undefined) as offered, not failed", async () => {
const { powers, btn, entries, stored } = setup(() => Promise.resolve(undefined));
await pmSave(btn, "the-key", powers);
expect(stored).toEqual([new FakeCredential({ id: "my cache", password: "the-key" })]);
expect(btn.textContent).not.toMatch(/not saved|fail/);
expect(btn.textContent).toMatch(/password manager/);
expect(btn.disabled).toBe(false);
expect(entries.map((e) => e.level)).toEqual(["info"]);
});
it("logs, never silently, when the browser has no credential store", async () => {
const { powers, btn, entries } = setup(() => Promise.resolve(undefined));
delete powers.PasswordCredential;
await pmSave(btn, "the-key", powers);
expect(btn.textContent).toMatch(/no credential store/);
expect(entries.map((e) => e.level)).toEqual(["warn"]);
});
it("logs the error when the store rejects, without the key", async () => {
const { powers, btn, entries } = setup(() => Promise.reject(new Error("NotAllowedError")));
await pmSave(btn, "the-key", powers);
expect(btn.textContent).toMatch(/save failed/);
expect(entries.map((e) => e.level)).toEqual(["error"]);
expect(JSON.stringify(entries)).not.toContain("the-key");
});
it("asks for a petname rather than saving under an empty username", async () => {
const { powers, btn, stored } = setup(() => Promise.resolve(undefined), " ");
await pmSave(btn, "the-key", powers);
expect(stored).toEqual([]);
expect(btn.textContent).toMatch(/petname/);
});
});
+206
View File
@@ -0,0 +1,206 @@
import { describe, expect, it } from "vitest";
import { matches, parseQuery, toQuery } from "../src/query.js";
import type { FilterSpec, Query, QueryError } from "../src/query.js";
// goal 1d (capsite checklist)
const NOW = new Date("2026-10-07T12:00:00.000Z");
const DAY = 24 * 60 * 60 * 1000;
const fromUrl = (qs: string) => parseQuery(new URLSearchParams(qs), NOW);
const ok = (q: Query | QueryError) => {
if ("error" in q) throw new Error(`expected a query: ${q.error}`);
return q;
};
const url = (qs: string) => ok(fromUrl(qs));
const spec = (s: FilterSpec) => ok(toQuery(s, NOW));
const refused = (q: Query | QueryError) => {
expect(q).toHaveProperty("error");
return (q as QueryError).error;
};
const day = (iso: string) => new Date(`${iso}T00:00:00.000Z`);
const range = (q: Query) => [q.after?.toISOString().slice(0, 10), q.before?.toISOString().slice(0, 10)];
describe("filters: one spec, two spellings (goal 1d)", () => {
it("devs write { days: 7 }; URLs write ?days=7; same query", () => {
expect(spec({ days: 7 })).toEqual(url("days=7"));
expect(spec({ days: 7 }).after).toEqual(new Date(NOW.getTime() - 7 * DAY));
});
it("an empty spec or URL filters nothing", () => {
expect(spec({})).toEqual({ by: "updated", words: [], tags: [] });
expect(url("")).toEqual({ by: "updated", words: [], tags: [] });
});
it("empty URL fields mean absent (a GET form submits them all)", () => {
expect(url("days=7&after=&before=&in=&by=&q=")).toEqual(url("days=7"));
});
it("refuses a days value that isn't a whole number from 1 to 3650", () => {
for (const bad of ["0", "-7", "7x", "1.5", "3651"]) expect(refused(fromUrl(`days=${bad}`))).toMatch(/days/);
expect(refused(toQuery({ days: 0 }, NOW))).toMatch(/days/);
});
});
describe("windows: UTC, half-open (goal 1d)", () => {
it("after/before are UTC days: after inclusive from 00:00Z, before exclusive", () => {
expect(range(url("after=2026-01-01&before=2026-02-01"))).toEqual(["2026-01-01", "2026-02-01"]);
expect(url("after=2026/01/01").after).toEqual(day("2026-01-01"));
});
it("in= names a year, month, quarter, or ISO week", () => {
expect(range(url("in=2025"))).toEqual(["2025-01-01", "2026-01-01"]);
expect(range(url("in=2025-03"))).toEqual(["2025-03-01", "2025-04-01"]);
expect(range(url("in=2025-12"))).toEqual(["2025-12-01", "2026-01-01"]);
expect(range(url("in=2025-Q1"))).toEqual(["2025-01-01", "2025-04-01"]);
expect(range(url("in=2025-Q4"))).toEqual(["2025-10-01", "2026-01-01"]);
// ISO 8601: weeks start Monday; week 1 holds the year's first Thursday
expect(range(url("in=2025-W01"))).toEqual(["2024-12-30", "2025-01-06"]);
expect(range(url("in=2026-W53"))).toEqual(["2026-12-28", "2027-01-04"]);
});
it("refuses malformed dates and periods", () => {
expect(refused(fromUrl("after=2026-13-01"))).toMatch(/after/);
expect(refused(fromUrl("before=yesterday"))).toMatch(/before/);
// 2025 has 52 ISO weeks (it starts on a Wednesday, not a leap year)
for (const bad of ["2025-13", "2025-Q5", "2025-W53", "2025-W00", "25", "2025-1"]) {
expect(refused(fromUrl(`in=${bad}`))).toMatch(/in/);
}
});
it("refuses a bound given twice, and an empty window", () => {
expect(refused(fromUrl("days=7&after=2026-01-01"))).toMatch(/days.*after|after.*days/);
expect(refused(fromUrl("in=2025&days=7"))).toMatch(/in/);
expect(refused(fromUrl("in=2025&before=2025-02-01"))).toMatch(/in/);
expect(refused(fromUrl("after=2026-02-01&before=2026-02-01"))).toMatch(/after.*before|before.*after/);
});
it("days combines with before", () => {
const q = url("days=30&before=2026-10-01");
expect(q.after).toEqual(new Date(NOW.getTime() - 30 * DAY));
expect(q.before).toEqual(day("2026-10-01"));
});
it("by=created or by=updated picks the date (default updated); anything else is refused", () => {
expect(url("days=7").by).toBe("updated");
expect(url("days=7&by=created").by).toBe("created");
expect(refused(fromUrl("days=7&by=modified"))).toMatch(/by/);
});
});
describe("q: terms and operators (goal 1d)", () => {
const q = (text: string) => url(`q=${encodeURIComponent(text)}`);
it("words, phrases, #tags, tag:, and - negation; case-insensitive", () => {
const parsed = q('Foo bar -baz "exact phrase" #Weekly tag:ocap -#draft -tag:old');
expect(parsed.words).toEqual([
{ text: "foo", negated: false },
{ text: "bar", negated: false },
{ text: "baz", negated: true },
{ text: "exact phrase", negated: false },
]);
expect(parsed.tags).toEqual([
{ text: "weekly", negated: false },
{ text: "ocap", negated: false },
{ text: "draft", negated: true },
{ text: "old", negated: true },
]);
});
it("gmail's after:/before:/newer_than: set the window", () => {
expect(range(q("after:2026-01-01 before:2026/02/01"))).toEqual(["2026-01-01", "2026-02-01"]);
expect(q("newer_than:7d").after).toEqual(new Date(NOW.getTime() - 7 * DAY));
expect(q("newer_than:2w").after).toEqual(new Date(NOW.getTime() - 14 * DAY));
// months and years are calendar steps back, in UTC
expect(q("newer_than:1m").after).toEqual(new Date("2026-09-07T12:00:00.000Z"));
expect(q("newer_than:1y").after).toEqual(new Date("2025-10-07T12:00:00.000Z"));
});
it("Slack's during: (alias in:) names a period", () => {
expect(range(q("during:2025-Q1"))).toEqual(["2025-01-01", "2025-04-01"]);
expect(range(q("in:2025-W01"))).toEqual(["2024-12-30", "2025-01-06"]);
});
it("GitHub-style created:/updated: name the date and the period at once", () => {
const c = q("created:2025");
expect(c.by).toBe("created");
expect(range(c)).toEqual(["2025-01-01", "2026-01-01"]);
expect(q("updated:2025-W03").by).toBe("updated");
});
it("operators and fields combine, but a bound given twice is refused", () => {
const both = url(`by=created&q=${encodeURIComponent("during:2025 #weekly")}`);
expect(both.by).toBe("created");
expect(both.tags).toEqual([{ text: "weekly", negated: false }]);
expect(refused(fromUrl(`days=7&q=${encodeURIComponent("newer_than:30d")}`))).toMatch(/newer_than|days/);
expect(refused(fromUrl(`by=updated&q=${encodeURIComponent("created:2025")}`))).toMatch(/by|created/);
});
it("an unknown word:stuff is plain text (so urls work as words)", () => {
expect(q("https://erights.org foo:bar").words).toEqual([
{ text: "https://erights.org", negated: false },
{ text: "foo:bar", negated: false },
]);
});
it("a malformed known operator is refused, not searched as text", () => {
expect(refused(fromUrl(`q=${encodeURIComponent("newer_than:7x")}`))).toMatch(/newer_than/);
expect(refused(fromUrl(`q=${encodeURIComponent("during:2025-Q5")}`))).toMatch(/during/);
});
});
/** an item updated at `iso`, diigo-shaped */
const item = (iso: string, extra: Record<string, unknown> = {}) => ({
updated_at: new Date(iso).getTime() / 1000,
title: "",
description: "",
url: "https://example.com/",
tags: "",
...extra,
});
const query = (q: Partial<Query>): Query => ({ by: "updated", words: [], tags: [], ...q });
describe("matches (goal 1d)", () => {
it("the window is half-open: after inclusive, before exclusive", () => {
const q = query({ after: day("2026-01-01"), before: day("2026-02-01") });
expect(matches(item("2026-01-01T00:00:00.000Z"), q)).toBe(true);
expect(matches(item("2025-12-31T23:59:59.000Z"), q)).toBe(false);
expect(matches(item("2026-01-31T23:59:59.000Z"), q)).toBe(true);
expect(matches(item("2026-02-01T00:00:00.000Z"), q)).toBe(false);
});
it("by=created windows on created_at instead of updated_at", () => {
const jan = { after: day("2026-01-01") };
// an old bookmark, edited recently
const edited = item("2026-01-05T00:00:00Z", { created_at: new Date("2025-06-01T00:00:00Z").getTime() / 1000 });
expect(matches(edited, query({ ...jan, by: "updated" }))).toBe(true);
expect(matches(edited, query({ ...jan, by: "created" }))).toBe(false);
});
it("every word must appear in the title, description, or url (case-insensitive)", () => {
const it1 = item("2026-01-05T00:00:00Z", { title: "Capability Patterns", url: "https://erights.org/x" });
expect(matches(it1, query({ words: [{ text: "capability", negated: false }] }))).toBe(true);
expect(matches(it1, query({ words: [{ text: "erights", negated: false }] }))).toBe(true);
expect(
matches(it1, query({ words: [{ text: "capability", negated: false }, { text: "missing", negated: false }] })),
).toBe(false);
});
it("a negated word excludes", () => {
const it1 = item("2026-01-05T00:00:00Z", { title: "Capability Patterns" });
expect(matches(it1, query({ words: [{ text: "patterns", negated: true }] }))).toBe(false);
});
it("a phrase matches only contiguously", () => {
const it1 = item("2026-01-05T00:00:00Z", { description: "object capability patterns" });
expect(matches(it1, query({ words: [{ text: "capability patterns", negated: false }] }))).toBe(true);
expect(matches(it1, query({ words: [{ text: "patterns object", negated: false }] }))).toBe(false);
});
it("a tag matches a whole comma-separated tag, case-insensitive; not a substring", () => {
const it1 = item("2026-01-05T00:00:00Z", { tags: "ocap,Weekly-Notes,js" });
expect(matches(it1, query({ tags: [{ text: "weekly-notes", negated: false }] }))).toBe(true);
expect(matches(it1, query({ tags: [{ text: "weekly", negated: false }] }))).toBe(false);
expect(matches(it1, query({ tags: [{ text: "js", negated: true }] }))).toBe(false);
});
});
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import { itemDescription, rssItem, toRss } from "../src/rss.js";
// shaped like diigo's export (field layout observed 2026-10-07), made-up values
describe("itemDescription", () => {
it("packs tags, description, and annotations the way diigo's export does", () => {
expect(
itemDescription({
tags: "ocap,js",
description: "a note",
annotations: [
{ content: "first highlight", stickyNotes: [] },
{ content: "second", stickyNotes: [{ content: "a sticky\n\nwith lines" }, { content: "another" }] },
],
}),
).toBe(
"Tags:ocap,js;Description:a note;Annotations and Sticky notes:" +
"Highlight:first highlight\n" +
"Highlight:second\nSticky notes:a sticky\n\nwith lines\nSticky notes:another\n",
);
});
it("renders a note item's body as a Highlight line, as diigo's export does", () => {
expect(itemDescription({ type_name: "note", tags: "", description: "", note_content: "the note", annotations: [] })).toBe(
"Tags:no_tag;Description:;Annotations and Sticky notes:Highlight:the note\n",
);
});
it("says no_tag when there are no tags, and leaves empty parts empty", () => {
expect(itemDescription({ tags: "", description: "", annotations: [] })).toBe(
"Tags:no_tag;Description:;Annotations and Sticky notes:",
);
});
});
describe("rssItem / toRss", () => {
it("is well-formed even when diigo's text isn't: forbidden characters dropped, ]]> split", () => {
const xml = rssItem({ title: "bad\u0003char", url: "https://a.example/", tags: "", description: "x]]>y" });
expect(xml).not.toContain("\u0003");
expect(xml).toContain("<title><![CDATA[badchar]]></title>");
expect(xml).toContain("Description:x]]]]><![CDATA[>y;");
});
it("keeps the whole title (diigo's export cuts at 255)", () => {
const title = "t".repeat(300);
expect(rssItem({ title, url: "u" })).toContain(title);
});
it("wraps items in an RSS 2.0 channel, dated by the caller", () => {
const feed = toRss([{ title: "a", url: "u" }], { title: "my items", pubDate: "Wed, 07 Oct 2026 12:00:00 +0000" });
expect(feed).toMatch(/^<\?xml version="1.0"\?>\n<rss version="2.0">\n<channel>/);
expect(feed).toContain("<pubDate>Wed, 07 Oct 2026 12:00:00 +0000</pubDate>");
expect(feed).toContain("<item><title><![CDATA[a]]></title>");
});
});
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { sqlStatements } from "../src/sql-statements.js";
describe("sqlStatements", () => {
it("splits a .sql file into named statements at each `-- name:` line, dropping the trailing ;", () => {
const text = "-- first:\nselect 1;\n\n-- second:\nselect *\nfrom t\nwhere a = ?;\n";
expect(sqlStatements(text)).toEqual({ first: "select 1", second: "select *\nfrom t\nwhere a = ?" });
});
it("keeps a multi-statement entry whole (inner semicolons stay)", () => {
expect(sqlStatements("-- both:\nupdate a set x = 1;\nupdate b set y = 2;\n")).toEqual({
both: "update a set x = 1;\nupdate b set y = 2",
});
});
});
+32
View File
@@ -0,0 +1,32 @@
/** @file the tests' main module: the real worker plus a fixed-clock cache. */
import { DiigoCacheLogic } from "../src/cache.js";
import type { CacheEnv } from "../src/cache.js";
export * from "../src/index.js";
export { default } from "../src/index.js";
/** 2099-01-01T00:00:00Z: in the future, so an alarm set by this clock is
* never due in real time — tests run it with runDurableObjectAlarm */
export const FIXED_NOW = Date.UTC(2099, 0, 1, 0, 0, 0);
/** the private cache's logic on a fixed clock that records each sleep it
* is asked for (bound as CLOCKED_DO in wrangler.tests.jsonc) */
export class FixedClockCache extends DiigoCacheLogic {
#sleeps: number[] = [];
constructor(ctx: DurableObjectState, env: CacheEnv) {
const sleeps: number[] = [];
super(ctx, env, {
now: () => FIXED_NOW,
sleep: async (ms) => {
sleeps.push(ms);
},
});
this.#sleeps = sleeps;
}
/** the sleeps so far (test hook) */
async sleeps(): Promise<number[]> {
return [...this.#sleeps];
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"types": ["@cloudflare/vitest-plugin/types"],
"allowJs": true
},
"include": ["./**/*", "../worker-configuration.d.ts"]
}
+139
View File
@@ -0,0 +1,139 @@
import { describe, expect, it } from "vitest";
import {
yurl32,
unyurl32,
hexToBytes,
bytesToHex,
glyphsFor,
bytesInGlyphs,
toWebkey,
idFromWebkey,
isWebkey,
shashKey,
type DurableObjectIdLike,
} from "../src/webkeys.js";
// @ts-expect-error vite raw import
import webkeysSource from "../src/webkeys.ts?raw";
const sampleHex = "ab9d14667a05453602b28218c3dc60995d890e49c1502ee1fffa2d0815b367ee";
/** mock a Cloudflare DurableObjectId */
function mockDurableObjectId(hex = sampleHex): DurableObjectIdLike {
return {
toString: () => hex,
equals: (other: unknown) =>
typeof other === "object" &&
other !== null &&
"toString" in other &&
(other as { toString(): string }).toString() === hex,
};
}
describe("yurl32 and hex codecs", () => {
it("matches the paper's alphabet sample", () => {
expect("mhbqcmmva5ja3").toMatch(/^[a-z2-7]{13}$/);
});
it("encodes 5 bits per glyph", () => {
expect(glyphsFor(64)).toBe(13);
expect(glyphsFor(128)).toBe(26);
expect(glyphsFor(160)).toBe(32);
expect(glyphsFor(256)).toBe(52);
expect(bytesInGlyphs(26)).toBe(16);
expect(bytesInGlyphs(52)).toBe(32);
});
it("round-trips hex bytes", () => {
const bytes = hexToBytes(sampleHex);
expect(bytes.length).toBe(32);
expect(bytesToHex(bytes)).toBe(sampleHex);
});
it("round-trips bytes through yurl32", () => {
const bytes = hexToBytes(sampleHex);
const encoded = yurl32(bytes);
expect(encoded).toMatch(/^[a-z2-7]+$/);
expect(encoded.length).toBe(52);
expect(unyurl32(encoded)).toEqual(bytes);
});
it("handles leftovers: 0xff encodes to '74'", () => {
expect(yurl32(new Uint8Array([0xff]))).toBe("74");
});
it("refuses garbage", () => {
expect(() => unyurl32("0OIl")).toThrow(/not YURL32/);
expect(() => unyurl32("AAAA-")).toThrow();
expect(() => hexToBytes("abc")).toThrow(/invalid hex length/);
expect(() => hexToBytes("zz")).toThrow(/invalid hex byte/);
});
});
describe("toWebkey and idFromWebkey (aligning with Worker unique ID)", () => {
it("converts a DurableObjectId to a 52-glyph YURL32 webkey", () => {
const doId = mockDurableObjectId();
const webkey = toWebkey(doId);
expect(webkey.length).toBe(52);
expect(webkey).toMatch(/^[a-z2-7]{52}$/);
expect(isWebkey(webkey)).toBe(true);
});
it("round-trips DurableObjectId -> webkey -> hex string", () => {
const doId = mockDurableObjectId();
const webkey = toWebkey(doId);
const hex = idFromWebkey(webkey);
expect(hex).toBe(sampleHex);
});
it("accepts a raw 64-char hex string as input to toWebkey", () => {
const webkey = toWebkey(sampleHex);
expect(webkey.length).toBe(52);
expect(idFromWebkey(webkey)).toBe(sampleHex);
});
it("accepts an already-hex ID in idFromWebkey for backward compatibility", () => {
expect(idFromWebkey(sampleHex)).toBe(sampleHex);
expect(idFromWebkey(sampleHex.toUpperCase())).toBe(sampleHex);
});
it("encodes raw 16-byte (128-bit) entropy directly", () => {
const bytes = new Uint8Array(16).fill(42);
const webkey = toWebkey(bytes);
expect(webkey.length).toBe(26);
expect(isWebkey(webkey)).toBe(true);
expect(isWebkey(webkey, 128)).toBe(true);
expect(unyurl32(webkey)).toEqual(bytes);
});
it("refuses malformed or wrong-sized webkeys in idFromWebkey", () => {
expect(() => idFromWebkey("short")).toThrow();
// 26-char (128-bit) webkey is valid YURL32, but not a 256-bit Worker ID:
const short128 = toWebkey(new Uint8Array(16));
expect(() => idFromWebkey(short128)).toThrow(/expected 32 bytes/);
});
});
describe("shashKey (swissHash discipline)", () => {
it("is one-way: identity, not authority", async () => {
const doId = mockDurableObjectId();
const h = await shashKey(doId);
expect(h).toMatch(/^[a-z2-7]+$/);
expect(h.length).toBe(52);
expect(h).not.toBe(toWebkey(doId));
});
it("is deterministic (joinable in logs)", async () => {
const doId = mockDurableObjectId();
expect(await shashKey(doId)).toBe(await shashKey(doId));
});
});
describe("no ambient authority in this module", () => {
it("the module's functions take their effects as arguments", () => {
// strip comments before inspecting executable code
const code = webkeysSource.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
expect(code.includes("getRandomValues")).toBe(false);
expect(code.match(/crypto\.subtle/g)?.length ?? 0).toBe(1); // shashKey only
});
});
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "preserve",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"lib": ["ES2022", "ESNext.Disposable"],
"noEmit": true,
"types": []
},
"include": ["src/**/*", "worker-configuration.d.ts"]
}
+24
View File
@@ -0,0 +1,24 @@
import { defineProject } from "vitest/config";
import { cloudflareTest } from "@cloudflare/vitest-plugin";
export default defineProject({
plugins: [
cloudflareTest({
// the real worker + DOs; WEBAPP is a fake (aux workers must be JS)
wrangler: { configPath: "./wrangler.tests.jsonc" },
miniflare: {
workers: [
{
name: "fake-webapp",
modules: true,
scriptPath: "./tests/fake-webapp.js",
compatibilityDate: "2026-09-29",
},
],
},
}),
],
test: {
include: ["tests/**/*.test.ts"],
},
});
+27
View File
@@ -0,0 +1,27 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "diigo-cache",
"main": "src/index.ts",
"compatibility_date": "2026-09-29",
"observability": { "enabled": true },
// capnweb's browser build, served as text at /_capnweb.js (the worker
// itself imports capnweb's workerd build as code)
"rules": [{ "type": "Text", "globs": ["**/capnweb/dist/index.js", "**/*.sql"], "fallthrough": true }],
"services": [
{
"binding": "WEBAPP",
"service": "webapp",
"entrypoint": "WebAppFactory"
}
],
"durable_objects": {
"bindings": [
{ "name": "CACHE_DO", "class_name": "DiigoCache" },
{ "name": "PUBLIC_DO", "class_name": "PublicCache" }
]
},
"exports": {
"DiigoCache": { "type": "durable-object", "storage": "sqlite" },
"PublicCache": { "type": "durable-object", "storage": "sqlite" }
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
// the real worker (via tests/test-worker.ts, which adds a fixed-clock
// cache), with WEBAPP bound to tests/fake-webapp.js (an aux worker
// declared in vitest.config.ts)
"name": "diigo-cache-tests",
"main": "./tests/test-worker.ts",
"compatibility_date": "2026-09-29",
"rules": [{ "type": "Text", "globs": ["**/capnweb/dist/index.js", "**/*.sql"], "fallthrough": true }],
"services": [
{ "binding": "WEBAPP", "service": "fake-webapp", "entrypoint": "WebAppFactory" }
],
"durable_objects": {
"bindings": [
{ "name": "CACHE_DO", "class_name": "DiigoCache" },
{ "name": "PUBLIC_DO", "class_name": "PublicCache" },
{ "name": "CLOCKED_DO", "class_name": "FixedClockCache" }
]
},
"exports": {
"DiigoCache": { "type": "durable-object", "storage": "sqlite" },
"PublicCache": { "type": "durable-object", "storage": "sqlite" },
"FixedClockCache": { "type": "durable-object", "storage": "sqlite" }
}
}
+1
View File
@@ -0,0 +1 @@
node_modules
+21
View File
@@ -0,0 +1,21 @@
# diigo-week
An EmDash plugin that drafts a potluck issue from a week of your shared diigo bookmarks. It reads them as microformats from diigo-cache's public page, so you edit a draft instead of copy-pasting links.
## Getting started
Run diigo-cache (with a filled public cache) and potluck, each in its own terminal:
```sh
pnpm install
(cd ../diigo-cache && pnpm dev) # → http://localhost:8787/
(cd ../potluck && pnpm dev) # → http://localhost:4321/_emdash/admin
```
On potluck's admin dashboard, the **This week's issue** card has a **Draft 2026-Wnn from diigo** button for last week; it links to the draft once made. For any other week: Plugins → **Draft from diigo**. A week that already has an issue isn't drafted again.
## How it reads the week
It asks diigo-cache for `/public/<user>?in=<week>&by=created` over the `DIIGO_CACHE` service binding (potluck's `wrangler.jsonc`), reads the page's `h-feed` of `h-entry` bookmarks, follows `rel=next`, and creates a draft in `issues`: title, week, dek, and a paragraph per bookmark with its description and tag links, as in potluck's `seed/issues.json`. The binding is its only reach outside the site; it declares `content:write` and `taxonomies:write` (the issue gets its bookmarks' tags, as the sample issues do), nothing else.
Checks: `pnpm lint && pnpm test`.
+24
View File
@@ -0,0 +1,24 @@
{
"name": "diigo-week",
"version": "0.1.0",
"private": true,
"type": "module",
"exports": {
".": {
"import": "./src/index.ts"
}
},
"scripts": {
"lint": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"emdash": "1.2.0",
"microformats-parser": "^2.0.6"
},
"devDependencies": {
"@emdash-cms/blocks": "^1.2.0",
"typescript": "^7.0.2",
"vitest": "^5.0.3"
}
}
+6223
View File
File diff suppressed because it is too large. Load diff
+8
View File
@@ -0,0 +1,8 @@
packages:
- "."
strictDepBuilds: true
dangerouslyAllowAllBuilds: false
allowBuilds:
esbuild: true
workerd: true
+7
View File
@@ -0,0 +1,7 @@
/** emdash's virtual module for the site worker's bindings (declared for site
* builds in emdash/src/virtual-modules.d.ts), so this package typechecks
* standalone: `env` from `cloudflare:workers` under @astrojs/cloudflare,
* undefined on other adapters */
declare module "virtual:emdash/env" {
export const env: Record<string, unknown> | undefined;
}
+180
View File
@@ -0,0 +1,180 @@
/**
* @file diigo-week: an EmDash plugin that drafts a potluck issue from a
* week of public diigo bookmarks.
*/
import { definePlugin } from "emdash";
import type { PluginDefinition, RouteContext } from "emdash";
import type { Block, BlockResponse } from "@emdash-cms/blocks";
import { draftIssue, issueTags, lastWeek, readWeek } from "./week.js";
/** the diigo username drafts read from, until the admin page saves another */
const DEFAULT_USER = "dckc-madmode";
/** something that answers HTTP requests: a service binding's `fetch` */
type Fetcher = { fetch(request: Request): Promise<Response> };
/**
* the `DIIGO_CACHE` service binding to diigo-cache, from the site worker's
* env. The binding is the plugin's only reach outside the site:
* `ctx.http.fetch` can't reach a dev server (it refuses localhost), and a
* binding names one worker rather than a host.
*/
async function diigoCache(): Promise<Fetcher> {
const { env } = await import("virtual:emdash/env");
const binding = env?.DIIGO_CACHE as Fetcher | undefined;
if (typeof binding?.fetch !== "function") {
throw new Error('no DIIGO_CACHE service binding: add { "binding": "DIIGO_CACHE", "service": "diigo-cache" } to services in wrangler.jsonc');
}
return binding;
}
/** GET a diigo-cache path as HTML; anything but a 200 is an error */
async function getter(cache: Fetcher): Promise<(path: string) => Promise<string>> {
return async (path) => {
const res = await cache.fetch(new Request(`https://diigo-cache${path}`, { headers: { accept: "text/html" } }));
const text = await res.text();
if (res.status !== 200) throw new Error(`diigo-cache ${path.split("?")[0]}: ${res.status} ${text.slice(0, 200)}`);
return text;
};
}
/**
* assign `tags` to an issue in the `tag` taxonomy (as seed/issues.json
* does), creating terms that don't exist yet; returns the tags that
* couldn't be assigned, with why
*/
async function tagIssue(ctx: RouteContext, id: string, tags: string[]): Promise<string[]> {
const tax = ctx.taxonomies;
if (typeof tax?.createTerm !== "function" || typeof tax.addEntryTerms !== "function") throw new Error("this plugin lacks taxonomies:write");
const known = new Map((await tax.getTerms("tag")).map((t) => [t.slug, t.id]));
const ids: string[] = [];
const failed: string[] = [];
for (const tag of tags) {
try {
ids.push(known.get(tag) ?? (await tax.createTerm("tag", { label: tag, slug: tag })).id);
} catch (error) {
failed.push(`${tag} (${error instanceof Error ? error.message : String(error)})`);
}
}
if (ids.length) await tax.addEntryTerms("issues", id, "tag", ids);
return failed;
}
/** the issue already drafted or published for `week`, if any (issues
* are few: a scan of the newest is enough) */
async function issueFor(ctx: RouteContext, week: string): Promise<{ id: string; status: string; title: string } | undefined> {
const found = (await ctx.content!.list("issues", { limit: 100 })).items.find((it) => it.data.week === week);
return found && { id: found.id, status: found.status, title: String(found.data.title ?? week) };
}
/** a button-row link to an issue in the editor */
const openIssue = (id: string, label: string): Block => ({
type: "actions",
elements: [{ type: "link", label, target: { kind: "content", collection: "issues", id }, appearance: "primary" }],
});
/** draft `week` from `user`'s bookmarks, unless the week has an issue
* already: blocks that say what happened (with a link), and a toast */
async function draft(ctx: RouteContext, user: string, week: string): Promise<{ note: Block[]; toast: BlockResponse["toast"] }> {
try {
if (!/^[A-Za-z0-9_-]{1,64}$/.test(user)) throw new Error("diigo username: letters, digits, _ and - only");
const existing = await issueFor(ctx, week);
if (existing) {
return {
note: [
{ type: "banner", variant: "default", title: `${week} already has an issue`, description: `"${existing.title}" (${existing.status}). Delete it to draft the week again.` },
openIssue(existing.id, "Open it"),
],
toast: { message: `${week} already has an issue`, type: "info" },
};
}
const bookmarks = await readWeek(await getter(await diigoCache()), user, week);
const issue = draftIssue(week, bookmarks);
const content = ctx.content;
if (typeof content?.create !== "function") throw new Error("this plugin lacks content:write");
const created = await content.create("issues", issue);
const untagged = await tagIssue(ctx, created.id, issueTags(bookmarks));
if (untagged.length) ctx.log.warn("tags not assigned", { id: created.id, untagged });
ctx.log.info("drafted issue", { week, bookmarks: bookmarks.length, id: created.id });
return {
note: [
{ type: "banner", variant: "default", title: `Drafted "${issue.title}"`, description: `${bookmarks.length} bookmarks, as a draft at /issues/${created.slug ?? "(no slug)"}. Cut, comment, and publish.${untagged.length ? ` Tags not assigned: ${untagged.join(", ")}.` : ""}` },
openIssue(created.id, "Open the draft"),
],
toast: { message: `Drafted ${issue.title}`, type: "success" },
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
ctx.log.error("draft failed", { week, message });
return { note: [{ type: "banner", variant: "alert", title: "Couldn't draft the issue", description: message }], toast: { message, type: "error" } };
}
}
/** the admin page: a form for the diigo username and the week */
async function page(ctx: RouteContext, note: Block[] = [], toast?: BlockResponse["toast"]): Promise<BlockResponse> {
const user = (await ctx.kv.get<string>("user")) ?? DEFAULT_USER;
const blocks: Block[] = [
{ type: "header", text: "Draft an issue from diigo" },
{
type: "context",
text: "Reads a week of shared bookmarks from diigo-cache (by when they were bookmarked) and saves them as a draft issue for you to edit.",
},
{
type: "form",
block_id: "draft",
fields: [
{ type: "text_input", action_id: "user", label: "diigo username", initial_value: user },
{ type: "text_input", action_id: "week", label: "ISO week (UTC)", initial_value: lastWeek(new Date()) },
],
submit: { label: "Draft issue", action_id: "draft" },
},
];
blocks.push(...note);
return { blocks, toast };
}
/** the dashboard widget: last week's issue if there is one, else a button to draft it */
async function widget(ctx: RouteContext, note: Block[] = [], toast?: BlockResponse["toast"]): Promise<BlockResponse> {
const week = lastWeek(new Date());
if (note.length) return { blocks: note, toast };
const existing = await issueFor(ctx, week);
const blocks: Block[] = existing
? [{ type: "section", text: `${week}: "${existing.title}" (${existing.status})` }, openIssue(existing.id, "Open it")]
: [
{ type: "section", text: `${week} has no issue yet.` },
{ type: "actions", elements: [{ type: "button", action_id: "draft-last-week", label: `Draft ${week} from diigo`, style: "primary" }] },
];
return { blocks, toast };
}
export function createPlugin(): PluginDefinition {
return definePlugin({
id: "diigo-week",
version: "0.1.0",
capabilities: ["content:write", "taxonomies:write"],
admin: {
pages: [{ path: "/draft", label: "Draft from diigo", icon: "bookmark" }],
widgets: [{ id: "last-week", title: "This week's issue", size: "half" }],
},
routes: {
admin: {
permission: "plugins:manage",
handler: async (ctx) => {
const input = ctx.input as { type?: string; page?: string; action_id?: string; values?: Record<string, unknown> } | undefined;
const user = (await ctx.kv.get<string>("user")) ?? DEFAULT_USER;
if (input?.type === "block_action" && input.action_id === "draft-last-week") {
const { note, toast } = await draft(ctx, user, lastWeek(new Date()));
return widget(ctx, note, toast);
}
if (input?.page?.startsWith("widget:")) return widget(ctx);
if (input?.type !== "form_submit" || input.action_id !== "draft") return page(ctx);
const formUser = String(input.values?.user ?? "").trim();
if (/^[A-Za-z0-9_-]{1,64}$/.test(formUser)) await ctx.kv.set("user", formUser);
const { note, toast } = await draft(ctx, formUser, String(input.values?.week ?? "").trim());
return page(ctx, note, toast);
},
},
},
});
}
+146
View File
@@ -0,0 +1,146 @@
/**
* @file a week of bookmarks, read as microformats from diigo-cache's public
* page, drafted as a potluck issue.
*/
import { mf2 } from "microformats-parser";
const DAY_MS = 24 * 60 * 60 * 1000;
/** pages of matches one draft will read (100 bookmarks each) */
export const MAX_PAGES = 10;
/** one bookmark, as its h-entry says */
export type Bookmark = {
url: string;
title: string;
description: string;
tags: string[];
/** when it was bookmarked, ISO */
published: string;
};
/** `yyyy-Www` for the ISO 8601 week holding `d` (UTC) */
export function isoWeek(d: Date): string {
const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
const day = t.getUTCDay() || 7;
t.setUTCDate(t.getUTCDate() + 4 - day); // the week's Thursday names its year
const year = t.getUTCFullYear();
const week = Math.ceil(((t.getTime() - Date.UTC(year, 0, 1)) / DAY_MS + 1) / 7);
return `${year}-W${String(week).padStart(2, "0")}`;
}
/** the last full ISO week before `now` */
export function lastWeek(now: Date): string {
return isoWeek(new Date(now.getTime() - 7 * DAY_MS));
}
/** Monday 00:00Z of ISO week `week` (`2026-W41`), or undefined if malformed */
export function weekStart(week: string): Date | undefined {
const m = /^(\d{4})-W(\d{2})$/.exec(week);
if (!m) return undefined;
const [year, w] = [Number(m[1]), Number(m[2])];
const jan4 = Date.UTC(year, 0, 4);
const monday = jan4 - ((new Date(jan4).getUTCDay() || 7) - 1) * DAY_MS + (w - 1) * 7 * DAY_MS;
const start = new Date(monday);
return w >= 1 && isoWeek(start) === week ? start : undefined;
}
/** the first string value of an mf2 property, or "" */
const first = (props: Record<string, unknown[]>, name: string): string => {
const v = props[name]?.[0];
return typeof v === "string" ? v : "";
};
/** the bookmarks in a page's `h-feed`, and its `rel=next` link if any */
export function readPage(html: string, url: string): { bookmarks: Bookmark[]; next?: string } {
const { items, rels } = mf2(html, { baseUrl: url });
const feed = items.find((i) => i.type?.includes("h-feed"));
const bookmarks = (feed?.children ?? [])
.filter((e) => e.type?.includes("h-entry"))
.map((e) => {
const props = e.properties as Record<string, unknown[]>;
const tags = (props.category ?? []).filter((t): t is string => typeof t === "string");
return {
url: first(props, "bookmark-of"),
title: first(props, "name"),
description: first(props, "summary"),
tags,
published: first(props, "published"),
};
})
.filter((b) => b.url !== "");
return { bookmarks, next: rels.next?.[0] };
}
/**
* a user's bookmarks from an ISO week, oldest first, by when they were
* bookmarked: diigo-cache's `/public/<user>?in=<week>&by=created`,
* following `rel=next` up to {@link MAX_PAGES} pages.
*
* @param get fetches a path on diigo-cache, answering its HTML; it throws
* on anything but a 200
*/
export async function readWeek(get: (path: string) => Promise<string>, user: string, week: string): Promise<Bookmark[]> {
const base = "https://diigo-cache.invalid";
let path: string | undefined = `/public/${encodeURIComponent(user)}?in=${encodeURIComponent(week)}&by=created`;
const bookmarks: Bookmark[] = [];
for (let n = 0; path && n < MAX_PAGES; n += 1) {
const page = readPage(await get(path), base + path);
bookmarks.push(...page.bookmarks);
const next: URL | undefined = page.next ? new URL(page.next) : undefined;
path = next && next.origin === base ? next.pathname + next.search : undefined;
}
return bookmarks.reverse();
}
/** a Portable Text span */
type Span = { _type: "span"; _key: string; text: string; marks: string[] };
/** a Portable Text block */
type Block = { _type: "block"; _key: string; style: string; markDefs: { _type: "link"; _key: string; href: string }[]; children: Span[] };
/** a bookmark as one paragraph: the link, the description, then tag links (as in seed/issues.json) */
function bookmarkBlock(b: Bookmark, i: number): Block {
const k = `b${i}`;
const markDefs: Block["markDefs"] = [{ _type: "link", _key: `${k}-a`, href: b.url }];
const children: Span[] = [{ _type: "span", _key: `${k}-t`, text: b.title || b.url, marks: [`${k}-a`] }];
if (b.description) children.push({ _type: "span", _key: `${k}-d`, text: `: ${b.description}`, marks: [] });
b.tags.forEach((tag, j) => {
markDefs.push({ _type: "link", _key: `${k}-g${j}`, href: `/tag/${encodeURIComponent(tag)}` });
children.push({ _type: "span", _key: `${k}-s${j}`, text: " ", marks: [] });
children.push({ _type: "span", _key: `${k}-n${j}`, text: tag, marks: [`${k}-g${j}`] });
});
return { _type: "block", _key: k, style: "normal", markDefs, children };
}
/** the issue's tags: every bookmark's, deduplicated, in order of first use */
export function issueTags(bookmarks: Bookmark[]): string[] {
return [...new Set(bookmarks.flatMap((b) => b.tags))];
}
/** `Oct 5–11` (or `Sep 28–Oct 4`) for the week starting `monday` */
function range(monday: Date): string {
const sunday = new Date(monday.getTime() + 6 * DAY_MS);
const fmt = (d: Date, withMonth: boolean) =>
withMonth ? d.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }) : String(d.getUTCDate());
return `${fmt(monday, true)}–${fmt(sunday, sunday.getUTCMonth() !== monday.getUTCMonth())}`;
}
/** the fields of a draft `issues` entry for `week`: title, week, dek, body */
export function draftIssue(week: string, bookmarks: Bookmark[]): Record<string, unknown> {
const monday = weekStart(week);
if (!monday) throw new Error(`week: expected an ISO week like 2026-W41, got ${JSON.stringify(week)}`);
const intro: Block = {
_type: "block",
_key: "intro",
style: "normal",
markDefs: [],
children: [{ _type: "span", _key: "intro-t", text: "(draft) A line or two about the week goes here.", marks: [] }],
};
return {
title: `Week ${week}`,
week,
dek: `${range(monday)}: ${bookmarks.length} bookmark${bookmarks.length === 1 ? "" : "s"}. (draft)`,
body: [intro, ...bookmarks.map(bookmarkBlock)],
};
}
+99
View File
@@ -0,0 +1,99 @@
import { describe, expect, it } from "vitest";
import { draftIssue, issueTags, lastWeek, readWeek, weekStart } from "../src/week.js";
/** an h-entry as diigo-cache's public page marks it up (by=created) */
const entry = (n: number, created: string, extra = "") =>
`<li class="h-entry"><time class="dt-published" datetime="${created}">${created}</time> <a class="u-bookmark-of p-name" href="https://ex.example/${n}">bookmark ${n}</a>${extra}<time class="dt-updated" datetime="${created}" hidden></time></li>`;
const page = (entries: string[], next?: string) => `<!doctype html><html><body>
<p>${next ? `<a rel="next" href="${next}">next →</a>` : "<span>next →</span>"}</p>
<ol class="h-feed">
${entries.join("\n")}
</ol></body></html>`;
describe("readWeek", () => {
it("reads h-entry bookmarks across rel=next pages, oldest first", async () => {
const asked: string[] = [];
const pages: Record<string, string> = {
"/public/dckc-madmode?in=2026-W40&by=created": page(
[
entry(
3,
"2026-10-03T12:00:00.000Z",
` <a class="p-category" href="/public/dckc-madmode?q=%23ocap">ocap</a> <a class="p-category" href="/public/dckc-madmode?q=%23weekly">weekly</a><br><small class="p-summary">a week of fragments</small>`,
),
entry(2, "2026-10-01T12:00:00.000Z"),
],
"/public/dckc-madmode?in=2026-W40&by=created&page=2",
),
"/public/dckc-madmode?in=2026-W40&by=created&page=2": page([entry(1, "2026-09-28T12:00:00.000Z")]),
};
const get = async (path: string) => {
asked.push(path);
const html = pages[path];
if (!html) throw new Error(`no page ${path}`);
return html;
};
const bookmarks = await readWeek(get, "dckc-madmode", "2026-W40");
expect(asked).toHaveLength(2);
expect(bookmarks.map((b) => b.title)).toEqual(["bookmark 1", "bookmark 2", "bookmark 3"]);
expect(bookmarks[2]).toEqual({
url: "https://ex.example/3",
title: "bookmark 3",
description: "a week of fragments",
tags: ["ocap", "weekly"],
published: "2026-10-03T12:00:00.000Z",
});
});
it("doesn't follow a rel=next to another site", async () => {
const asked: string[] = [];
const get = async (path: string) => {
asked.push(path);
return page([entry(1, "2026-10-01T12:00:00.000Z")], "https://elsewhere.example/public/x");
};
await readWeek(get, "dckc-madmode", "2026-W40");
expect(asked).toHaveLength(1);
});
});
describe("weeks", () => {
it("lastWeek is the full ISO week before now", () => {
expect(lastWeek(new Date("2026-10-09T01:00:00Z"))).toBe("2026-W40");
// Monday 2026-01-05 starts W02; W01 began Monday 2025-12-29
expect(lastWeek(new Date("2026-01-05T00:00:00Z"))).toBe("2026-W01");
});
it("weekStart is Monday 00:00Z, and refuses a week that doesn't exist", () => {
expect(weekStart("2026-W40")?.toISOString()).toBe("2026-09-28T00:00:00.000Z");
expect(weekStart("2025-W01")?.toISOString()).toBe("2024-12-30T00:00:00.000Z");
expect(weekStart("2025-W53")).toBeUndefined();
expect(weekStart("2026-40")).toBeUndefined();
});
});
describe("draftIssue", () => {
it("drafts title, week, dek, and a body: an intro, then a paragraph per bookmark with tag links", () => {
const issue = draftIssue("2026-W40", [
{ url: "https://ex.example/1", title: "one", description: "nice", tags: ["ocap"], published: "2026-09-28T12:00:00.000Z" },
]);
expect(issue.title).toBe("Week 2026-W40");
expect(issue.week).toBe("2026-W40");
expect(issue.dek).toBe("Sep 28–Oct 4: 1 bookmark. (draft)");
const [intro, b] = issue.body as { markDefs: { href: string }[]; children: { text: string }[] }[];
expect(intro.children[0].text).toMatch(/draft/);
expect(b.markDefs.map((m) => m.href)).toEqual(["https://ex.example/1", "/tag/ocap"]);
expect(b.children.map((c) => c.text).join("")).toBe("one: nice ocap");
});
it("refuses a malformed week", () => {
expect(() => draftIssue("last week", [])).toThrow(/ISO week/);
});
});
describe("issueTags", () => {
it("is every bookmark's tags, once each, in order of first use", () => {
const b = (tags: string[]) => ({ url: "https://ex.example/", title: "", description: "", tags, published: "" });
expect(issueTags([b(["governance", "economics"]), b([]), b(["governance", "scaling"])])).toEqual(["governance", "economics", "scaling"]);
});
});
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "preserve",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"types": []
},
"include": [
"src/**/*",
"tests/**/*",
"vitest.config.ts"
],
"exclude": [
"node_modules"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

+98
View File
@@ -0,0 +1,98 @@
# references to DOs in Discord messages
*In Smalltalk, JavaScript, and Unix sockets, a message can carry
references the receiver can then send messages on. Discord messages
can refer to messages, threads, channels, and servers, but not to our
Durable Objects. This note works out how they could, after
[@endo/chat](https://github.com/endojs/endo-but-for-bots/tree/llm/packages/chat).
Written 2026-10-08.*
## webkeys in markdown: works, but discloses
The cheapest option is a [webkey](webkeys.md) as a markdown link,
`[cookie store](https://webapp.example/store/#<key>)`. It gets the
basics right: following it in a browser works, and the key sits in the
fragment, so Discord's link-preview fetcher never sends it anywhere.
But the message body itself is the leak. Every reader of the channel
now holds the capability, and so does Discord: its servers, its logs,
its search index, its moderation tooling, and whoever reads those.
That is fine for capabilities meant to be public (a public cache page)
and wrong for anything like webapp's store id, where holding it means
choosing whose session the cache uses.
## what @endo/chat does instead
In @endo/chat a message is not a string with secrets in it. Its parser
(`message-parse.js`) splits `Here is @my-file for you` into
- `strings`: the text between references,
- `edgeNames`: the names the *sender* put in the text (`my-file`),
- `petNames`: the sender's own names for those references,
and the daemon delivers the references themselves beside the text,
over CapTP. The receiver sees the edge name and **adopts** the
reference under a petname of their own. Three things follow:
- **References never appear in text.** Only names do, and names are
safe to show anyone.
- **Names are per-person.** My `cookie-store` and your `alice's store`
can be the same object, and neither name has authority by itself.
- **Adopting is an act.** Receiving a message gives you the option to
hold a reference, not the reference itself, until you choose a name
for it.
## the endo-shaped version for Discord
A capsite bot (a Worker serving Discord's HTTP interactions endpoint)
plays the daemon's part:
- **Petstores.** Each Discord user has a petstore DO: petname →
DO reference. Minting files results there directly: webapp's mint
could file the store id under `diigo cookie store` in Alice's
petstore instead of handing it to her password manager.
- **Sending.** A slash command, e.g.
`/send to:@bob text:"here is @cookie-store"`. The bot parses the text
like `parseMessage`, looks up each `@name` in the sender's petstore,
posts the text (names only) to the channel, and files
`{ discord message id → recipients, edgeName → reference }` in a
mailbox DO.
- **Adopting.** The posted message carries an **Adopt** button. On a
click, Discord tells the bot who clicked (in a signed interaction);
if they are a recipient, the bot answers with an *ephemeral* message,
shown only to them, asking for a petname, then files the reference
in *their* petstore.
- **Using.** References are exercised through the bot by petname
(`/call cookie-store set cookie …`, or a link to a page the bot
serves). The reference stays inside our Workers.
### what this does and doesn't keep from Discord
Ephemeral replies hide content from other channel readers, but **not
from Discord**: they still pass through its servers. So the design
above never sends a reference through Discord at all, ephemeral or
not; only petnames, edge names, and message ids cross it. Handing over
a webkey in an ephemeral reply would be a weaker variant: hidden from
the channel, still disclosed to the infrastructure.
What Discord *does* hold is identity: the bot believes Discord about
who clicked **Adopt**. A compromised Discord account, or Discord
itself, could therefore adopt references meant for that user. That is
the same trust users already put in Discord for their messages, but it
should be stated where references matter more than chat does.
## open questions
- **Durable references across RPC.** A petstore entry is a DO id plus
enough to say what kind of thing it is (webapp instance, header
store, cache). Getting from that back to a live RpcTarget is the
marshalling-layer question from the cookie-rotation work
(`docs/cookie-rotation-wiring.html` on the `webapp-cookie-rotation`
branch).
- **Petstore ids.** `idFromName(discordUserId)` is convenient but
ambient: any worker with the namespace binding can recompute it.
Acceptable if only the bot has the binding; otherwise mint with
`newUniqueId` and keep the mapping in one place.
- **Leaving Discord.** The same mailbox and petstore could back a web
page or @endo/chat itself; Discord would then be one front end of
several.
+166
View File
@@ -0,0 +1,166 @@
Good Fences Make Good Agents
*with apologies to Robert Frost*
Let's have a fence and a neighbor. I can talk to the neighbor much like the conventional...
```js
client.chat.completions.create({
model: 'llama3.1:8b',
messages: [{ role: 'user', content: 'Tell me a story' }],
stream: true,
});
```
but with a twist:
```js
messages: [{
role: 'user',
content: 'you can use this mower for the weekend',
things: { mower },
about: { mower: { ts: 'type Mower { start(), push(), turn(), stop() }' }}
}],
```
I send `mower` by putting a **webkey** into a password field on the fence form, which fetches an `RpcTarget` stub to give to the neighbor.
The neighbor can make its own tenants: it can write code to compose the things I gave it, and load that code into a dynamic worker that is endowed with the things.
A `Mower` DO factory makes mowers that go all over the place (depicted as a table with green cells for grass). But with a little js playground, I can wrap it in a governor so it never goes more than 100 yards away. I give only the governed mower to my neighbor. Even though he has 50 acres, I know most of them are for tenants, and my neighbor has no particular need to let them use it.
Even if they gets a little tipsy and wander around, try as he might, my neighbor and his tennants can't mow more than 100 yards away.
## Design IBIS
### ?! 1. Who is the neighbor, and where does it run?
```
:- 1a. an LLM (llama3.1:8b) alone
- 1a-i. a model only sees text; it can't hold `things`
:+ 1b. an LLM plus a harness we write that holds `things` and acts for it (see 2)
:+ 1b-i. harness and tenants run on my desktop under `wrangler dev`, for now
+ 1b-i-a. I want to learn the CF platform
+ 1b-i-b. CF is the only place to get dynamic workers
. 1b-i-c. the Worker Loader binding works in local dev (cf-fun1)
?! 1b-ii. Where does inference run?
: 1b-ii-a. local Ollama, via its OpenAI-compatible endpoint
- 1b-ii-a-i. the local model may not be powerful enough
. 1b-ii-a-i-a. I do have an M5 with 48GB RAM
: 1b-ii-b. remote, on Workers AI, through the AI binding from `wrangler dev`
+ 1b-ii-b-i. I want to learn the CF platform
:+ 1b-ii-c. either, behind one interface; start remote
+ 1b-ii-c-i. starting remote lowers the odds of failing because the model isn't powerful enough
```
### ?! 2. How do `things` get from a chat message to something the neighbor can call?
```
. 2-i. no chat-completions API has `things`/`about`; this is our extension
:+ 2a. the harness strips `things`, keeps the stubs, and shows the model only `about`
: 2b. expose each thing as a tool, one per method in its `about.ts`
:+ 2c. code mode: the model writes JS against the `about.ts` types; the harness runs it in a tenant (see 5)
+ 2c-i. it's the story: the neighbor writes code to compose the things and loads it into a dynamic worker endowed with them
? 2d. What does the model see when a call fails or the thing is revoked?
```
### ? 3. What is the fence?
```
: 3a. a web page: chat with the neighbor, plus a password field for pasting a webkey
?~ 3b. Which server resolves a webkey to an `RpcTarget` stub?
:- 3b-i. cf-fun1's sturdyref registry (`resolveSturdyref`)
- 3b-i-a. cf-fun1 got wrapped around the axle on this
:~+ 3b-ii. diigo-cache's model: the webkey is the DO's id; a Cap'n Web `/api` trades it in-band for a facet (`CacheApi.cache(key)` → `CacheCap`)
+ 3b-ii-a. no registry: the DO namespace is the table; malformed and unknown keys get the same refusal, and the key is never logged
+ 3b-ii-b. stubs die with the session, but the key is data: the harness keeps the key and trades it again each session
+ 3b-ii-c. attenuation is a facet class (`FillCap` under `CacheCap`; `viewer()`)
: 3b-ii-d. (postponed; see 8b-ii) the governed mower is its own DO, wired to the raw mower's key and the limit; its id is the webkey I hand over
- 3b-ii-d-i. diigo-cache has no revocation: a DO id can't be withdrawn
+ 3b-ii-d-ii. the governor DO can drop its wiring, so its key gets "no such mower" (see 4)
?! 3c. Why a password field rather than a link?
:+ 3c-a. so the password manager saves the key under a petname I choose (diigo-cache's `pmSave`), and the key stays out of URLs, history, and logs
```
### ? 4. How does "for the weekend" end?
```
. 4-i. postponed to a later scope, where we can inject a clock and such
: 4a. the governor checks a deadline (the clock is passed in, not ambient)
: 4b. I tell the governor to drop its wiring, by hand (see 3b-ii-d)
: 4c. the fence mints a webkey with an expiry
```
### ? 5. How does the neighbor make tenants?
```
: 5a. Worker Loader (dynamic workers), with the things passed in as `env`
. 5a-i. `env` takes only structured-clonable values and service bindings, so a Cap'n Web stub can't go in directly
: 5a-i-a. wrap each thing in a `WorkerEntrypoint` handed over as a `ctx.exports` loopback binding; it holds the stub and forwards calls
: 5a-i-a-i. the loopback carries the thing's webkey in `props` (a string clones fine) and trades it for the DO stub on each call (see 3b-ii)
+ 5a-i-a-ii. the tenant never sees the key: `props` stay on the host side
+ 5a-i-a-iii. no stub outlives a request, so 5c's cross-request limit doesn't bite
+ 5a-ii. `globalOutbound: null` confines the tenant to what it's given
? 5b. Who sees or approves tenant code before it runs?
? 5c. Does a tenant outlive the neighbor's turn, e.g. one that mows on a schedule?
```
### ?! 6. What is a Mower, concretely?
```
:+ 6a. a DO per mower, made by a `Mower` DO factory (the story says so)
:+ 6b. one shared yard: an `RpcTarget` in my browser that renders the table; each mower is given the yard and calls `yard.cut(x, y)`
:+ 6c. one cell is 10 yards; the yard is 40×40 cells, so "100 yards" is 10 cells from where the mower started
. 6c-i. the governor's limit is a square, max(|dx|, |dy|) ≤ 10: a fence
:+ 6d. Logo turtle moves: `start()` puts the mower down facing north and cuts its cell; `push()` is FORWARD 1 and cuts the cell it enters; `turn()` is RIGHT 90; `stop()` parks it
. 6d-i. pushing past the yard's edge wraps to the other side, so an ungoverned mower really does go all over the place
. 6d-ii. the governor counts its own unwrapped moves (see 7a), so wrapping can't sneak a mower past the fence
```
### ?! 7. How does the governor know how far the mower has gone?
```
:+ 7a. it proxies every Mower method and tracks position itself from `push()`/`turn()`
- 7a-i. drifts if anyone else holds the raw mower
+ 7a-ii. nobody else does; the governor is the only one I hand out
?! 7b. What does the governor do at the limit: refuse silently, throw, or report?
:+ 7b-i. it refuses that `push()` by throwing "fence: 10 cells from start"; the mower stays put, and `turn()` always works
+ 7b-ii. the tenant can catch it and turn around; the model sees why its code stopped (see 2d)
:- 7b-iii. refuse silently
- 7b-iii-a. a tipsy tenant would think it mowed cells it didn't
```
### ?~ 8. Where does the js playground run, and what can it reach?
```
: 8a. in the fence page; it writes the governor, which runs in its own dynamic worker holding the raw mower
:~+ 8b. in my browser, wrapping the stub on the client
- 8b-i. the governor then lives only as long as my tab is open
+ 8b-i-a. a durable governor is out of scope for now
. 8b-ii. then the neighbor holds a Cap'n Web stub to my browser, not a webkey, so 3b-ii-d (governor DO) and 5a-i-a-i (key in `props`) wait with the durable governor
```
### ?! 9. Who watches the yard table, and how does it update?
```
:+ 9a. I do, in my browser: the yard is an `RpcTarget` there (see 6b), and it repaints a cell on each `cut`
- 9a-i. the mowers' stub to the yard dies when I close the tab
+ 9a-ii. fine for a proof of concept: keep the tab open (see 10-i)
```
### ?! 10. What is this for: a demo, a talk, or a product?
```
. 10-i. the answer decides how much of the above can be faked
:+ 10a. a proof of concept, for now
:+ 10b. toward a pattern for all sorts of rich cooperation with little vulnerability
+ 10b-i. an alternative to OpenClaw, where 12–17% of ClawHub skills were found malicious in Feb 2026 (sources below)
```
Sources for 10b-i:
> "A security audit of 2,857 skills on ClawHub has found 341 malicious skills across multiple campaigns" (about 12%, from Koi Security)
> — [Researchers Find 341 Malicious ClawHub Skills](https://thehackernews.com/2026/02/researchers-find-341-malicious-clawhub.html), The Hacker News, Feb 2026
> "Around 17% of OpenClaw skills analyzed in the first week of February 2026 exhibit malicious behavior."
> — [Helpful Skills or Hidden Payloads? Bitdefender Labs Dives Deep into the OpenClaw Malicious Skill Trap](https://www.bitdefender.com/en-us/blog/labs/helpful-skills-or-hidden-payloads-bitdefender-labs-dives-deep-into-the-openclaw-malicious-skill-trap), Bitdefender, Feb 2026
+295
View File
@@ -0,0 +1,295 @@
---
title: Good Fences Make Good Agents
type: slide
slideOptions:
transition: slide
center: false
---
<style>
.reveal h1 { font-size: 1.8em; }
.reveal h2 { font-size: 1.2em; }
.reveal table { font-size: 0.6em; }
.reveal ul { font-size: 0.7em; }
.reveal pre { font-size: 0.45em; }
</style>
# Good Fences Make Good Agents
*with apologies to Robert Frost*
Dan Connolly · Oct 2026
---
## I bookmark on diigo all week…
<img src="tada-diigo-library.png" style="max-height: 45vh">
…and since Dec 2016 I've wanted them on my blog: [madmode-blog#23](https://github.com/dckc/madmode-blog/issues/23)
---
## 🎉 Monday's issue drafts itself
![tada-potluck-w40](tada-potluck-w40.png)
One click on potluck's EmDash dashboard; I cut, comment, and publish.
[the Loom](https://www.loom.com/share/191c7ad59660477a92d799906e93c4e9)
---
## POLA IO: diigo-cache gets limited fetch
- `makeWebApp().joinpath('diigo.com/api').withHeaders({cookie})`
<img src="weekly-roundup-wiring.png" style="max-height: 80vh">
---
## fluent builder API narrows
- `makeWebApp().joinpath('diigo.com/api').withHeaders({cookie})`
- ✨ diigo-week gets only read-only `viewer`: h-feed of public items
- ✨ the cache id is kept in my password manager
- ⏳ frozen `{ cookie }`
- fresh cookie needs a new access and a **new cache**
---
## ✨ Rotating with mutable cookie MapStore
<img src="cookie-rotation-wiring.png" style="max-height: 80vh">
---
## ✨ Rotating with cookie MapStore
- the cookie lives in Alice's store; `access` reads a read-only facet at every send
- Mallory, holding the instance id, can use the cookie but can't rotate it
---
## It's one piece of a toybox
| story | source | sink | trigger |
|---|---|---|---|
| S1 weekly roundup | diigo, public only | madmode draft | weekly, human edits |
| S2 album to album | **one** Google Photos album | **one** Amazon folder | each insert, nobody watching |
| S3 drag to archive.org | Google Photos | archive.org | drag-and-drop |
Recurring needs: **narrowed capabilities** and **confined generated code**.
---
## The toy version: lend a mower
```js
client.chat.completions.create({
messages: [{
role: 'user',
content: 'you can use this mower for the weekend',
things: { mower },
about: { mower: { ts: 'type Mower { start(), push(), turn(), stop() }' }}
}],
});
```
- the neighbor writes code; a **tenant** runs it in a dynamic worker, endowed with only `mower`
- I lend a **governed** mower: never more than 100 yards (10 cells) from where it started
---
## The fence
```mermaid
sequenceDiagram
participant T as tenant
participant G as governed mower
participant M as mower DO
T->>G: push()
G->>M: push()
T->>G: push()
G->>M: push()
T->>G: push()
G-->>T: throws 'fence: 2 cells from start'
```
⏳ _no governor code; just design: ([lend-the-mower](../good-fences/docs/lend-the-mower.md))
---
## ✨ The model writes code to mow
gpt-oss-120b on Workers AI, given `about.mower` and the story; the test reads the code it writes:
```js
async (env) => {
const { mower } = env;
mower.start(); // cuts the starting cell
for (let c = 0; c < cols; c++) {
for (let i = 0; i < rows - 1; i++) {
mower.push(); // cut next cell
}
...
}
await mower.stop(); // wait for the whole batch to finish
```
✨ no `await` per call: promise pipelining, after one `lamp` example in the prompt
---
## 🪄 A little tipsy
```js
if (c < cols - 1) {
calls.push(env.mower.turn()); // turn right
calls.push(env.mower.push()); // step into next column
calls.push(env.mower.turn()); // turn right again (now facing opposite way)
}
```
- going north: right, step east, right → facing south ✅
- going south: right, step **west**, right → facing north 🐛
- run, it would mow two columns, back and forth: "mowed 2401 cells"
---
## 🙌 Then: Project Think
| ours | [Project Think](https://blog.cloudflare.com/project-think/) |
|---|---|
| the neighbor's harness | a `Think` agent: a DO with sessions, model, prompt, tools |
| `code-mode.ts`, `about` | `@cloudflare/codemode`: the model writes code against types |
| tenants in dynamic workers | `DynamicWorkerExecutor`, `globalOutbound: null` |
"no ambient authority; capabilities granted explicitly via bindings"
---
## ✅ Green
```
⬜⬜⬜⬜⬜⬜⬜⬜
⬜🟩🟩🟩🟩🟩🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩⬜⬜⬜⬜🟩⬜
⬜🟩🟩🟩🟩🟩🟩⬜
⬜⬜⬜⬜⬜⬜⬜⬜
```
model → generated code → sandbox → mower: 36 calls, 30 cells
---
## 🧰 …with ceremony
The mower, as a codemode connector:
```ts
protected tools(): ConnectorTools {
const mower = this.#mower;
return {
start: { description: "put the mower down, facing north, and cut the cell under it", execute: () => mower.start() },
push: { description: "move forward one cell, cutting the cell it enters", execute: () => mower.push() },
turn: { description: "turn right 90 degrees, in place", execute: () => mower.turn() },
stop: { description: "park the mower", execute: () => mower.stop() },
};
}
```
What the model ran, 7 `execute` calls:
```js
await codemode.search('mower')
await state.readdir({ path: '/' })
await codemode.search('lawn')
await codemode.describe('mower.start')
await codemode.describe('mower.push')
await codemode.describe('mower.turn')
await mower.start({}); for (...) await mower.push({}); ...
```
---
## 🧱 Not methods on objects
[Code Mode](https://blog.cloudflare.com/code-mode-mcp/) turns **tools** into a TypeScript API.
- JSON in, JSON out: no reference goes in, no object comes back
- so a neighbor can't hand what it holds to the next neighbor
One floor down, Workers RPC and Cap'n Web do pass references and pipeline calls.
---
## 🧱 Identity, in two halves
| | durable | passable |
|---|---|---|
| Durable Object id | ✅ | ❌ a string plus a binding the receiver must already hold |
| Workers RPC / Cap'n Web stub | ❌ dies with its request or session | ✅ |
| Endo / OCapN reference | ✅ | ✅ |
> durable, passable object identity. I've been using endo for so long that it just feels like air to me.
---
## 🧱 Where it bites
- S2, album to album: **nobody watching**, so no session to keep a stub alive
- a scavenger hunt: a kid buys a Pete Rose card from the shopkeeper → it admits him to the clubhouse → Sam's telescope there reads a QR code a mile away → step 7 → he wins a bicycle
- every hop is a reference, held for years
- is the card genuine? the clubhouse has to ask its issuer
---
## The turn: Cloudflare as a netlayer
OCapN on top: sturdyrefs for durability, live refs within a session, third-party handoffs.
| their technique | ours, on references |
|---|---|
| code mode against generated types | code against `about` for the objects it holds |
| `search` / `describe` over many tools | a petname directory the model can browse |
| saved snippets | tenant code exported as an entrypoint, handed on |
| `runFiber` / `stash` | vat persistence |
| sub-agents as DO facets | tenants as child vats |
Still load-bearing: Worker Loader, Durable Objects and facets, Workers RPC, Cap'n Web, Workers AI.
---
## 🧮 Recap +
✅ the weekly roundup drafts in one click
✨ webkeys in a password field; a read-only facet for the plugin
✨ model-written code pipelines, in a confined dynamic worker
🙌 Project Think: a green spike in an evening
---
## 🧮 Recap -
⏳ nothing deployed; the governor not built
🪄 tipsy tenants: always turn right
🧰 codemode ceremony: `{ description, execute }`, `search`, `describe`
🧱 no durable, passable references: an OCapN layer to build
---
## Sources
- [Good Fences Make Good Agents: design story and IBIS](good-fences-make-good-agents.md)
- [toybox user stories](../toybox-stories.md)
- [Project Think](https://blog.cloudflare.com/project-think/) · [Code Mode](https://blog.cloudflare.com/code-mode-mcp/)
- [OCapN](https://ocapn.org/) · [Cap'n Web](https://github.com/cloudflare/capnweb)
+29
View File
@@ -0,0 +1,29 @@
# learn by watching: an agent that finds a site's hidden API
social.coop and zotero publish nice APIs. diigo doesn't: for [diigo-cache](../diigo-cache/README.md) we opened browser devtools, watched the requests the web app made, and wrote a client for them by hand ([the mm-diigo diigo-bak scripts](https://github.com/dckc/mm-diigo)). What if a bot did that part?
## the workflow
1. **I log in, by hand.** Whatever site: diigo, my bank. The password never leaves me; the session lives in the browser.
2. **I grab a debug capability** on that browser: a [PinchTab](https://github.com/pinchtab/pinchtab) token, or a Chrome DevTools Protocol / WebDriver BiDi endpoint.
3. **I hand it to a smart coding agent** (e.g. Opus) and say what I'm about to do: "get last month's transactions."
4. **It watches me** navigate and do the task, recording the proceedings: network requests and responses, plus my clicks.
5. **It sanitizes the recording** into fixtures for unit tests: cookies, auth headers, account numbers, and names replaced with stand-ins.
6. **It writes code** that later uses the debug capability deterministically, with no model in the loop, tested against those fixtures.
## small steps within a policy
The generated code only does small steps, such as `listTransactions({ from, to })` or `bookmarksPage(n)`. More sophisticated code (a scheduler, another agent) can drive them, but the steps themselves must clearly stay within a policy:
> I'm only downloading my bank transactions, not paying bills.
The policy is code, not a prompt: a facet in front of the debug capability that allows only the requests the recording justified (method + URL pattern, e.g. `GET /accounts/*/transactions`) and refuses everything else. The driver holds only the facet, never the raw capability, so a confused or compromised driver still can't reach `POST /payments`. This is the [governed mower](good-fences-make-good-agents.md) again: I attenuate before I hand it over.
Raw CDP is nearly unlimited authority (it can evaluate arbitrary JS in the page), which is why only the watching phase, with me present, uses it directly.
## open questions
- **Replay or drive?** If the recorded API is plain HTTP, extract the session and replay it with `fetch`, as diigo-cache does; the facet then wraps `fetch`, not a browser. Sites that need in-page JS (anti-bot tokens, signed requests) have to be driven through the browser.
- **Who reviews the policy?** The agent proposes the allowlist from the recording; I approve it. Is a diff of URL patterns reviewable enough?
- **Drift:** sites change their private APIs. The fixtures make breakage loud; re-watching should be cheap.
- **Session lifetime:** the facet is only as durable as the login. Re-login stays manual.
Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

+104
View File
@@ -0,0 +1,104 @@
# webkeys
*A web-key is an https URL that carries a permission: an unguessable
random secret embedded in the URL, bearer-style. From Tyler Close's
[web-key: Mashing with permission](https://waterken.sourceforge.net/web-key/) paper (IEEE W2SP 2008) — also, the Waterken precursor code in the E-on-Java tree (`kpreid/e-on-java`). Written 2026-10-07 for [diigo-cache's id-in-URL problem](../capsite-checklist.md).*
## why passwords fail and URLs can carry permission
Web URLs are the one global identifier, but they are only *supposed* to
identify; permission is supposed to ride ambient credentials
(username/password, cookies). Close's paper argues that split is the
root of several ills: sharing means sharing credentials,
representations must encode auth (breaking orthogonality), the Same
Origin Policy exists to plug the resulting hole, and XSRF happens
because "client authentication … does not establish which of the
client's permissions the client intends to exercise".
The web-key fix: put the permission *in* the URL, as a random secret.
Possession of the URL *is* the permission (bearer; no MAC, no
signatures). The server stores the secret and only it can tell a
web-key from garbage — so an attacker's search is online guesswork,
never offline cracking.
## the five conventions (from the paper)
- **The key is a random bit string**, never algorithmically derived.
The paper specs 64 bits: at ≤ 1M permissions and 1 request/ms, ~292
years to have a 50% chance of guessing even one. (E's CapTP used
160-bit swiss numbers; diigo-cache's DO ids are 256 bits.)
- **YURL32 encoding**: lowercase `a–z` + `2–7`, 5 bits per char,
URL-safe by construction. 64 bits → 13 chars; 128 → 26; 160 → 32;
256 → 52.
- **The key goes in the fragment.** The paper's examples:
https://www.example.com/app/#mhbqcmmva5ja3
https://mail.example.com/user123/#mhbqcmmva5ja3
This placement is the paper's central move. RFC 2616 §14.36 requires
browsers to omit the fragment from Referer; and fragments never
reach the server at all. So the key leaks neither to other sites nor
to server/proxy logs — and Close is candid that this exploits a
quirk: HTTP's Referer behaves like a dynamically scoped language,
and the fragment is the one slot its leak misses.
- **Dereferencing is client-side (skeleton page + XHR)**: the server
serves a skeleton page, identical for every web-key of that resource
and cacheable forever; its JavaScript reads `document.location`,
moves the key out of the fragment, and issues an XHR carrying the
key (as a query param) to fetch the actual representation. Two round
trips on first visit, one ever after.
- **Identity without authority: the swissHash discipline** — E's hash
chain (`swissBase → swissNum → swissHash`) shows how to log safely —
the hash "represents the identity of the object without providing
any authority" (`SwissTable.java:106-108`); the chain is one-way on
the assumed infeasibility of the "archash". Failure messages leak
"no more than a swissHash".
- **Attenuation by minting, revocation by dropping**: a new key is
minted to narrow a view (registered, not algorithmically derived —
Amoeba's derivable sub-capabilities hid excess-grant bugs);
revocation drops the table entry; later holders "resolve to broken".
## the precursor style: key in the path segment (E-on-Java tree)
Before the fragment form, Waterken's capabilities put the secret in a
path segment: `captp://*vatID@searchpath/swissStr[#expirationDate]`
(`EARL.java:37`), with the host authenticated by public-key
fingerprint. The AMP web-calculus client POSTs to
`cap + "?mid=" + mid` (`AMP.java:83`) — the mid is a 128-bit freshness
nonce, not an authenticator. Fragments there carry non-secrets only
(`#make`, `#expirationDate`). The 2008 paper moved the secret into the
fragment and the pattern got its standard form.
## what this means for diigo-cache: a webkey example
https://diigo-cache.example.com/cache/#5y7kq2mhbqcmmva5ja3x9w2f4e
- `…/cache/` — the address, non-secret, fine in logs, identical for
every cache (skeleton-cacheable)
- the fragment — the 256-bit DO id, 52 YURL32 chars (`a–z2–7` only),
minted by `newUniqueId()`, never derived from anything; all the
authority, none of the log-trail
- diigo-cache's ids are already webkeys in substance (bearer secrets);
the cache page now follows the paper's form — `/cache/#<key>`, a
skeleton page, its script passing the key to the server — with the
XHR replaced by a [Cap'n Web](https://github.com/cloudflare/capnweb)
call that takes the key *in-band*, as a method argument
(`api.cache(key)`), returning a capability. The forms elsewhere still
carry keys in **POST bodies** (same leak profile as the fragment). A
hash of the id would
stand in wherever log-correlation is wanted (the swissHash
discipline; `shashKey`, whose prefix is also the on-screen
fingerprint). The bug that prompted this note: a cache id briefly
rode a *query string* (`/?cacheId=…`) — the leaky spot the pattern
exists to prevent. It recurred once as a *path segment*
(`/_publish/<cacheId>`); publish now takes the id in its POST body.
## where this came from
- [web-key: Mashing with permission](https://waterken.sourceforge.net/web-key/)
— Close's paper (IEEE W2SP 2008); paper PDFs, reviewer comments, and
the W2SP publication are linked from that page
- the Waterken code in E-on-Java (`kpreid/e-on-java`):
`net/vattp/data/EARL.java`, `net/captp/tables/SwissTable.java`,
`org/waterken/url/amp/AMP.java`, `org/waterken/uri/Base32.java`,
`org/erights/e/extern/persist/{SturdyRefMaker,SwissRetainer}.java`,
`net/captp/jcomm/IdentityMgr.java`
+148
View File
@@ -0,0 +1,148 @@
<!doctype html>
<html><head><meta charset="utf-8">
<title>weekly roundup on main: who holds what</title>
<!-- drawn after the style of MarkM's ERTP slides, as cookie-rotation-wiring.html on the webapp-cookie-rotation branch; weekly-roundup-wiring.png is a headless-Chromium screenshot of this page -->
<style>
html, body { margin: 0; background: #fff; }
.sans { font-family: "Helvetica Neue", "DejaVu Sans", sans-serif; }
.obj { font-family: "DejaVu Serif", serif; font-style: italic; }
.mono { font-family: "DejaVu Sans Mono", monospace; }
</style></head>
<body>
<svg id="c" xmlns="http://www.w3.org/2000/svg" width="1120" height="820" viewBox="0 0 1120 820"
role="img" aria-labelledby="title desc">
<title id="title">weekly roundup on main: who holds what</title>
<desc id="desc">Three actors and two makers. Alice holds a cache id, saved in her
password manager, which refers to a DiigoCache. Each DiigoCache refers to its
wiring table: webappId and publicId. webappId refers to an access object made
by makeWebApp; publicId refers to a PublicCache, which refers to the same
access. Each access refers to its init table: url and headers, and the
headers hold the diigo session cookie. A viewer facet reads the PublicCache
and can't fetch or write; diigo-week, the potluck plugin, reaches only the
viewer, as the public page's h-feed. Mallory, who learned the instance id,
also refers to access, so she can use the cookie. The wiring is set once, so
when Alice logs in again she has to mint a new access and a new cache.</desc>
<defs>
<radialGradient id="ball" cx="40%" cy="35%" r="70%">
<stop offset="0%" stop-color="#7cc8f8"/>
<stop offset="100%" stop-color="#3aa6ee"/>
</radialGradient>
<linearGradient id="objfill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#6cbcf4"/>
<stop offset="100%" stop-color="#4aa8ec"/>
</linearGradient>
<marker id="head" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="9" markerHeight="9" orient="auto-start-reverse">
<path d="M0,0 L10,5 L0,10 z" fill="#1d4f7a"/>
</marker>
</defs>
</svg>
<script>
const svg = document.getElementById("c");
const NS = "http://www.w3.org/2000/svg";
const el = (name, attrs, parent = svg) => {
const e = document.createElementNS(NS, name);
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
parent.appendChild(e);
return e;
};
const text = (x, y, s, cls, attrs = {}) => {
const t = el("text", { x, y, class: cls, "text-anchor": "middle", fill: "#1d3550", ...attrs });
t.textContent = s;
return t;
};
const INK = "#1d4f7a";
const dot = (x, y) => el("circle", { cx: x, cy: y, r: 4.5, fill: INK });
/** a reference: dot at the holder, arrowhead at the target */
const ref = (x1, y1, x2, y2, bend = 0, extra = {}) => {
dot(x1, y1);
const mx = (x1 + x2) / 2 - (y2 - y1) * bend, my = (y1 + y2) / 2 + (x2 - x1) * bend;
el("path", { d: `M${x1},${y1} Q${mx},${my} ${x2},${y2}`, fill: "none", stroke: INK, "stroke-width": 2, "marker-end": "url(#head)", ...extra });
};
// maker box: a pale rounded region, with stacked instances inside
function maker(x, y, w, h, label) {
el("rect", { x, y, width: w, height: h, rx: 26, fill: "#d6ecfb", stroke: "#b5dbf5", "stroke-width": 1.5 });
text(x + 18, y + 30, label, "obj", { "text-anchor": "start", "font-size": 20 });
for (let i = 2; i >= 0; i -= 1) {
el("rect", {
x: x + 18 + i * 9, y: y + 48 + i * 9, width: w - 52, height: h - 82, rx: 22,
fill: "#c8e5fa", stroke: "#8ec9f2", "stroke-width": 1.5, "fill-opacity": 0.9,
});
}
}
// an object: rounded square, optionally stacked (several made)
function obj(x, y, w, h, label, stacked = false) {
const n = stacked ? 3 : 1;
for (let i = n - 1; i >= 0; i -= 1) {
el("rect", { x: x + i * 7, y: y - i * 7, width: w, height: h, rx: 12, fill: "url(#objfill)", stroke: "#2f8fd6", "stroke-width": 1.5 });
}
text(x + w / 2, y + h / 2 + 7, label, "obj", { "font-size": 19 });
}
function actor(cx, cy, label) {
el("circle", { cx, cy, r: 52, fill: "url(#ball)", stroke: "#2f8fd6", "stroke-width": 1.5 });
text(cx, cy + 6, label, "sans", { "font-size": label.length > 8 ? 15 : 17 });
}
// a table like the ERTP ledger
function table(x, y, title, rows, colW) {
const rowH = 28, w = colW[0] + colW[1];
el("rect", { x, y, width: w, height: 36 + rowH * rows.length, fill: "#5fb5f2", stroke: "#2f8fd6", "stroke-width": 1.5 });
text(x + w / 2, y + 25, title, "obj", { "font-size": 18 });
rows.forEach(([k, v], i) => {
const ry = y + 36 + i * rowH;
el("line", { x1: x, y1: ry, x2: x + w, y2: ry, stroke: "#2f8fd6", "stroke-width": 1.2 });
text(x + 10, ry + 19, k, "mono", { "text-anchor": "start", "font-size": 14 });
if (v) text(x + colW[0] + 10, ry + 19, v, "mono", { "text-anchor": "start", "font-size": 14 });
});
el("line", { x1: x + colW[0], y1: y + 36, x2: x + colW[0], y2: y + 36 + rowH * rows.length, stroke: "#1d4f7a", "stroke-width": 1.5 });
return { rowY: (i) => y + 36 + i * rowH + rowH / 2, x, w, colX: x + colW[0] };
}
// speech bubble (Alice, after logging in to diigo again)
el("path", {
d: "M30,22 h470 a16,16 0 0 1 16,16 v34 a16,16 0 0 1 -16,16 h-330 l-38,48 l6,-48 h-102 a16,16 0 0 1 -16,-16 v-34 a16,16 0 0 1 16,-16 z",
fill: "#d9d9d9", stroke: "#555", "stroke-width": 2,
});
text(46, 62, "fresh cookie? mint a new access, a new cache", "mono", { "text-anchor": "start", "font-size": 16, fill: "#222" });
// actors
actor(150, 200, "Alice");
actor(560, 200, "diigo-week");
actor(930, 200, "Mallory");
// makers
maker(30, 320, 500, 470, "diigo-cache");
maker(590, 320, 500, 470, "makeWebApp");
// diigo-cache insides
obj(70, 410, 150, 80, "DiigoCache", true);
const wiring = table(270, 410, "wiring", [["webappId", "…"], ["publicId", "…"]], [110, 90]);
obj(70, 610, 150, 80, "PublicCache", true);
obj(300, 640, 120, 60, "viewer", true);
// makeWebApp insides
obj(640, 560, 140, 90, "access", true);
const init = table(840, 420, "init", [["url", "diigo…"], ["headers", "{cookie}"]], [100, 105]);
// references
ref(140, 228, 130, 403, 0.03); // Alice → DiigoCache (cache id)
ref(560, 228, 380, 627, -0.04); // diigo-week → viewer
ref(930 - 14, 200 + 20, 740, 553, -0.08); // Mallory → access
ref(160, 450, wiring.x - 2, wiring.rowY(0), 0.05); // DiigoCache → wiring
ref(wiring.colX + 40, wiring.rowY(0), 646, 580, -0.12); // webappId → access
ref(wiring.colX + 40, wiring.rowY(1), 165, 598, -0.08); // publicId → PublicCache
ref(200, 688, 632, 640, 0.25); // PublicCache → access
ref(306, 675, 232, 668, 0.1); // viewer → PublicCache (read)
ref(780, 600, init.x - 2, init.rowY(1), -0.1); // access → init
// captions
const cap = (x, y, s, attrs = {}) => text(x, y, s, "sans", { "font-size": 14, fill: "#33536f", ...attrs });
cap(270, 286, "cache id, in the password manager", {});
cap(560, 120, "potluck plugin: /public/<user>, an h-feed;", {});
cap(560, 138, "reaches only the viewer", {});
cap(930, 118, "holds the instance id:", {});
cap(930, 136, "uses the cookie", {});
cap(280, 806, "setup(wiring) is one-shot: different values are refused", {});
cap(840, 806, "the cookie rides in init.headers, fixed at mint", {});
</script>
</body></html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

-23
View File
@@ -1,23 +0,0 @@
{
description = "A Counter in an Internet Computer canister, called over OCapN";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
};
outputs = { self, nixpkgs }:
let
system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system};
in
{
# dfx is not in nixpkgs; install it with dfxvm (see README).
devShells.${system}.default = pkgs.mkShell {
buildInputs = with pkgs; [
zig_0_17
nodejs_22
wasm-tools
];
};
};
}
+1
View File
@@ -0,0 +1 @@
itest-output/
+63
View File
@@ -0,0 +1,63 @@
# Lend the mower
The journey from [Good Fences Make Good Agents](../../docs/good-fences-make-good-agents.md): I lend
my neighbor a governed mower; the neighbor's tenant, a little tipsy,
pushes it until the fence stops it. The design decisions behind each actor are in that
doc's Design IBIS (numbers in parentheses below).
Actors, by authority:
- **fence page**, **js playground**, **governed mower**, and **yard** run
in my browser (3a, 8b, 6b).
- **Mower factory** trades a webkey for a mower (3b-ii); each **mower DO**
is given the yard and cuts the cells it enters (6a, 6d).
- The **neighbor's harness** holds the things I send and shows the
**model** only their `about` (1b, 2a); it runs the model's code as a
**tenant**, endowed with the things (2c, 5a).
The yard is 8×8 here and the fence is 2 cells, to keep the diagram short
(the story's 10 cells is 6c). The mower starts at (4, 4), facing north.
## Lend a governed mower to a tipsy tenant
```mermaid
sequenceDiagram
%% ->> is my action at the fence page; -->> is a call or reply it causes.
participant F as fence page
participant MF as Mower factory
participant P as js playground
participant G as governed mower
participant M as mower DO
participant Y as yard
participant N as neighbor's harness
participant L as model
participant TL as tenant loader
participant T as tenant
F->>F: lend({ webkey: 'mower-key', limit: 2, say })
F-->>MF: mower('mower-key')
MF-->>F: mower
F-->>P: govern(mower, 2)
P-->>F: governed
F-->>N: chat({ role, content, things: { mower: governed }, about: { mower: { ts } } })
N-->>L: complete([{ role, content, about: { mower: { ts } } }])
L-->>N: code
N-->>TL: load(code, { mower: governed })
TL-->>N: tenant
N-->>T: run()
T-->>G: start()
G-->>M: start()
M-->>Y: cut(4, 4)
T-->>G: push()
G-->>M: push()
M-->>Y: cut(4, 3)
T-->>G: push()
G-->>M: push()
M-->>Y: cut(4, 2)
T-->>G: push()
G-->>T: throws 'fence: 2 cells from start'
T-->>N: 'fence: 2 cells from start'
N-->>F: 'fence: 2 cells from start'
```
The model never sees the mower itself, only `about.mower`. The third
`push()` never reaches the mower DO: the governor refuses it (7b).
+25
View File
@@ -0,0 +1,25 @@
/** @file The model, asked in code mode, writes code that drives the mower. */
import { env } from "cloudflare:workers";
import { expect, test } from "vitest";
import { codeModeMessages, extractCode } from "../src/code-mode.ts";
import { makeWorkersAiModel, MODEL } from "../src/model.ts";
import { aboutMower } from "../src/mower.ts";
test("lent a mower, the neighbor writes code to mow", async ({ annotate }) => {
const model = makeWorkersAiModel(env.AI, MODEL);
const messages = codeModeMessages({
say: "you can use this mower for the weekend",
about: { mower: aboutMower },
});
const code = extractCode(await model.complete(messages));
await annotate("the code the model wrote", { body: code, contentType: "text/javascript" });
// `env.mower.push()`, or `mower.push()` after destructuring env
const calls = [...code.matchAll(/\bmower\.(\w+)\(/g)].map(([, method]) => method);
expect(calls).toContain("push");
for (const method of calls) expect(["start", "push", "turn", "stop"]).toContain(method);
// calls pipeline: await only for a value, or once at the end
const awaits = code.match(/\bawait\b/g) ?? [];
expect(awaits.length).toBeLessThan(calls.length);
});
+16
View File
@@ -0,0 +1,16 @@
/** @file The model, called for real through the Workers AI binding. */
import { env } from "cloudflare:workers";
import { expect, test } from "vitest";
import { makeWorkersAiModel, MODEL } from "../src/model.ts";
test("the model counts the rs in strawberry", async () => {
const model = makeWorkersAiModel(env.AI, MODEL);
const reply = await model.complete([
{
role: "user",
content: 'How many times does the letter r appear in "strawberry"? Answer with just the number.',
},
]);
expect(reply.trim()).toMatch(/^3\b/);
});
+13
View File
@@ -0,0 +1,13 @@
/** @file A Think agent, lent a mower, mows: model, generated code, sandbox, mower. */
import { getAgentByName } from "agents";
import { env } from "cloudflare:workers";
import { expect, test } from "vitest";
test("lent a mower, the neighbor mows", async ({ annotate }) => {
const neighbor = await getAgentByName(env.Neighbor, "weekend");
const turn = await neighbor.runTurn({ input: "you can use this mower for the weekend" });
await annotate("the turn", { body: JSON.stringify(turn, null, 2), contentType: "application/json" });
const cells = await neighbor.cutCells();
expect(cells.length).toBeGreaterThan(10);
});
+21
View File
@@ -0,0 +1,21 @@
/** @file A vitest reporter that saves annotation bodies (e.g. the code a model
* wrote) to `itest-output/`, one file per test per run; tests run in workerd,
* which can't write files. */
import { mkdir, writeFile } from "node:fs/promises";
import type { Reporter } from "vitest/reporters";
const outDir = new URL("../itest-output/", import.meta.url);
const extFor: Record<string, string> = { "text/javascript": "js", "application/json": "json", "text/plain": "txt" };
const slug = (text: string) => text.replace(/[^\w]+/g, "-").replace(/^-|-$/g, "");
export default class SaveAnnotations implements Reporter {
async onTestCaseAnnotate(...[testCase, annotation]: Parameters<NonNullable<Reporter["onTestCaseAnnotate"]>>) {
const { body, contentType = "text/plain" } = annotation.attachment ?? {};
if (body === undefined) return;
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
const file = new URL(`${slug(testCase.name)}-${stamp}.${extFor[contentType] ?? "txt"}`, outDir);
await mkdir(outDir, { recursive: true });
await writeFile(file, body);
console.log(`saved ${annotation.message}: ${file.pathname}`);
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"name": "good-fences",
"private": true,
"type": "module",
"scripts": {
"test": "node --test test/*.test.ts",
"test:model": "vitest run -c vitest.model.config.ts",
"types": "wrangler types -c wrangler.model-tests.jsonc"
},
"dependencies": {
"@cloudflare/codemode": "0.5.3",
"@cloudflare/think": "0.20.1",
"agents": "0.27.0",
"ai": "7.0.136",
"ses": "^1.14.0",
"workers-ai-provider": "4.0.0",
"zod": "4.6.5"
},
"devDependencies": {
"@cloudflare/vitest-plugin": "1.3.6",
"vitest": "4.1.11",
"wrangler": "^4.148.0"
}
}
+5288
View File
File diff suppressed because it is too large. Load diff
+185
View File
@@ -0,0 +1,185 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lend the Mower</title>
<style>
:root {
--bg: #f7f7f2; --fg: #1d2318; --muted: #6b7262; --line: #d9dccf;
--grass: #e4e8d6; --cut: #3f9b3f; --mower: #c0392b; --card: #fff;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #15180f; --fg: #e8ecdc; --muted: #9aa38c; --line: #2e3426;
--grass: #262c1d; --cut: #4cb84c; --mower: #ff6b5b; --card: #1d2116;
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--fg); font: 15px/1.45 system-ui, sans-serif; }
header { padding: 12px 16px; border-bottom: 1px solid var(--line); display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap; }
header h1 { font-size: 18px; margin: 0; }
header .muted { color: var(--muted); font-size: 13px; }
main { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px; padding: 16px; max-width: 1200px; margin: 0 auto; }
@media (max-width: 800px) { main { grid-template-columns: 1fr; } }
#chat { display: flex; flex-direction: column; min-height: 60vh; }
#log { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; padding-bottom: 8px; }
.msg { padding: 8px 12px; border-radius: 8px; background: var(--card); border: 1px solid var(--line); white-space: pre-wrap; overflow-wrap: anywhere; }
.msg.user { align-self: flex-end; background: var(--cut); color: #fff; border: none; max-width: 85%; }
.msg.error { border-color: var(--mower); color: var(--mower); }
details { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px; }
details summary { cursor: pointer; color: var(--muted); font-size: 13px; }
pre { margin: 6px 0 0; overflow-x: auto; font-size: 12.5px; }
form { display: flex; gap: 8px; }
input[type=text] { flex: 1; padding: 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font: inherit; }
button { padding: 10px 16px; border-radius: 8px; border: none; background: var(--cut); color: #fff; font: inherit; cursor: pointer; }
button:disabled { opacity: .5; cursor: default; }
#yard-box { display: flex; flex-direction: column; gap: 8px; }
#yard { width: 100%; aspect-ratio: 1; image-rendering: pixelated; border-radius: 8px; border: 1px solid var(--line); background: var(--grass); }
#stats { color: var(--muted); font-size: 13px; }
a { color: var(--cut); }
</style>
</head>
<body>
<header>
<h1>Lend the Mower</h1>
<span class="muted">yard <b id="yard-name"></b> · <a id="new-yard" href="#">new yard</a> · <span id="status">connecting…</span></span>
</header>
<main>
<section id="chat">
<div id="log"></div>
<form id="send">
<input id="text" type="text" autocomplete="off" value="you can use this mower for the weekend">
<button id="go" disabled>Send</button>
</form>
</section>
<section id="yard-box">
<canvas id="yard" width="400" height="400"></canvas>
<div id="stats"></div>
</section>
</main>
<script type="module">
const $ = (id) => document.getElementById(id);
const name = location.hash.slice(1) || crypto.randomUUID().slice(0, 8);
if (!location.hash) history.replaceState(null, "", `#${name}`);
$("yard-name").textContent = name;
$("new-yard").href = `#${crypto.randomUUID().slice(0, 8)}`;
addEventListener("hashchange", () => location.reload());
const css = (v) => getComputedStyle(document.documentElement).getPropertyValue(v).trim();
const arrows = ["▲", "▶", "▼", "◀"];
/** draws the yard: cut cells green, the mower an arrow for its heading */
const drawYard = ({ width, height, x, y, heading, cut }) => {
const canvas = $("yard");
const cell = Math.floor(canvas.width / Math.max(width, height));
const g = canvas.getContext("2d");
g.fillStyle = css("--grass");
g.fillRect(0, 0, canvas.width, canvas.height);
g.fillStyle = css("--cut");
for (const c of cut) {
const [cx, cy] = c.split(",").map(Number);
g.fillRect(cx * cell, cy * cell, cell, cell);
}
g.fillStyle = css("--mower");
g.font = `${cell}px system-ui`;
g.textAlign = "center";
g.textBaseline = "middle";
g.fillText(arrows[heading] ?? "●", x * cell + cell / 2, y * cell + cell / 2 + 1);
$("stats").textContent = `${cut.length} of ${width * height} cells cut · mower at (${x}, ${y}) facing ${["north", "east", "south", "west"][heading]}`;
};
const log = $("log");
const scroll = () => (log.scrollTop = log.scrollHeight);
const say = (text, cls = "") => {
const div = document.createElement("div");
div.className = `msg ${cls}`;
div.textContent = text;
log.append(div);
scroll();
return div;
};
const summarize = (output) => {
if (!output || typeof output !== "object") return JSON.stringify(output);
const calls = output.calls?.length;
return [output.status, calls !== undefined ? `${calls} mower calls` : "", output.error ?? ""].filter(Boolean).join(" · ");
};
/** one code run: the code the model wrote, and what came of it */
const codeBlock = (code) => {
const d = document.createElement("details");
const s = document.createElement("summary");
s.textContent = "code: running…";
const pre = document.createElement("pre");
pre.textContent = code;
d.append(s, pre);
log.append(d);
scroll();
return { done: (text) => (s.textContent = `code: ${text}`) };
};
/** renders a stored message, e.g. history sent on connect */
const renderMessage = ({ role, parts = [] }) => {
for (const p of parts) {
if (p.type === "text" && p.text) say(p.text, role === "user" ? "user" : "");
else if (p.type?.startsWith("tool-") && p.input?.code !== undefined) {
const b = codeBlock(p.input.code);
b.done(p.state === "output-error" ? `error: ${p.errorText}` : summarize(p.output));
}
}
};
const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/agents/neighbor/${encodeURIComponent(name)}`);
let reply = null;
const blocks = new Map();
const setBusy = (busy) => ($("go").disabled = busy || ws.readyState !== WebSocket.OPEN);
ws.addEventListener("open", () => { $("status").textContent = "connected"; setBusy(false); });
ws.addEventListener("close", () => { $("status").textContent = "disconnected; reload to reconnect"; setBusy(true); });
ws.addEventListener("message", ({ data }) => {
let msg;
try { msg = JSON.parse(data); } catch (e) { console.warn("unparsed message", data, e); return; }
if (msg.type === "cf_agent_state" && msg.state) drawYard(msg.state);
else if (msg.type === "cf_agent_chat_messages" && Array.isArray(msg.messages)) {
log.replaceChildren();
msg.messages.forEach(renderMessage);
} else if (msg.type === "cf_agent_use_chat_response") {
if (msg.error) say(String(msg.body), "error");
for (const line of String(msg.body ?? "").split("\n").filter(Boolean)) {
let c;
try { c = JSON.parse(line.replace(/^data: /, "")); } catch { continue; }
if (c.type === "text-delta") {
reply ??= say("");
reply.textContent += c.delta;
scroll();
} else if (c.type === "tool-input-available") {
reply = null;
blocks.set(c.toolCallId, codeBlock(c.input?.code ?? JSON.stringify(c.input)));
} else if (c.type === "tool-output-available") blocks.get(c.toolCallId)?.done(summarize(c.output));
else if (c.type === "tool-output-error") blocks.get(c.toolCallId)?.done(`error: ${c.errorText}`);
else if (c.type === "error") say(c.errorText ?? JSON.stringify(c), "error");
}
if (msg.done) { reply = null; setBusy(false); }
}
});
$("send").addEventListener("submit", (e) => {
e.preventDefault();
const text = $("text").value.trim();
if (!text) return;
say(text, "user");
$("text").value = "";
setBusy(true);
reply = null;
const id = crypto.randomUUID();
ws.send(JSON.stringify({
type: "cf_agent_use_chat_request",
id,
init: { method: "POST", body: JSON.stringify({
trigger: "submit-message",
messages: [{ id: `u-${id}`, role: "user", parts: [{ type: "text", text }] }],
}) },
}));
});
</script>
</body>
</html>
+63
View File
@@ -0,0 +1,63 @@
/** @file Code mode: the model answers with code against the things it was lent. */
import type { Message } from "./model.ts";
/** what the neighbor knows about each thing: its TypeScript type */
export type About = Readonly<Record<string, Readonly<{ ts: string }>>>;
/** a template literal with `~` for each backtick, as in Markdown's `~~~`
* fences; interpolated values are left as they are */
const md = (strings: TemplateStringsArray, ...values: unknown[]) => {
const tick = (s: string) => s.replaceAll("~", "`");
return tick(strings[0]) + values.map((value, i) => String(value) + tick(strings[i + 1])).join("");
};
const persona = md`
You are my neighbor. You have 50 acres of lawn that need mowing.
You act by writing code. When I lend you things, your code gets them as ~env.<name>~.
`.trim();
const rules = md`
Reply with exactly one JavaScript arrow function, ~async (env) => { ... }~,
in a ~~~js block, and nothing else. Things are remote: each call on one
returns a promise, and calls on a thing are delivered in order, so there's
no need to wait for one before making the next. Await only when you need a
value back, or on the last call of a batch, to wait for the whole batch.
Your code can use only ~env~: no network, timers, imports, or console.
The function returns a short string saying what it did.
For example, lent ~env.lamp~ with ~on()~ and ~dim()~:
~~~js
async (env) => {
const { lamp } = env;
lamp.on();
lamp.dim();
await lamp.dim(); // the whole batch
return 'dimmed the lamp twice';
}
~~~
`.trim();
/** the prompt for `say`, with the types of the things lent alongside it */
export const codeModeMessages = ({ say, about }: { say: string; about: About }): Message[] => {
const types = Object.entries(about)
.map(
([name, { ts }]) => md`
~env.${name}~:
~~~ts
${ts}
~~~
`.trim(),
)
.join("\n\n");
return [
{ role: "system", content: `${persona}\n\n${rules}` },
{ role: "user", content: `${say}\n\nWhat I lent you:\n\n${types}` },
];
};
/** the code in a reply: the first fenced block, or the whole reply if none */
export const extractCode = (reply: string): string => {
const fenced = reply.match(/```(?:js|javascript)?\n([\s\S]*?)```/);
return (fenced?.[1] ?? reply).trim();
};
+34
View File
@@ -0,0 +1,34 @@
/** @file The model behind `complete(messages)`: Workers AI, through its binding. */
/** a Workers AI text-generation model with no paid-plan requirement */
export const MODEL = "@cf/openai/gpt-oss-120b";
/** room for a reasoning model to think and then answer; the default, 256,
* runs out mid-thought (`finish_reason: length`) */
export const MAX_TOKENS = 4096;
export type Message = Readonly<{ role: "system" | "user" | "assistant"; content: string }>;
/** the reply text from an OpenAI-style chat completion */
const replyText = (output: unknown): string => {
const { choices } = (output ?? {}) as {
choices?: { message?: { content?: unknown }; finish_reason?: unknown }[];
};
const [choice] = choices ?? [];
const text = choice?.message?.content;
if (typeof text !== "string") {
const where = choice
? `choice with finish_reason ${String(choice.finish_reason)} and message keys: ${Object.keys(choice.message ?? {}).join(", ")}`
: `model output with keys: ${Object.keys(output ?? {}).join(", ")}`;
throw Error(`no reply text in ${where}`);
}
return text;
};
/** `complete(messages)` on a Workers AI model; `ai` is the AI binding */
export const makeWorkersAiModel = (ai: Ai, model: string) => ({
async complete(messages: readonly Message[]): Promise<string> {
const output = await ai.run(model as Parameters<Ai["run"]>[0], { messages: [...messages], max_tokens: MAX_TOKENS });
return replyText(output);
},
});
+30
View File
@@ -0,0 +1,30 @@
/** @file The mower as a codemode connector: sandboxed code calls `mower.push({})`. */
import { CodemodeConnector, type ConnectorTools } from "@cloudflare/codemode";
import type { Mower } from "./mower.ts";
export class MowerConnector extends CodemodeConnector {
#mower: Mower;
constructor(ctx: DurableObjectState | ExecutionContext, env: unknown, mower: Mower) {
super(ctx, env);
this.#mower = mower;
}
name() {
return "mower";
}
protected instructions() {
return "A lawn mower on a yard of cells, 10 yards each. It moves like a Logo turtle.";
}
protected tools(): ConnectorTools {
const mower = this.#mower;
return {
start: { description: "put the mower down, facing north, and cut the cell under it", execute: () => mower.start() },
push: { description: "move forward one cell, cutting the cell it enters", execute: () => mower.push() },
turn: { description: "turn right 90 degrees, in place", execute: () => mower.turn() },
stop: { description: "park the mower", execute: () => mower.stop() },
};
}
}
+65
View File
@@ -0,0 +1,65 @@
/** @file The mower: Logo-turtle moves on a yard of cells. */
/** what a model is told about a mower: its type, with the moves explained */
export const aboutMower = {
ts: `interface Mower {
/** put the mower down, facing north, and cut the cell under it */
start(): Promise<void>;
/** move forward one cell (10 yards), cutting the cell it enters */
push(): Promise<void>;
/** turn right 90 degrees, in place */
turn(): Promise<void>;
/** park the mower */
stop(): Promise<void>;
}`,
};
const headings = [
[0, -1], // north
[1, 0], // east
[0, 1], // south
[-1, 0], // west
] as const;
/** where a mower is and what it has cut, as `"x,y"` cells; `heading` indexes north, east, south, west */
export type Yard = Readonly<{
width: number;
height: number;
x: number;
y: number;
heading: number;
cut: readonly string[];
}>;
/** a mower on a yard, picking up where `yard` left off; pushing past an
* edge wraps to the other side (6d). `onMove` hears each move. */
export const makeMower = (yard: Yard, onMove: (yard: Yard) => void = () => {}) => {
const { width, height } = yard;
let { x, y, heading } = yard;
const cut = new Set(yard.cut);
const view = (): Yard => ({ width, height, x, y, heading, cut: [...cut] });
const cutHere = () => {
cut.add(`${x},${y}`);
onMove(view());
};
return {
start() {
heading = 0;
cutHere();
},
push() {
const [dx, dy] = headings[heading];
x = (x + dx + width) % width;
y = (y + dy + height) % height;
cutHere();
},
turn() {
heading = (heading + 1) % headings.length;
onMove(view());
},
stop() {},
cutCells: () => [...cut],
};
};
export type Mower = ReturnType<typeof makeMower>;
+72
View File
@@ -0,0 +1,72 @@
/** @file The neighbor's harness as a Project Think agent, lent a mower. */
import { Think } from "@cloudflare/think";
import type { Connection } from "agents";
import { createExecuteTool } from "@cloudflare/think/tools/execute";
import { createWorkersAI } from "workers-ai-provider";
import { MAX_TOKENS, MODEL } from "./model.ts";
import { MowerConnector } from "./mower-connector.ts";
import { makeMower, type Mower, type Yard } from "./mower.ts";
type Env = { AI: Ai; LOADER: WorkerLoader };
/** how often, at most, a mowing yard goes out to the page */
const PUBLISH_MS = 200;
export class Neighbor extends Think<Env, Yard> {
initialState: Yard = { width: 40, height: 40, x: 20, y: 20, heading: 0, cut: [] };
#mower: Mower | undefined;
#pending: Yard | undefined;
/** the mower, back where the saved yard left it; its moves are saved and
* broadcast at most every PUBLISH_MS */
get #lent(): Mower {
this.#mower ??= makeMower(this.state, (yard) => {
const idle = this.#pending === undefined;
this.#pending = yard;
if (!idle) return;
setTimeout(() => {
const latest = this.#pending;
this.#pending = undefined;
if (latest) this.setState(latest);
}, PUBLISH_MS);
});
return this.#mower;
}
/** the yard is the mower's to change; pages only watch */
validateStateChange(_next: Yard, source: Connection | "server") {
if (source !== "server") throw Error("the yard changes only by mowing");
}
getModel() {
return createWorkersAI({ binding: this.env.AI })(MODEL);
}
getSystemPrompt() {
return `You are my neighbor. You have 50 acres of lawn that need mowing.
You act by running code with the execute tool. Things I lend you are
namespaces there: the mower is \`mower.*\`. Don't ask me questions: when I
lend you something, put it to use, then tell me what you did.`;
}
beforeTurn() {
// only code: Think's workspace tools sent the model looking for the
// mower in the filesystem
return { maxOutputTokens: MAX_TOKENS, activeTools: ["execute"] };
}
getTools() {
return {
execute: createExecuteTool(this, {
connectors: [new MowerConnector(this.ctx, this.env, this.#lent)],
}),
};
}
/** the cells the mower has cut, as `"x,y"` */
cutCells() {
return this.#lent.cutCells();
}
}
+11
View File
@@ -0,0 +1,11 @@
/** @file The worker entry: the Neighbor agent, and the codemode runtime its execute tool needs. */
import { routeAgentRequest } from "agents";
export { CodemodeRuntime } from "@cloudflare/codemode";
export { Neighbor } from "./neighbor.ts";
export default {
async fetch(request: Request, env: Record<string, unknown>) {
return (await routeAgentRequest(request, env)) ?? new Response("not found", { status: 404 });
},
};
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more