pi-pocket 0.27.0-beta.8 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/docs/design/design-mode.md +1 -1
  2. package/docs/extensions/reference/names.md +2 -2
  3. package/docs/extensions/tools.md +1 -0
  4. package/docs/features.md +2 -1
  5. package/docs/map.md +5 -3
  6. package/package.json +1 -1
  7. package/src/server/design/docsite-color-section.ts +0 -1
  8. package/src/server/design/docsite-components.ts +0 -1
  9. package/src/server/design/docsite-core.ts +4 -14
  10. package/src/server/design/docsite-space.ts +0 -2
  11. package/src/server/design/docsite.ts +0 -4
  12. package/src/server/design/fix.ts +136 -15
  13. package/src/server/design/guide.ts +9 -104
  14. package/src/server/design/index.ts +3 -12
  15. package/src/server/design/lint-color.ts +34 -12
  16. package/src/server/design/lint-suggest.ts +74 -28
  17. package/src/server/design/scan-categorize.ts +0 -2
  18. package/src/server/design/scan-colors.ts +1 -9
  19. package/src/server/design/scan-facts-files.ts +0 -1
  20. package/src/server/design/scan-facts.ts +0 -4
  21. package/src/server/design/scan-files.ts +0 -2
  22. package/src/server/design/scan-import-eval.ts +0 -1
  23. package/src/server/design/scan-import.ts +0 -1
  24. package/src/server/design/scan-infer.ts +1 -1
  25. package/src/server/design/scan-palette.ts +0 -2
  26. package/src/server/design/scan-parse.ts +0 -3
  27. package/src/server/design/scan-prepare.ts +0 -1
  28. package/src/server/design/scan-render-pages.ts +90 -8
  29. package/src/server/design/scan-render-probe.ts +0 -1
  30. package/src/server/design/scan-roles.ts +2 -9
  31. package/src/server/design/scan-scales.ts +0 -1
  32. package/src/server/design/scan-tailwind.ts +0 -1
  33. package/src/server/design/tokens-cache.ts +202 -0
  34. package/src/server/design/tokens-io.ts +14 -0
  35. package/src/server/design/tokens-values.ts +5 -2
  36. package/src/server/design/tokens.ts +11 -3
  37. package/src/server/extensions/agent-teams.ts +1 -1
  38. package/src/server/extensions/artifacts.ts +35 -65
  39. package/src/server/extensions/browser.ts +8 -13
  40. package/src/server/extensions/codemode.ts +16 -2
  41. package/src/server/extensions/design/color.js +0 -1
  42. package/src/server/extensions/design/style.css +5 -0
  43. package/src/server/extensions/design/system-routes.ts +7 -4
  44. package/src/server/extensions/design/system-widgets.js +0 -1
  45. package/src/server/extensions/design/system.css +0 -2
  46. package/src/server/extensions/memory.ts +14 -19
  47. package/src/server/extensions/plan.ts +1 -0
  48. package/src/server/extensions/prompt.ts +49 -15
  49. package/src/server/extensions/schedules.ts +2 -2
  50. package/src/server/extensions/subagents.ts +19 -23
  51. package/src/server/extensions/tool-search.ts +182 -0
  52. package/src/server/gallery/reach.ts +36 -17
  53. package/src/server/guides/artifact-bridge.md +7 -0
  54. package/src/server/guides/design.md +124 -0
  55. package/src/server/reload.ts +3 -0
  56. package/docs/design/notes-a.md +0 -106
  57. package/docs/design/notes-b.md +0 -123
  58. package/docs/design/notes-c.md +0 -92
  59. package/docs/design/notes-d.md +0 -78
@@ -1,6 +1,6 @@
1
1
  # Design mode (0.26.0)
2
2
 
3
- Status: built. The four streams (A to D) are merged into `feat/design`, off `release/0.26.0`. This page is the plan, corrected where the build differs from it. Each place that changed says "Built:". What each stream built is in `notes-a.md` to `notes-d.md`; the words for the release are in `release-notes-design.md`.
3
+ Status: built. The four streams (A to D) are merged into `feat/design`, off `release/0.26.0`. This page is the plan, corrected where the build differs from it. Each place that changed says "Built:". The words for the release are in `release-notes-design.md`.
4
4
 
5
5
  Design mode gives Pi Pocket what Claude Design has: a big canvas beside the chat, where Pi makes interactive designs (prototypes, screens, one-pagers, slide decks), and people point at them, comment, tweak, edit text, compare versions and variations, export, and hand off to code.
6
6
 
@@ -7,7 +7,7 @@ The rules for the names that a module gives. These are the names of its file, ex
7
7
  To install an extension with the name of an installed extension replaces that extension. A tool with the name of another tool replaces it in all sessions. Thus Pi Pocket refuses a drop-in that would take a name that Pi Pocket keeps, or a name that another module has. Menu → Extensions says why.
8
8
 
9
9
  - **Extension names that Pi Pocket keeps:** `coding-tools`, and all names that start with `pocket-`, such as `pocket-core`, `pocket-prompt`, and `pocket-guard`. This is true also when that built-in module is off.
10
- - **Built-in tools:** `read`, `write`, `edit`, `bash`, `artifact`, `artifact_inline`, `browser`, `subagent`, `team`, `schedule`, `codemode`, and `memory`. PiP's tools: `sessions`, `session_read`, `session_start`, `session_send`, `session_follow`, `session_stop`, `session_archive`, `session_schedule`, `approvals`, `repo_watch`, and `session_watch_pr`. The triggers' tool: `watch_pr`. Design's tools: `design_preview`, `design_export`, and `design_system`.
10
+ - **Built-in tools:** `read`, `write`, `edit`, `bash`, `artifact`, `artifact_inline`, `browser`, `subagent`, `team`, `schedule`, `background`, `codemode`, `tool_search`, `memory`, `ask`, and `ask_someone`. PiP's tools: `sessions`, `session_read`, `session_start`, `session_send`, `session_follow`, `session_stop`, `session_archive`, `session_schedule`, `approvals`, `repo_watch`, and `session_watch_pr`. The triggers' tool: `watch_pr`. Design's tools: `design_preview`, `design_export`, and `design_system`.
11
11
  - **Names that another module has:** the first module to install an extension or tool keeps its name.
12
12
 
13
13
  Give each extension and tool a name of your own, with a prefix: `example-clock`, `acme_lookup`. To change how a built-in tool works, do not replace it. Wrap it (`wrapTool` in Pi Durable's README), or check its calls with a hook.
@@ -16,7 +16,7 @@ Give each extension and tool a name of your own, with a prefix: `example-clock`,
16
16
 
17
17
  - A module is a `.ts` file in the drop-in folder.
18
18
  - Files that start with `_`, or that end in `.test.ts`, are not modules. Use them for helpers and tests.
19
- - A drop-in with the name of a built-in module does not load. The built-in modules are `prompt`, `artifacts`, `browser`, `subagents`, `agent-teams`, `schedules`, `goals`, `plan`, `guard`, `codemode`, `memory`, `pip`, `triggers`, `gallery`, and `design`.
19
+ - A drop-in with the name of a built-in module does not load. The built-in modules are `prompt`, `artifacts`, `browser`, `subagents`, `agent-teams`, `schedules`, `goals`, `plan`, `guard`, `codemode`, `memory`, `pip`, `triggers`, `gallery`, `design`, and `tool-search`.
20
20
  - `_pocket.d.ts` in the drop-in folder is Pi Pocket's link to its types. Do not use this name. See [Types for your editor](types.md).
21
21
 
22
22
  What a module adds to the app uses the name of its file without `.ts`: `server-status.ts` is `server-status`, at `/api/x/server-status/` and `/x/server-status/`. File names are unique across the two folders of modules, so these addresses never collide. A module that adds to the app needs a name of letters, digits, `-`, and `_` that starts with a letter or digit.
@@ -27,6 +27,7 @@ export default function createMyWords() {
27
27
 
28
28
  - `name` must be different from the name of each other tool ([Names](reference/names.md)). Use a prefix of your own.
29
29
  - `description` and `parameters` go to the model with each request. Keep them short and exact.
30
+ - `deferred: true` keeps a tool out of the requests until Pi loads it with `tool_search`, which only the Tool search module offers: while it is off, Pi cannot load the tool. Use it for a tool that few conversations need, or for a large set of tools. `test/prompt-budget.test.ts` keeps Pi Pocket's own prompt and tools at 16,000 characters in a plain session.
30
31
  - `parameters` is a TypeBox schema (`Type` from `@earendil-works/pi-ai`). Pi Durable checks the arguments against it before `execute` runs.
31
32
  - `execute(args, api, context)` does the work.
32
33
 
package/docs/features.md CHANGED
@@ -20,6 +20,7 @@ The full tour. For setup, see the [README](../README.md).
20
20
  - **A new context.** Menu → **New context** (or `/reset [note]`): Pi starts fresh and no longer sees the messages so far, while everyone still does. An optional handoff note carries over what matters.
21
21
  - **Instructions for Pi.** Menu → **Instructions for Pi** (or `/instructions …`): ground rules Pi gets with every message in this session, such as "use pnpm, not npm". Everyone in the session can see them.
22
22
  - **Memory.** Short lessons Pi keeps across sessions: how to build and test a project, a gotcha it hit, a convention, a preference someone stated. Pi proposes one with its `memory` tool (one or two sentences each, never secrets) only when a person asks for it, or when Pi is sure that it will help in many later sessions, never for a one-off detail, and proposes fixing or forgetting one that turns out wrong; the owner approves. What Pi reads (a web page, a post, a comment, a file) could talk it into a "lesson" that would reach every later session, so nothing Pi saves, changes, or forgets counts until the owner says: **Approve** and **Discard** show right under Pi's memory call, with the words that wait and where they would apply (this project, or everywhere: every session and PiP), and in the sheet. Approve approves only what you saw: if Pi changed it since, the app says so and shows the new words. Lessons and project names are kept on one line, without invisible characters, so Pi reads only what the owner saw. A change or forgetting Pi proposes leaves the lesson as it was until then. Lessons you add yourself count at once. Each is for this project or for everywhere: a project's lessons reach every later session in the same repository, its worktrees included (or the same folder, outside a repository), and everywhere's reach every session and PiP. Menu → **Memory** (its hint says how many apply here and everywhere) lists them in those two groups, each with who saved it and a link to the session it came from (when you may see it), with Edit and Forget; type one in to add it by hand, for this project or everywhere, or use `/remember run the tests with make check` or **Remember…** on a message. A guest's lessons wait for the owner too, and a guest's change to one in force is a proposal they can withdraw. What waits shows at the top of the owner's sheet; the menu's hint says how many. Lessons waiting take no room from the approved ones, and a person (or Pi for them) may have 20 waiting at most. Only the owner, or whoever saved a lesson, changes or forgets it; viewers only read. A project keeps 40 lessons and everywhere 30; past that, forget one first. Changes show as lines in the chat. Turn it off in Extensions.
23
+ - **A lean prompt.** A new session gets only the tools most conversations use. `browser`, `background`, `schedule`, `watch_pr`, `ask_someone`, and the design tools wait, and so do their prompt sections; the prompt lists them with a line each, and Pi loads one with `tool_search` when a task needs it. On a model whose provider takes tool changes in the messages (Claude 4.8 and 5, and later), the tool joins the list and stays for the conversation; on any other, Pi calls it from a `codemode` script, so the tool list and the prompt cache never change. Long guides, such as the design guide and the page-to-app messages of artifacts, are files that Pi reads when it needs them. Turn the **Tool search** module off in Menu → Extensions to offer every tool every time. A test keeps Pi Pocket's own part of a plain session's prompt at 16,000 characters (about 4,000 tokens) or less.
23
24
  - **Plan mode.** The **Plan** chip by the message box (or `/plan`): Pi reads files, runs read-only commands, and uses tools their extensions mark read-only, then proposes a plan; writing, editing, and other commands are blocked. Subagents inherit plan mode and explore under the same restrictions. **Approve plan** turns plan mode off and tells Pi to go ahead; it waits until Pi has answered since plan mode went on.
24
25
  - **Scheduled messages.** `/schedule in 2h check the deploy`, `/schedule tomorrow 9am …`, or `/schedule every weekday 8:00 summarize CI`, or Menu → **Scheduled messages**: Pi gets the message at its time, in this device's time zone, even with nobody watching, and the people in the session get the usual "Pi finished" notification. Pi can schedule its own follow-ups with its `schedule` tool. Each schedule is a durable task: a restart while it waits keeps waiting, one after its time sends at once, and none is ever sent twice. A schedule is cancelled, with a line in the chat saying why, once its person can no longer steer the session or a spend limit is reached. Limits (settable since 0.24.0): a session holds 50 schedules, a message 4000 characters, a repeat comes at most every 10 minutes (a short repeat can cost money in model calls), and `in …` reaches 366 days ahead. The owner changes each in Menu → Extensions, under Scheduled messages; a change applies at once, to new schedules only.
25
26
  - **Done when.** `/until npm test`: after each of Pi's answers, the check runs in the session's folder; while it fails, Pi gets the end of its output and keeps going, for five checks at most. A bar above the message box shows how it stands. With Lancet Guard on, the check must be a command the guard allows outright. In plan mode the check waits until the plan is approved, and past a spend limit Pi stops going on. A check cut off by a server restart is not run again, as it may have done part of its work: Pi hears so, and its next answer is checked.
@@ -69,7 +70,7 @@ The full tour. For setup, see the [README](../README.md).
69
70
  - **Tweaks.** A page can declare knobs (colors, sizes, choices, switches) and the Tweaks tab shows them as controls that change the page live. Values are each person's own, kept for each design. **Keep these** puts them in the message box so that Pi writes them into the design.
70
71
  - **Variations.** Artifacts of one group show as a grid of live thumbnails. **Use this one** puts a message about it in the message box.
71
72
  - **Export and share.** PNG, PDF, PPTX (decks), and an HTML zip, from the menu. The file is written in the session's `exports/` folder and the browser downloads it. **Share a link** is the artifact viewer's Share. There is no Canva export.
72
- - **What Pi does.** Its guide (a prompt section, only while the module is on) gives Pi an order of work, after Claude Design's (since 0.27.0): one round of questions when the work is new or unclear, then a start from what exists (the design system, the code, the screens) rather than a mock from scratch, a first version early, iterations, a check, and a short reply. A screen that exists is redesigned from itself: Pi reads its code and data first, makes version 1 the screen as it is today (in its place in the app, compared with a screenshot of the real one when it can get one), and then changes it in new versions, within what the code supports; a change that needs new data or server work is marked in the design and named in the reply, and a different direction becomes a new artifact in the same group. The product's own type sizes, spacing, and density win over the guide's craft defaults. It also gives Pi a page skeleton and craft rules: one HTML artifact for each design, `data-pid` on meaningful elements, a tweaks manifest of 3 to 8 knobs bound to the system's tokens, assets for images and fonts, variations as a group of 2 to 4 artifacts, a link to `ds/tokens.css` when the project has a design system, and a check with `design_preview` before it replies. When the project has a system, the guide carries a summary of it (roles and components first) as untrusted project data. Its tools: `design_preview` renders a version in a private headless Chromium (never the browser people watch) at mobile and desktop sizes, or the sizes asked for, and returns screenshots and a short report (see **Checks**); its options are `checks` (on by default), `tweaks`, `colorScheme`, `page` (another page of the bundle), and `actions` (hover, click, or focus on a selector before the screenshot). `design_export` writes PNG, PDF, PPTX, or an HTML zip, by default as `exports/<id>-v<version>.<ext>`, and refuses a path outside the session's folder; it also takes `tweaks`, a custom `viewport`, and, for a deck's PNG, `slide` (a number, or `"all"` for a zip of every slide). A page's PDF is as wide as its viewport, and PPTX slide images have twice the pixels. `design_system` reads, scans, and changes the project's design system (see **The design system**). The private renderer serves the bundle on a loopback address under a random path and gives Chromium no sign-in; other requests go through `host.fetchPublic`, so a design reaches only public addresses. Renders run 2 at once, and more wait their turn; each has 90 seconds.
73
+ - **What Pi does.** Its guide, `src/server/guides/design.md`, which Pi reads before it makes or changes a design (a short prompt section, only while the module is on, points to it), gives Pi an order of work, after Claude Design's (since 0.27.0): one round of questions when the work is new or unclear, then a start from what exists (the design system, the code, the screens) rather than a mock from scratch, a first version early, iterations, a check, and a short reply. A screen that exists is redesigned from itself: Pi reads its code and data first, makes version 1 the screen as it is today (in its place in the app, compared with a screenshot of the real one when it can get one), and then changes it in new versions, within what the code supports; a change that needs new data or server work is marked in the design and named in the reply, and a different direction becomes a new artifact in the same group. The product's own type sizes, spacing, and density win over the guide's craft defaults. It also gives Pi a page skeleton and craft rules: one HTML artifact for each design, `data-pid` on meaningful elements, a tweaks manifest of 3 to 8 knobs bound to the system's tokens, assets for images and fonts, variations as a group of 2 to 4 artifacts, a link to `ds/tokens.css` when the project has a design system, and a check with `design_preview` before it replies. When the project has a system, the prompt section carries a summary of it (roles and components first) as untrusted project data. Its tools: `design_preview` renders a version in a private headless Chromium (never the browser people watch) at mobile and desktop sizes, or the sizes asked for, and returns screenshots and a short report (see **Checks**); its options are `checks` (on by default), `tweaks`, `colorScheme`, `page` (another page of the bundle), and `actions` (hover, click, or focus on a selector before the screenshot). `design_export` writes PNG, PDF, PPTX, or an HTML zip, by default as `exports/<id>-v<version>.<ext>`, and refuses a path outside the session's folder; it also takes `tweaks`, a custom `viewport`, and, for a deck's PNG, `slide` (a number, or `"all"` for a zip of every slide). A page's PDF is as wide as its viewport, and PPTX slide images have twice the pixels. `design_system` reads, scans, and changes the project's design system (see **The design system**). The private renderer serves the bundle on a loopback address under a random path and gives Chromium no sign-in; other requests go through `host.fetchPublic`, so a design reaches only public addresses. Renders run 2 at once, and more wait their turn; each has 90 seconds.
73
74
  - **The design system.** A project's design system lives in `.pi/design/` in the session's folder: `tokens.json` (W3C Design Tokens, DTCG: groups, `$value`, `$type`, references such as `{color.blue.500}`, tiers for primitives, semantic roles, and component tokens), `tokens.<mode>.json` for each other mode (dark, high contrast, a brand), `components/<slug>.html` (a component specimen with its states), and `guidelines.md`. Pi Pocket checks it (broken or circular references, raw values in semantic roles, declared contrast pairs in every mode) and builds `dist/`: `tokens.css` (`:root`, a `[data-theme]` block for each mode, and a `prefers-color-scheme` block), `tailwind.css` (a Tailwind v4 `@theme`, with utilities such as `bg-surface` and `text-primary`), `tokens.<mode>.resolved.json` (DTCG, one for each mode), `tokens.studio.json` (Tokens Studio), `tokens.resolved.json` (a compact summary), and `components.css`. A design that links `ds/tokens.css`, `ds/tailwind.css`, or `ds/components.css` gets the current files as assets when Pi publishes it, a snapshot kept with that version. Pi's `design_system` tool has the actions `scan` (a structured draft from the project's style files: colors in every CSS syntax, roles, the type, spacing, and radius scales, shadows, breakpoints, and dark mode, from CSS custom properties and rules in CSS, SCSS, Less, and page style blocks, Sass and Less variables with literal values, Tailwind's `@theme` and a `tailwind.config` theme read as a literal, and DTCG, Style Dictionary, and Tokens Studio JSON files; a browser renders the project's pages to fill in what the files leave out), `init` (from a scan or given tokens; it refuses to replace a system unless asked), `set`, `validate`, `compile`, `component`, `guidelines`, and the 0.26 `read` and `write`. A project with only `.pi/design-system.md` (the 0.26 format) keeps working.
74
75
  - **The System view.** The first row of the design picker (or `/design-open system`, or the launcher's "Open the design system") shows the system: **Colors** (role cards with contrast badges first, a live sample card, and the palette as ramp strips in a folded group), **Type**, **Spacing**, **Radii**, **Shadows** (each with its value), **Motion** (durations and easings that play), **Components** (every state, in a frame that runs nothing and loads nothing), and **Guidelines**. A section's count is its role tokens; the palette and component tokens show their own counts inside it. Modes show one at a time or side by side, and a mode's value says whether it is its own or inherited from the default. People who steer change a color, a size, a time, a weight, a font, an easing, or a shadow's layers in place, or link a token to another; the open design shows each change live when it uses the system's variables. The editor lists every contrast pair of a color (an exempt pair shows as exempt, not as a failure). **Undo** and **Redo** step through the changes, **Discard** gives them up, and **Save** writes the files and the generated CSS with no run of Pi (it refuses a change that the checks refuse, or one made on a system that changed meanwhile). The menu publishes the documentation page as a design, exports the generated files as a zip, and adds or removes a mode. People who only view see everything and change nothing. **Focus mode** hides the conversation for wide work. On a phone, the canvas fits the screen's width, and until a size is chosen it takes the size of its panel. The Design module loads only a small shell at app start; the workspace and the System view load when first opened.
75
76
  - **Checks.** A design's **Check** tab and `design_preview` render the page on the server and judge only what the author's CSS sets, never the browser's defaults. They report values that are not the system's (colors, fonts, and sizes, each with the exact CSS edit and the nearest token of the matching role), contrast (WCAG 2.2 AA, judged only where the background is certain), non-text contrast of focus rings and icon buttons (3:1), tap targets (an error under 24 px, a warning under 44 px), sideways overflow, image alt text, heading order, a missing `lang`, form controls with no label (a placeholder is not a label), links, buttons, and widgets with no accessible name, no `main` landmark, fonts that did not load, a missing viewport tag, missing `data-pid`s, elements with no visible focus style, long motion with no `prefers-reduced-motion` rule, and author-set input text under 16 px on a phone. A check runs in any mode of the system. The tab follows the mode and size on the canvas, puts a pin on each element, and **Send to Pi** puts one message with every finding in the message box. **Fix N exact matches** rewrites literals that equal a token exactly to `var(--token)` and saves a new version with no run of Pi. On a phone, the tab starts as a bar with the counts, so the page keeps most of the screen.
package/docs/map.md CHANGED
@@ -150,6 +150,7 @@ The agent's side of Design mode. `extensions/design.ts` installs it (see Extensi
150
150
  | `design/pptx.ts` | The PPTX writer: one image for each slide, at the deck's slide size (16:9 by default), with the slide's text as speaker notes, through `zip.ts` |
151
151
  | `design/system-types.ts` | The shared shapes: `DesignSystem`, `ResolvedToken`, `ComponentSpec`, `SystemChange`, `CheckReport`, `CheckFinding` |
152
152
  | `design/tokens.ts` | The tokens engine: `loadDesignSystem`, `writeDesignSystem` (validate, atomic writes, rebuild `dist/`), `compileDesignSystem`, `systemSummary`; `tokens-model.ts` (`buildSystem`: the phases in order) with `tokens-model-defs.ts` (definitions and modes), `tokens-model-resolve.ts` (types and references), `tokens-model-checks.ts` (the warnings and contrast), and `tokens-model-report.ts` (the problem list), `tokens-values.ts` (value forms), `tokens-ramps.ts` (the ramp-order warning), `tokens-compile.ts` (`tokens.css`, `components.css`), `tokens-tailwind.ts` (the Tailwind v4 theme), `tokens-names.ts` (the names table, `names.md`), `tokens-dtcg.ts` (the DTCG files for each mode, the 2025.10 forms, and `tokens.studio.json`), `tokens-io.ts` (bounded reads without links), `tokens-summary.ts` (the prompt summary: roles and components first), `tokens-base.ts` |
153
+ | `design/tokens-cache.ts` | A loaded system kept while its folder's files stay the same: the revision is read on every call, so an edit by any program shows at once |
153
154
  | `design/components.ts` | Component specimens: `components/<slug>.html` with its metadata, CSS, and one template for each state |
154
155
  | `design/color.ts` | Color math: re-exports `extensions/design/color.js` (every CSS color syntax and DTCG color objects, OKLab and OKLCH, WCAG luminance and contrast, hex), the one copy that the server and the System view share, and adds `mixColors` |
155
156
  | `design/system.ts` | `design_system`: the actions on `.pi/design/` and the 0.26 `.pi/design-system.md`, its parameters, bounded, read and written without following links, output fenced as project data |
@@ -158,17 +159,18 @@ The agent's side of Design mode. `extensions/design.ts` installs it (see Extensi
158
159
  | `design/scan-render.ts` | The rendered scan: a project's HTML pages shown offline in the private Chromium, once as they are and once in dark mode, and read as the browser computed them; the static scan wins where it is sure, the rendered values fill the rest |
159
160
  | `design/scan-render-pages.ts` | The pages the rendered scan shows: the project's HTML (and its built output), the files they need, and the custom property names and dark-mode switches the stylesheets name; a bounded walk that follows no link |
160
161
  | `design/scan-render-probe.ts` | The script that reads a rendered page in an isolated world: only values the author's styles set (it reads the page again with all styles off), as bounded plain data |
161
- | `design/lint.ts` | `checkDesign` and `checkPage`: the page checks of `design_preview`, the Check tab, and the CLI; `lint-page.ts` and `lint-page-*.ts` (the script the page runs, in an isolated world: setup, the author's CSS index, values, elements, states, focus, and page checks), `lint-color.ts` (token sets and OKLab distance); `analyze` calls its phases in `lint-analyze-system.ts` (color, font, size), `lint-analyze-contrast.ts`, `lint-analyze-page.ts`, and `lint-analyze-util.ts` |
162
+ | `design/lint.ts` | `checkDesign` and `checkPage`: the page checks of `design_preview` and the Check tab; `lint-page.ts` and `lint-page-*.ts` (the script the page runs, in an isolated world: setup, the author's CSS index, values, elements, states, focus, and page checks), `lint-color.ts` (token sets and OKLab distance); `analyze` calls its phases in `lint-analyze-system.ts` (color, font, size), `lint-analyze-contrast.ts`, `lint-analyze-page.ts`, and `lint-analyze-util.ts` |
162
163
  | `design/lint-suggest.ts` | Which token a check suggests for a color: what a token is for, how the page uses the color, and the order of preference |
163
164
  | `design/fix.ts` | `applyExactFixes`: one-tap fixes; a literal that equals a token exactly becomes `var(--token)`, only in `<style>` and `style=""`, only where the place is certain |
164
165
  | `design/docsite.ts` | `renderSystemDoc`: the documentation page of a system; `docsite-core.ts` (the context, counts, and the nonce CSP), one file for each group of sections (`docsite-color-section.ts`, `docsite-type.ts`, `docsite-space.ts`, `docsite-components.ts`, `docsite-reference.ts`), `docsite-sanitize.ts` (the allowlist sanitizer and CSS parser for component specimens, drawn in shadow roots), `docsite-css.ts` and `docsite-js.ts` (the page's one sheet and one script), `docsite-markdown.ts` |
165
- | `design/guide.ts` | The prompt section: a page skeleton, craft rules, and the design system's summary as fenced, untrusted data |
166
+ | `design/guide.ts` | The prompt section: a pointer to `guides/design.md`, and the design system's summary as fenced, untrusted data |
166
167
 
167
168
  ### Elsewhere
168
169
 
169
170
  | File | Owns |
170
171
  | ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
171
172
  | `providers.ts`, `net.ts` | Provider sign-ins, and those that need signing in again (a subscription its provider will not renew); HTTP settings for provider streams |
173
+ | `guides/*.md` | Pages that the prompt points Pi to, to read only when a task needs them (`artifact-bridge.md`, `design.md`), so that the prompt stays short |
172
174
  | `public-fetch.ts` | `host.fetchPublic`: fetch that reaches only public addresses, checked where each connection is made and at each redirect |
173
175
  | `gallery.ts` | The extension gallery (`app.gallery`, `host.gallery`): its index read and kept in the data folder's `gallery/`, downloads checked against their pinned SHA-256, installs (off), updates with a diff, removal, the `<name>.gallery.json` provenance beside each, revoked versions, and Share's draft entries |
174
176
  | `gallery/entry.ts` | The index's format, read strictly: entries, file names in the drop-in folder's rules, limits, compatibility, addresses. The index repository's checks import it too |
@@ -186,7 +188,7 @@ Outside `src/`: `flake.nix` and `nix/` build Pi Pocket with Nix (`nix/package.ni
186
188
 
187
189
  ## Extensions: `src/server/extensions/`
188
190
 
189
- Each default-exports `(host: PocketHost, web: ExtensionWeb) => Extension | Extension[] | void` (`web` adds to the app: [extensions/app.md](extensions/app.md)) and is installed in this order: `prompt` (system prompt, with where Pi Pocket's docs are), `artifacts` (the `artifact` and `artifact_inline` tools: one store, `publish`, and bundles: `assets`, `removeAssets`, `group`, `kind`), `browser` (browser tool and its prompt section; through `host.browsers`), `subagents` (subagent tool and its tasks: anchors, reporters, and the courier that sends waiting reports to the parent together; a subagent runs on its session's model, or one the owner allowed, and the app rebuilds the module when that list changes), `agent-teams` (Agent Teams, off by default: the `team` tool and its prompt section, through `host.linkedSessions`; its browser module `agent-teams.js` describes the tool's calls with `pocket.toolCall`; it imports of Pi Pocket's only types and `model-facts.ts`, a pure helper that formats model facts), `schedules` (schedule tool and its four limits, as settings; installs the schedule task), `background` (the background tool and its one setting, through `host.background`; installs the watch task), `goals` (hook after each answer), `plan` (tool hook and prompt section), `anthropic-subscription` (Claude subscription billing), `guard` (tool hook that asks for approval), `codemode` (codemode tool; a script's calls go through the same hooks), `memory` (memory tool and the prompt section of lessons in force; through `host.memory`), `pip` (PiP's tools, prompt, and follow task, through `host.pip`; only PiP's conversation selects it, as `PocketApp`'s settings leave it out of every other conversation's), `triggers` (the PR and repository watch tasks and the `watch_pr` tool, through `host.watches` and `host.repoWatches`; webhooks need it on), `gallery` (the extension gallery's owner-only routes under `/api/x/gallery/`, through `host.gallery`, and its twice-daily look for revoked versions; it installs `pocket-gallery`, which tells the web app it is on), `session-tags` (Session tags, off by default: its `x.session-tags.tags` document, routes that check ids with `request.sessions()`, and its browser folder `session-tags/`, which uses the session list's extension points; it imports nothing of Pi Pocket's but types, as a drop-in would), `ask` (Ask: Pi's `ask` tool and its prompt section, questions with answers to pick on a card through `host.ask`; subagents do not get it, and plan mode lets it run), `ask-someone` (Ask someone, off by default: the `ask_someone` tool, which saves a draft question in its `x.ask-someone.questions` document; routes to edit, share, and end them; a public page (`web.publicPage`) for one answer through each link; and its browser folder `ask-someone/`; it imports nothing of Pi Pocket's but types), `updates` (Updates of Pi Pocket itself: owner-only routes under `/api/x/updates/`, through `host.updates`, its three settings (look, install by itself, beta updates), the look every 6 hours and the install by itself, and its browser folder `updates/`, the menu row, launcher action, and sheet, which says in words how the copy was installed and shows the hints that the server gives for a local or npx install), and `design` (Design mode's workspace: its routes under `/api/x/design/` for comments, tweaks, "go back to this one", and the designs list, the `pocket.design-comments` document, the `/design-open` command, and the agent side from `../design/index.ts` (tools, prompt guide, export route); its browser folder `design/` is the canvas: only `index.js` (the store, the rail button, the launcher actions, the command, and a loading state), `paths.js`, and `state.js` (the workspace's one store) load at app start; `app.js` (the workspace, with `style.css`) loads when the panel first opens, and `docks.js`, `views.js`, and the System view (`system-ui.js`, with `system.css`) when first used; `unsaved.js` carries the System view's unsaved count and save; `workspace.js` is the picker, toolbar, and modes, `canvas.js` the frame and its bridge, `docks.js` the versions, comments, text edits, and tweaks, `system-view.js`, `system-sections.js`, `system-widgets.js`, `system-actions.js`, `system-data.js`, and `system-preview.js` the System view, `check.js` the Check tab, `picker.js` the design picker, `views.js` compare, the variations grid, the slide strip, and present mode, `data.js` what it asks of the server, `parts.js` small pieces, `style.css` the workspace's sheet, and `system.css` the System view's; `devices.js`, `tweaks.js`, `edits.js`, `messages.js`, `comments.js`, `system.js`, `color.js`, and `specimen.js` are pure helpers (`color.js`, with `color.d.ts`, is also the server's color math, through `../design/color.ts`); `system-routes.ts` and `system-api.ts` are the System view's routes (`system`, `system/check`, `system/docs`, `system/export`) and the engines they call; it imports the app's own `/store.js` and `/artifact-bridge.js`).
191
+ Each default-exports `(host: PocketHost, web: ExtensionWeb) => Extension | Extension[] | void` (`web` adds to the app: [extensions/app.md](extensions/app.md)) and is installed in this order: `prompt` (system prompt, with where Pi Pocket's docs are), `artifacts` (the `artifact` and `artifact_inline` tools: one store, `publish`, and bundles: `assets`, `removeAssets`, `group`, `kind`), `browser` (browser tool and its prompt section; through `host.browsers`), `subagents` (subagent tool and its tasks: anchors, reporters, and the courier that sends waiting reports to the parent together; a subagent runs on its session's model, or one the owner allowed, and the app rebuilds the module when that list changes), `agent-teams` (Agent Teams, off by default: the `team` tool and its prompt section, through `host.linkedSessions`; its browser module `agent-teams.js` describes the tool's calls with `pocket.toolCall`; it imports of Pi Pocket's only types and `model-facts.ts`, a pure helper that formats model facts), `schedules` (schedule tool and its four limits, as settings; installs the schedule task), `background` (the background tool and its one setting, through `host.background`; installs the watch task), `goals` (hook after each answer), `plan` (tool hook and prompt section), `anthropic-subscription` (Claude subscription billing), `guard` (tool hook that asks for approval), `codemode` (codemode tool; a script's calls go through the same hooks), `memory` (memory tool and the prompt section of lessons in force; through `host.memory`), `pip` (PiP's tools, prompt, and follow task, through `host.pip`; only PiP's conversation selects it, as `PocketApp`'s settings leave it out of every other conversation's), `triggers` (the PR and repository watch tasks and the `watch_pr` tool, through `host.watches` and `host.repoWatches`; webhooks need it on), `gallery` (the extension gallery's owner-only routes under `/api/x/gallery/`, through `host.gallery`, and its twice-daily look for revoked versions; it installs `pocket-gallery`, which tells the web app it is on), `session-tags` (Session tags, off by default: its `x.session-tags.tags` document, routes that check ids with `request.sessions()`, and its browser folder `session-tags/`, which uses the session list's extension points; it imports nothing of Pi Pocket's but types, as a drop-in would), `ask` (Ask: Pi's `ask` tool and its prompt section, questions with answers to pick on a card through `host.ask`; subagents do not get it, and plan mode lets it run), `ask-someone` (Ask someone, off by default: the `ask_someone` tool, which saves a draft question in its `x.ask-someone.questions` document; routes to edit, share, and end them; a public page (`web.publicPage`) for one answer through each link; and its browser folder `ask-someone/`; it imports nothing of Pi Pocket's but types), `updates` (Updates of Pi Pocket itself: owner-only routes under `/api/x/updates/`, through `host.updates`, its three settings (look, install by itself, beta updates), the look every 6 hours and the install by itself, and its browser folder `updates/`, the menu row, launcher action, and sheet, which says in words how the copy was installed and shows the hints that the server gives for a local or npx install), `design` (Design mode's workspace: its routes under `/api/x/design/` for comments, tweaks, "go back to this one", and the designs list, the `pocket.design-comments` document, the `/design-open` command, and the agent side from `../design/index.ts` (tools, prompt guide, export route); its browser folder `design/` is the canvas: only `index.js` (the store, the rail button, the launcher actions, the command, and a loading state), `paths.js`, and `state.js` (the workspace's one store) load at app start; `app.js` (the workspace, with `style.css`) loads when the panel first opens, and `docks.js`, `views.js`, and the System view (`system-ui.js`, with `system.css`) when first used; `unsaved.js` carries the System view's unsaved count and save; `workspace.js` is the picker, toolbar, and modes, `canvas.js` the frame and its bridge, `docks.js` the versions, comments, text edits, and tweaks, `system-view.js`, `system-sections.js`, `system-widgets.js`, `system-actions.js`, `system-data.js`, and `system-preview.js` the System view, `check.js` the Check tab, `picker.js` the design picker, `views.js` compare, the variations grid, the slide strip, and present mode, `data.js` what it asks of the server, `parts.js` small pieces, `style.css` the workspace's sheet, and `system.css` the System view's; `devices.js`, `tweaks.js`, `edits.js`, `messages.js`, `comments.js`, `system.js`, `color.js`, and `specimen.js` are pure helpers (`color.js`, with `color.d.ts`, is also the server's color math, through `../design/color.ts`); `system-routes.ts` and `system-api.ts` are the System view's routes (`system`, `system/check`, `system/docs`, `system/export`) and the engines they call; it imports the app's own `/store.js` and `/artifact-bridge.js`), and `tool-search` (the `tool_search` tool, and the list of tools that wait to be searched for: `browser`, `background`, `schedule`, `watch_pr`, `ask_someone`, and the design tools; it marks them deferred with `wrapTool`, and shows their prompt sections only once one of their tools is loaded, with `wrapSection` (the design guide's section with any of the three design tools); on a model whose provider takes tool changes in the messages it loads a tool into the list, and on any other it gives the tool's description in the search result and Pi calls it from a codemode script, so the list, and the prompt cache that starts with it, never change; turn it off and they are offered every time).
190
192
 
191
193
  ## Web: `web/` (Preact and htm, no build)
192
194
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-pocket",
3
- "version": "0.27.0-beta.8",
3
+ "version": "0.27.0",
4
4
  "description": "A durable, multiplayer, mobile-first web app for Pi agents, built on Pi Durable",
5
5
  "keywords": [
6
6
  "pi",
@@ -208,7 +208,6 @@ export function colorSection(ctx: Ctx): string | undefined {
208
208
  `<h3 id="color-roles">Roles</h3><p class="sub">Roles say what a color is for. Use a role, never a palette step, so the color follows the mode.</p>${capNote(roles.length, allRoles.length)}`,
209
209
  );
210
210
 
211
- // Groups of one or two cards would leave rows half empty: they share one grid.
212
211
  const groups = grouped(roles);
213
212
  const small = groups.filter(([, list]) => list.length <= 2);
214
213
  const shown: [string, ResolvedToken[]][] = [
@@ -15,7 +15,6 @@ import type { ComponentSpec } from "./system-types.ts";
15
15
  export const snippet = (id: string, text: string, label: string, kind = "") =>
16
16
  `<div class="snip"${kind === "" ? "" : ` data-kind="${kind}" data-panel="${esc(label)}"`}><div class="snip-head"><span>${esc(label)}</span><button class="mini" type="button" data-copy-from="${esc(id)}">Copy</button></div><pre id="${esc(id)}"><code>${esc(text)}</code></pre></div>`;
17
17
 
18
- // The page's script draws each state from the listings below, sanitized, in a shadow root (see docsite-js.ts).
19
18
  function stage(ctx: Ctx): string {
20
19
  const ground = groundToken(ctx);
21
20
  const text = textToken(ctx);
@@ -92,7 +92,6 @@ export function stackOf(value: unknown): string | undefined {
92
92
  export const valueIn = (token: ResolvedToken, mode: string): ModeValue | undefined =>
93
93
  token.modes[mode];
94
94
 
95
- /** A color as CSS text: the engine's own form when it gave one, else the value itself. */
96
95
  function colorText(value: unknown): string | undefined {
97
96
  if (typeof value === "string") {
98
97
  return value;
@@ -242,7 +241,6 @@ export interface Ctx {
242
241
 
243
242
  export const nameOfRef = (text: string) => text.replace(/^\{|\}$/g, "").trim();
244
243
 
245
- /** Text that is the same in every mode is written once; texts that differ show by the mode in force, in CSS alone. */
246
244
  export function variants(ctx: Ctx, make: (mode: string) => string): string {
247
245
  const texts = ctx.modes.map((mode) => make(mode));
248
246
 
@@ -352,7 +350,6 @@ export const copyName = (token: ResolvedToken) => `<button class="tk">${esc(toke
352
350
  export const descOf = (token: ResolvedToken) =>
353
351
  token.description === undefined ? "" : `<span class="desc">${esc(token.description)}</span>`;
354
352
 
355
- /** Specimens of one section, and whether any list was cut, for one note under it. */
356
353
  export function limiter(ctx: Ctx): {
357
354
  take: (list: ResolvedToken[]) => ResolvedToken[];
358
355
  note: () => string;
@@ -378,18 +375,13 @@ export function limiter(ctx: Ctx): {
378
375
  };
379
376
  }
380
377
 
381
- /** A token as a row: its name and description, its value in each mode, and a sample. */
382
378
  export function rowOf(ctx: Ctx, token: ResolvedToken, sample: string): string {
383
379
  const value = variants(ctx, (mode) => esc(plain(token.type, valueIn(token, mode))));
384
380
 
385
381
  return `<div class="row" data-s><div class="meta">${copyName(token)}${descOf(token)}</div><div class="val">${value}</div><div class="sample">${sample}</div></div>`;
386
382
  }
387
383
 
388
- /**
389
- * The headline (the number in the navigation) is the section's role tokens, the semantic tier; a section with none
390
- * counts its primitives. The palette and a component's own tokens are counted inside the section. The System view
391
- * counts the same way.
392
- */
384
+ /** The System view counts the same way: semantic tokens, else primitives. */
393
385
  export function sectionCount(ctx: Ctx, id: SectionId) {
394
386
  const list = tokensOf(ctx, id);
395
387
  const semantic = list.filter((token) => token.tier === "semantic").length;
@@ -419,7 +411,7 @@ export function countsLine(ctx: Ctx, id: SectionId): string {
419
411
  return count.total === 0 ? "" : `<p class="counts">${parts.join(" · ")}</p>`;
420
412
  }
421
413
 
422
- function modeCell(ctx: Ctx, token: ResolvedToken, mode: string, across: number): string {
414
+ function modeCell(token: ResolvedToken, mode: string, across: number): string {
423
415
  const value = valueIn(token, mode);
424
416
  const hex = token.type === "color" ? hexOf(token, mode) : undefined;
425
417
  const body = `${hex === undefined ? "" : `<i class="chip" style="background:${esc(hex)}"></i>`}${esc(clip(plain(token.type, value), 160))}`;
@@ -429,7 +421,6 @@ function modeCell(ctx: Ctx, token: ResolvedToken, mode: string, across: number):
429
421
  : `<td data-label="${esc(modeLabel(mode))}" class="v">${body}</td>`;
430
422
  }
431
423
 
432
- /** Rows of the token table: a column for each mode, or one cell across them when the value is the same in every mode. */
433
424
  export function tableRows(ctx: Ctx, tokens: ResolvedToken[]): string {
434
425
  return tokens
435
426
  .map((token) => {
@@ -438,8 +429,8 @@ export function tableRows(ctx: Ctx, tokens: ResolvedToken[]): string {
438
429
  );
439
430
  const same = ctx.modes.length > 1 && texts.every((text) => text === texts[0]);
440
431
  const cells = same
441
- ? modeCell(ctx, token, ctx.modes[0]!, ctx.modes.length)
442
- : ctx.modes.map((mode) => modeCell(ctx, token, mode, 1)).join("");
432
+ ? modeCell(token, ctx.modes[0]!, ctx.modes.length)
433
+ : ctx.modes.map((mode) => modeCell(token, mode, 1)).join("");
443
434
  const deprecated =
444
435
  token.deprecated === undefined || token.deprecated === false
445
436
  ? ""
@@ -450,7 +441,6 @@ export function tableRows(ctx: Ctx, tokens: ResolvedToken[]): string {
450
441
  .join("");
451
442
  }
452
443
 
453
- /** The tokens of a section that no specimen drew (most are a component's), so every token is on the page. */
454
444
  export function moreTokens(ctx: Ctx, id: SectionId): string {
455
445
  const left = tokensOf(ctx, id).filter((token) => !ctx.claimed.has(token));
456
446
 
@@ -37,7 +37,6 @@ export function spacingSection(ctx: Ctx): string | undefined {
37
37
  const own = mine.filter((token) => token.tier !== "component" && token.type === "dimension");
38
38
  const space = take(own.filter((token) => SPACE_ROOT.test(rootOf(token))));
39
39
  const sizes = take(own.filter((token) => SIZE_ROOT.test(rootOf(token))));
40
- // The roles that use a step: semantic tokens of the section that are neither the scale nor sizes.
41
40
  const roles = take(
42
41
  own.filter(
43
42
  (token) =>
@@ -111,7 +110,6 @@ export function shadowSection(ctx: Ctx): string | undefined {
111
110
  .join("")}</div>${note()}${moreTokens(ctx, "shadows")}`;
112
111
  }
113
112
 
114
- /** Breakpoints, borders, layers, and what fits no other section: one table. */
115
113
  export function otherSection(ctx: Ctx): string | undefined {
116
114
  const mine = tokensOf(ctx, "other");
117
115
 
@@ -58,7 +58,6 @@ const ACCENTS = [
58
58
  "color.accent",
59
59
  ];
60
60
 
61
- /** The page's own accent: the system's, when it reads at 4.5:1 on the page's ground in that scheme. */
62
61
  function chromeAccent(ctx: Ctx, theme: "light" | "dark"): string {
63
62
  const fallback = theme === "dark" ? "#8fb0ff" : "#3557a5";
64
63
  const page = parseColor(theme === "dark" ? "#0e0f15" : "#fafafc")!;
@@ -75,7 +74,6 @@ function chromeAccent(ctx: Ctx, theme: "light" | "dark"): string {
75
74
 
76
75
  const ICON_MENU = `<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M3 5.5h14M3 10h14M3 14.5h14"/></svg>`;
77
76
 
78
- /** The swatches of the overview: the base roles first, in a fixed order, then any semantic color, up to 12. */
79
77
  const SAMPLER: [string, string[], RegExp][] = [
80
78
  ["background", BASE_GROUNDS, /^color\.(bg|background)\.(base|default|canvas|page)$/],
81
79
  [
@@ -138,7 +136,6 @@ function sampler(ctx: Ctx): string {
138
136
  .join("")}</div>`;
139
137
  }
140
138
 
141
- /** The tokens as custom properties on `body.ds`: the first mode's values, then what each other mode changes. */
142
139
  function tokenVars(ctx: Ctx): string {
143
140
  const first = ctx.modes[0]!;
144
141
  const declare = (mode: string, only: (token: ResolvedToken) => boolean) =>
@@ -168,7 +165,6 @@ function tokenVars(ctx: Ctx): string {
168
165
  return rules.join("\n");
169
166
  }
170
167
 
171
- // An artifact holds 2 MB at most: a system so large that its page would not fit shows fewer rows in the token table.
172
168
  export function renderSystemDoc(system: DesignSystem): SystemDoc {
173
169
  let rows = MAX_TOKENS;
174
170
  let doc = build(system, rows);
@@ -405,7 +405,6 @@ function colorIn(entry: ModeValue) {
405
405
  return css === undefined ? undefined : parseColor(css);
406
406
  }
407
407
 
408
- /** True when the token has one value in every mode of the system: a page that uses it looks the same in each. */
409
408
  export function sameInEveryMode(token: ResolvedToken, modes: string[]): boolean {
410
409
  const [first, ...rest] = modes.map((mode) => token.modes[mode]);
411
410
 
@@ -502,6 +501,112 @@ function families(text: string): string[] {
502
501
  .filter((name) => name !== "");
503
502
  }
504
503
 
504
+ interface Piece {
505
+ text: string;
506
+ start: number;
507
+ end: number;
508
+ color: ReturnType<typeof parseColor> | null | false;
509
+ }
510
+
511
+ const pieces = new WeakMap<Declaration, Piece[]>();
512
+
513
+ function piecesOf(declaration: Declaration): Piece[] {
514
+ let found = pieces.get(declaration);
515
+
516
+ if (found === undefined) {
517
+ found = tokens(declaration.masked).map((token) => ({ ...token, color: false as const }));
518
+ pieces.set(declaration, found);
519
+ }
520
+
521
+ return found;
522
+ }
523
+
524
+ function colorOf(piece: Piece) {
525
+ if (piece.color === false) {
526
+ piece.color = parseColor(piece.text) ?? null;
527
+ }
528
+
529
+ return piece.color ?? undefined;
530
+ }
531
+
532
+ type Color = NonNullable<ReturnType<typeof parseColor>>;
533
+
534
+ const byteOf = (channel: number) => Math.round(channel * 255);
535
+ const colorIndexes = new WeakMap<Declaration[], Map<string, [number, number][]>>();
536
+
537
+ // A color that `sameColor` takes is at most half a byte step away: in this bucket or a next one.
538
+ function colorIndexOf(all: Declaration[]): Map<string, [number, number][]> {
539
+ let index = colorIndexes.get(all);
540
+
541
+ if (index === undefined) {
542
+ const made = new Map<string, [number, number][]>();
543
+
544
+ all.forEach((declaration, at) => {
545
+ piecesOf(declaration).forEach((piece, place) => {
546
+ const color = colorOf(piece);
547
+
548
+ if (color !== undefined) {
549
+ const key = `${byteOf(color.r)},${byteOf(color.g)},${byteOf(color.b)}`;
550
+ const list = made.get(key);
551
+
552
+ if (list === undefined) {
553
+ made.set(key, [[at, place]]);
554
+ } else {
555
+ list.push([at, place]);
556
+ }
557
+ }
558
+ });
559
+ });
560
+ index = made;
561
+ colorIndexes.set(all, index);
562
+ }
563
+
564
+ return index;
565
+ }
566
+
567
+ // The same places, in the same order, as a scan of every declaration of the properties, piece by piece.
568
+ function colorMatches(all: Declaration[], literal: Color, properties: Set<string>): Match[] {
569
+ const index = colorIndexOf(all);
570
+ const keys = new Set<string>();
571
+ const [r, g, b] = [byteOf(literal.r), byteOf(literal.g), byteOf(literal.b)];
572
+
573
+ for (const dr of [-1, 0, 1]) {
574
+ for (const dg of [-1, 0, 1]) {
575
+ for (const db of [-1, 0, 1]) {
576
+ keys.add(`${r + dr},${g + dg},${b + db}`);
577
+ }
578
+ }
579
+ }
580
+
581
+ const found: [number, number][] = [];
582
+
583
+ for (const key of keys) {
584
+ for (const item of index.get(key) ?? []) {
585
+ const declaration = all[item[0]]!;
586
+
587
+ if (
588
+ properties.has(declaration.property) &&
589
+ sameColor(colorOf(piecesOf(declaration)[item[1]]!)!, literal)
590
+ ) {
591
+ found.push(item);
592
+ }
593
+ }
594
+ }
595
+
596
+ return found
597
+ .sort((x, y) => x[0] - y[0] || x[1] - y[1])
598
+ .map(([at, place]) => {
599
+ const declaration = all[at]!;
600
+ const piece = piecesOf(declaration)[place]!;
601
+
602
+ return {
603
+ start: declaration.start + piece.start,
604
+ end: declaration.start + piece.end,
605
+ declaration,
606
+ };
607
+ });
608
+ }
609
+
505
610
  function placesIn(
506
611
  content: string,
507
612
  declaration: Declaration,
@@ -518,18 +623,11 @@ function placesIn(
518
623
  }
519
624
 
520
625
  const found: { start: number; end: number }[] = [];
521
- const literal = fix.kind === "color" ? parseColor(fix.literal) : undefined;
522
626
  const pixels = fix.kind === "length" ? Number.parseFloat(fix.literal) : Number.NaN;
523
627
  let first = true;
524
628
 
525
- for (const token of tokens(declaration.masked)) {
526
- if (fix.kind === "color") {
527
- const color = literal === undefined ? undefined : parseColor(token.text);
528
-
529
- if (color !== undefined && literal !== undefined && sameColor(color, literal)) {
530
- found.push({ start: base + token.start, end: base + token.end });
531
- }
532
- } else if (/^\d*\.?\d+px$/i.test(token.text)) {
629
+ for (const token of piecesOf(declaration)) {
630
+ if (/^\d*\.?\d+px$/i.test(token.text)) {
533
631
  // In the `font` shorthand only the first length is the size; the next, after a slash, is the line height.
534
632
  if (
535
633
  Number.parseFloat(token.text) === pixels &&
@@ -566,6 +664,17 @@ export function applyExactFixes(
566
664
 
567
665
  const scanned = regions(content);
568
666
  const all = scanned.regions.flatMap((region) => declarations(content, region));
667
+ const byProperty = new Map<string, number[]>();
668
+
669
+ all.forEach((declaration, index) => {
670
+ const list = byProperty.get(declaration.property);
671
+
672
+ if (list === undefined) {
673
+ byProperty.set(declaration.property, [index]);
674
+ } else {
675
+ list.push(index);
676
+ }
677
+ });
569
678
  const fixable = findings.filter((finding) => finding.fix !== undefined);
570
679
 
571
680
  for (const finding of findings) {
@@ -588,13 +697,25 @@ export function applyExactFixes(
588
697
  const properties = new Set(fix.properties.map((property) => property.toLowerCase()));
589
698
  const matches: Match[] = [];
590
699
 
591
- for (const declaration of all) {
592
- if (!properties.has(declaration.property)) {
593
- continue;
700
+ if (fix.kind === "color") {
701
+ const literal = parseColor(fix.literal);
702
+
703
+ for (const match of literal === undefined
704
+ ? []
705
+ : colorMatches(all, literal, properties)) {
706
+ matches.push(match);
594
707
  }
708
+ } else {
709
+ const order = [...properties]
710
+ .flatMap((property) => byProperty.get(property) ?? [])
711
+ .sort((a, b) => a - b);
712
+
713
+ for (const index of order) {
714
+ const declaration = all[index]!;
595
715
 
596
- for (const place of placesIn(content, declaration, fix)) {
597
- matches.push({ ...place, declaration });
716
+ for (const place of placesIn(content, declaration, fix)) {
717
+ matches.push({ ...place, declaration });
718
+ }
598
719
  }
599
720
  }
600
721