@niwa-labs/plan 0.0.0-stage → 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Niwa Labs contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # @niwa-labs/plan
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A plugin for revisable plans: items, revisions and the decisions still ahead.
4
+
5
+ A plan is of something a caller names (`of`: a task, a run, a branch). Each revision is one
6
+ `plan.revised { of, basedOn, rev, goal?, items }` record carrying the whole plan, so any revision reads back
7
+ without folding the ones before it. An item is `{ id, text, state, note? }`; its state is `open` (a
8
+ decision still ahead), `planned`, `done` or `dropped`.
9
+
10
+ | Action | Effect | What it does |
11
+ | --- | --- | --- |
12
+ | `plan.set { of, goal?, items, expect? }` | record / niwa | Writes the next revision. Matching items and goal record a `plan.unchanged` receipt and return the observed revision. `expect` refuses the set, equal or not, when the plan is no longer at that revision (`0` for a plan not yet written). A call cut off and made again finds the revision it wrote and returns it, whatever was written after. |
13
+ | `plan.get { of, rev? }` | read / niwa | The latest revision, or the one asked for by the number it carries. |
14
+ | `plan.list { open? }` | read / niwa | Each plan at its latest revision with its count of open items; `open: true` keeps those with a decision ahead. |
15
+
16
+ `plan.set` and `plan.get` name the plan as their `@target`, so a grant can be limited to one plan
17
+ (`plan.set@task-3fa9c2`). The name is one segment: `/`, spaces and other characters a target cannot hold are encoded.
18
+
19
+ A refusal (`unknown-plan`, `unknown-revision`, `stale`) is a `PlanRefusal`, an error the caller catches: its `code` says which. A stale write leaves a `niwa.record.refused` audit entry. A host that is not serving the journal fails each action with `NotSent` instead of showing no plans.
20
+
21
+ What an agent ticks off while it works is not here: that checklist is read through the history of
22
+ its session.
23
+
24
+ Another plugin or a script reads the records through `@niwa-labs/plan/records`, which also holds the query builder
25
+ `planRevised(of, rev?)`: `await wait(planRevised(task.id), { timeout: "1h" })` waits for a revision of that plan, typed.
26
+
27
+ In the cockpit (`./cockpit`) the plans are listed with the ones that wait for a decision first. A plan opens
28
+ with its items, how many are done, and any revision, each shown with what it changed from the one before.
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@niwa-labs/plan",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.ts",
8
+ "./records": "./src/records.ts",
9
+ "./cockpit": "./src/cockpit/index.tsx"
10
+ },
11
+ "dependencies": {
12
+ "@niwa-labs/cockpit-sdk": "*",
13
+ "@niwa-labs/core": "*",
14
+ "@niwa-labs/plugin": "*",
15
+ "@niwa-labs/ui-kit": "*",
16
+ "zod": "^4.6.7"
17
+ },
18
+ "devDependencies": {
19
+ "@niwa-labs/testing": "*",
20
+ "@tanstack/react-query": "^5.108.2",
21
+ "@types/react": "^19.3.0",
22
+ "@types/react-dom": "^19.3.0",
23
+ "react": "^19.3.1",
24
+ "react-dom": "^19.3.1"
25
+ },
26
+ "peerDependencies": {
27
+ "@tanstack/react-query": "^5.108.2",
28
+ "react": "^19.3.1",
29
+ "react-dom": "^19.3.1"
30
+ }
31
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The plan actions as the cockpit calls them: name and the part of each schema the page reads.
3
+ *
4
+ * The module runs in the browser and cannot import the host-side schemas, which reach for Node. A field the host
5
+ * stopped sending fails the page that reads it, which `test/cockpit-actions.test.ts` checks against the real actions.
6
+ */
7
+
8
+ import { z } from "zod";
9
+
10
+ export const ItemState = z.enum(["open", "planned", "done", "dropped"]);
11
+ export type ItemState = z.infer<typeof ItemState>;
12
+
13
+ export const PlanItem = z.object({ id: z.string(), text: z.string(), state: ItemState, note: z.string().optional() });
14
+ export type PlanItem = z.infer<typeof PlanItem>;
15
+
16
+ export const PlanSummary = z.object({
17
+ of: z.string(),
18
+ rev: z.number(),
19
+ goal: z.string().optional(),
20
+ items: z.number(),
21
+ open: z.number(),
22
+ });
23
+ export type PlanSummary = z.infer<typeof PlanSummary>;
24
+
25
+ export const listAction = {
26
+ name: "plan.list",
27
+ input: z.object({ open: z.boolean().optional() }),
28
+ output: z.object({ plans: z.array(PlanSummary) }),
29
+ } as const;
30
+
31
+ export const PlanView = z.object({
32
+ of: z.string(),
33
+ rev: z.number(),
34
+ goal: z.string().optional(),
35
+ items: z.array(PlanItem),
36
+ revisions: z.number(),
37
+ at: z.number(),
38
+ });
39
+ export type PlanView = z.infer<typeof PlanView>;
40
+
41
+ export const getAction = {
42
+ name: "plan.get",
43
+ input: z.object({ of: z.string(), rev: z.number().int().positive().optional() }),
44
+ output: PlanView,
45
+ } as const;
@@ -0,0 +1,19 @@
1
+ /** The cockpit module of the plan plugin: the plans with their items and a look at any revision. */
2
+
3
+ import { definePlugin } from "@niwa-labs/cockpit-sdk";
4
+
5
+ import { PlansPage } from "./page.tsx";
6
+
7
+ export default definePlugin({
8
+ id: "plan",
9
+ setup(ctx) {
10
+ ctx.pages.add({
11
+ path: "/plans",
12
+ title: "Планы",
13
+ commandHeading: true,
14
+ nav: { order: 55 },
15
+ commands: [{ action: "plan.set", label: "Составить план" }],
16
+ component: PlansPage,
17
+ });
18
+ },
19
+ });
@@ -0,0 +1,128 @@
1
+ /** The plans of the host, one at a time with its items, and a look at what any revision changed. */
2
+
3
+ import { PageLink, pathFor, useCall, type PageProps } from "@niwa-labs/cockpit-sdk";
4
+ import { CopyValue, StateRing } from "@niwa-labs/ui-kit";
5
+
6
+ import { getAction, listAction, type PlanSummary, type PlanView } from "./actions.ts";
7
+ import { ITEM_LABEL, ITEM_RING, changeText, changesBetween, plansInOrder, progressOf, revisionOf, type ItemChange } from "./revisions.ts";
8
+
9
+ const REFRESH = { refreshOn: { types: ["plan.revised"] } };
10
+
11
+ function planPath(of: string, rev?: number): string {
12
+ return pathFor("/plans", {}, { of, rev: rev === undefined ? undefined : String(rev) });
13
+ }
14
+
15
+ function PlanRow({ plan, selected }: { plan: PlanSummary; selected: boolean }) {
16
+ return (
17
+ <li data-slot="plan-row" data-selected={selected} className="min-w-0">
18
+ <PageLink to={planPath(plan.of)} className={selected ? "block bg-muted/60 px-3 py-2 hover:underline" : "block px-3 py-2 hover:bg-muted/40 hover:underline"}>
19
+ <span className="block break-words text-sm font-medium">{plan.goal || plan.of}</span>
20
+ <span className="desk-tools text-xs text-muted-foreground">
21
+ <span>Пунктов {plan.items}</span>
22
+ {plan.open > 0 ? <span>Ждут решения {plan.open}</span> : null}
23
+ <span>Версия {plan.rev}</span>
24
+ </span>
25
+ </PageLink>
26
+ </li>
27
+ );
28
+ }
29
+
30
+ function ItemRow({ change }: { change: ItemChange }) {
31
+ const { item } = change;
32
+ return (
33
+ <li data-slot="plan-item" data-change={change.kind} data-state={item.state} className="flex min-w-0 items-start gap-3 py-2">
34
+ <StateRing state={ITEM_RING[item.state]} label={ITEM_LABEL[item.state]} />
35
+ <div className="flex min-w-0 flex-col gap-0.5">
36
+ <span className={change.kind === "removed" ? "text-sm line-through" : "text-sm"}>{item.text}</span>
37
+ <span className="text-xs text-muted-foreground">{ITEM_LABEL[item.state]}</span>
38
+ {item.note === undefined ? null : <span className="text-xs text-muted-foreground">{item.note}</span>}
39
+ {change.kind === "same" ? null : (
40
+ <span className="text-xs text-muted-foreground">
41
+ {change.kind === "changed" ? changeText(change) : change.kind === "added" ? "Добавлен в этой версии" : "Удалён в этой версии"}
42
+ </span>
43
+ )}
44
+ </div>
45
+ </li>
46
+ );
47
+ }
48
+
49
+ function PlanDetail({ of, asked }: { of: string; asked: string | undefined }) {
50
+ const latest = useCall(getAction, { of }, REFRESH);
51
+ const rev = latest.data === undefined ? undefined : (revisionOf(asked, latest.data.revisions) ?? latest.data.rev);
52
+ const shown = useCall(getAction, { of, rev }, { ...REFRESH, enabled: rev !== undefined && rev !== latest.data?.rev });
53
+ const earlier = useCall(getAction, { of, rev: rev === undefined ? undefined : rev - 1 }, { ...REFRESH, enabled: rev !== undefined && rev > 1 });
54
+ if (latest.isPending) return <p className="text-sm text-muted-foreground">Загружаем план…</p>;
55
+ if (latest.isError) return <p role="alert" className="text-sm text-destructive">Не удалось загрузить план. {latest.error.message}</p>;
56
+ const plan: PlanView | undefined = rev === latest.data.rev ? latest.data : shown.data;
57
+ if (plan === undefined && shown.isError) return <p role="alert" className="text-sm text-destructive">Не удалось загрузить версию. {shown.error.message}</p>;
58
+ if (plan === undefined) return <p className="text-sm text-muted-foreground">Загружаем версию…</p>;
59
+ const progress = progressOf(plan.items);
60
+ const changes = plan.rev > 1 && earlier.data !== undefined ? changesBetween(earlier.data.items, plan.items) : plan.items.map((item): ItemChange => ({ kind: "same", item }));
61
+ return (
62
+ <article data-slot="plan-page" className="flex min-w-0 flex-col gap-3">
63
+ <header className="flex min-w-0 flex-col gap-1">
64
+ <h3 className="break-words text-base font-semibold">{plan.goal || "План"}</h3>
65
+ <div className="text-xs"><CopyValue value={plan.of} /></div>
66
+ <p className="text-xs text-muted-foreground">
67
+ Выполнено {progress.done} из {progress.total}
68
+ {progress.counts.open > 0 ? ` · Ждут решения ${String(progress.counts.open)}` : ""}
69
+ {progress.counts.dropped > 0 ? ` · Снято ${String(progress.counts.dropped)}` : ""}
70
+ </p>
71
+ {progress.total > 0 ? (
72
+ <div role="progressbar" aria-label="Ход выполнения плана" aria-valuenow={progress.done} aria-valuemin={0} aria-valuemax={progress.total}
73
+ style={{ height: "0.4rem", width: "min(100%, 16rem)", background: "var(--muted)", borderRadius: "0.25rem", overflow: "hidden" }}>
74
+ <div style={{ height: "100%", width: `${(progress.done / progress.total) * 100}%`, background: "var(--state-done)" }} />
75
+ </div>
76
+ ) : null}
77
+ </header>
78
+ {plan.rev > 1 && earlier.isError ? <p role="alert" className="text-xs text-destructive">Не удалось сравнить с предыдущей версией. {earlier.error.message}</p> : null}
79
+ {changes.length === 0 ? <p className="text-sm text-muted-foreground">В этой версии пока нет пунктов.</p> : <ul data-slot="plan-items" className="divide-y rounded-lg border bg-card px-3 text-card-foreground">
80
+ {changes.map((change) => (
81
+ <ItemRow key={`${change.kind}/${change.item.id}`} change={change} />
82
+ ))}
83
+ </ul>}
84
+ <details data-slot="plan-revisions" className="space-y-1 text-xs">
85
+ <summary className="cursor-pointer font-medium">Версия {plan.rev} из {plan.revisions} · {new Date(plan.at).toLocaleString("ru")}</summary>
86
+ <nav aria-label="Версии плана" className="flex flex-wrap items-center gap-1">
87
+ {Array.from({ length: plan.revisions }, (_, index) => index + 1).map((number) => (
88
+ <PageLink key={number} to={planPath(plan.of, number)} className={number === plan.rev ? "rounded bg-muted px-1.5 py-0.5 font-semibold" : "rounded px-1.5 py-0.5 hover:bg-muted"}>
89
+ {number}
90
+ </PageLink>
91
+ ))}
92
+ </nav>
93
+ </details>
94
+ </article>
95
+ );
96
+ }
97
+
98
+ export function PlansPage({ search }: PageProps<"/plans">) {
99
+ const plans = useCall(listAction, {}, REFRESH);
100
+ const ordered = plansInOrder(plans.data?.plans ?? []);
101
+ const selected = search["of"] ?? ordered[0]?.of;
102
+ const requestedRevision = search["of"] === undefined ? undefined : search["rev"];
103
+ return (
104
+ <div className="desk-page">
105
+ {plans.isPending ? (
106
+ <p className="text-sm text-muted-foreground">Загружаем планы…</p>
107
+ ) : plans.isError ? (
108
+ <p role="alert" className="text-sm text-destructive">Не удалось загрузить планы. {plans.error.message}</p>
109
+ ) : ordered.length === 0 ? (
110
+ <p className="text-sm text-muted-foreground">Планов пока нет. Составьте план, чтобы отслеживать его выполнение.</p>
111
+ ) : (
112
+ <div className="flex min-w-0 flex-wrap gap-4">
113
+ <nav aria-label="Список планов" className="min-w-0" style={{ flex: "1 1 12rem" }}>
114
+ <ul data-slot="plans" className="divide-y overflow-hidden rounded-lg border bg-card">
115
+ {ordered.map((plan) => <PlanRow key={plan.of} plan={plan} selected={plan.of === selected} />)}
116
+ </ul>
117
+ </nav>
118
+ {selected === undefined ? null : (
119
+ <div className="min-w-0" style={{ flex: "3 1 24rem" }}>
120
+ <PlanDetail key={selected} of={selected} asked={requestedRevision} />
121
+ </div>
122
+ )}
123
+ </div>
124
+ )}
125
+ {ordered.length === 0 && search["of"] !== undefined ? <PlanDetail key={search["of"]} of={search["of"]} asked={requestedRevision} /> : null}
126
+ </div>
127
+ );
128
+ }
@@ -0,0 +1,72 @@
1
+ /** What the plan page makes of a plan: how far it has come, what a revision changed, and which revision is shown. */
2
+
3
+ import type { WorkState } from "@niwa-labs/ui-kit";
4
+
5
+ import type { ItemState, PlanItem, PlanSummary } from "./actions.ts";
6
+
7
+ /** The ring an item is drawn with: a decision still ahead is a wait for somebody. */
8
+ export const ITEM_RING: Readonly<Record<ItemState, WorkState>> = {
9
+ open: "waiting",
10
+ planned: "pending",
11
+ done: "done",
12
+ dropped: "skipped",
13
+ };
14
+
15
+ export const ITEM_LABEL: Readonly<Record<ItemState, string>> = {
16
+ open: "Ждёт решения",
17
+ planned: "Запланирован",
18
+ done: "Выполнен",
19
+ dropped: "Снят",
20
+ };
21
+
22
+ /** How many items stand in each state, and how many of the work that is still to be done are done. */
23
+ export function progressOf(items: readonly PlanItem[]): { counts: Record<ItemState, number>; done: number; total: number } {
24
+ const counts: Record<ItemState, number> = { open: 0, planned: 0, done: 0, dropped: 0 };
25
+ for (const item of items) counts[item.state] += 1;
26
+ // Dropped work is no longer owed: it is neither done nor still to do.
27
+ return { counts, done: counts.done, total: items.length - counts.dropped };
28
+ }
29
+
30
+ /** The plans in the order of the page: those with a decision ahead first, then the others by name. */
31
+ export function plansInOrder(plans: readonly PlanSummary[]): PlanSummary[] {
32
+ return [...plans].sort((a, b) => Number(b.open > 0) - Number(a.open > 0) || a.of.localeCompare(b.of));
33
+ }
34
+
35
+ export type ItemChange =
36
+ | { kind: "added"; item: PlanItem }
37
+ | { kind: "removed"; item: PlanItem }
38
+ | { kind: "changed"; item: PlanItem; before: PlanItem }
39
+ | { kind: "same"; item: PlanItem };
40
+
41
+ /**
42
+ * What a revision did to the items of the one before it, in the order of the revision, then the items it removed.
43
+ * An item that kept its text, state and note but moved is the same: the order is the plan's own and shows as it is.
44
+ */
45
+ export function changesBetween(before: readonly PlanItem[], after: readonly PlanItem[]): ItemChange[] {
46
+ const earlier = new Map(before.map((item) => [item.id, item]));
47
+ const kept = new Set<string>();
48
+ const changes: ItemChange[] = after.map((item): ItemChange => {
49
+ const was = earlier.get(item.id);
50
+ if (was === undefined) return { kind: "added", item };
51
+ kept.add(item.id);
52
+ return was.text === item.text && was.state === item.state && was.note === item.note ? { kind: "same", item } : { kind: "changed", item, before: was };
53
+ });
54
+ for (const item of before) if (!kept.has(item.id)) changes.push({ kind: "removed", item });
55
+ return changes;
56
+ }
57
+
58
+ /** What changed about an item, in a few words: its state or its words. */
59
+ export function changeText(change: Extract<ItemChange, { kind: "changed" }>): string {
60
+ const parts: string[] = [];
61
+ if (change.before.state !== change.item.state) parts.push(`${ITEM_LABEL[change.before.state]} → ${ITEM_LABEL[change.item.state]}`);
62
+ if (change.before.text !== change.item.text) parts.push("Текст обновлён");
63
+ if (change.before.note !== change.item.note) parts.push(change.item.note === undefined ? "Заметка удалена" : "Заметка обновлена");
64
+ return parts.join(", ");
65
+ }
66
+
67
+ /** The revision a page address asks for: a whole number from 1 up to the latest, or none for the latest. */
68
+ export function revisionOf(asked: string | undefined, revisions: number): number | undefined {
69
+ if (asked === undefined || !/^[1-9][0-9]*$/.test(asked)) return undefined;
70
+ const rev = Number(asked);
71
+ return rev <= revisions ? rev : undefined;
72
+ }
package/src/index.ts ADDED
@@ -0,0 +1,179 @@
1
+ /**
2
+ * The plan plugin: revisable plans, read back at any revision.
3
+ *
4
+ * - **plan.set** writes the next revision of the plan of something: a goal and the whole list of
5
+ * items. A set that changes nothing records which revision it returned.
6
+ * - **plan.get** reads a plan at its latest revision, or at one asked for.
7
+ * - **plan.list** lists the plans, and the ones with a decision still ahead.
8
+ *
9
+ * What an agent ticks off while it works is not here: that checklist is read from the history of
10
+ * its session.
11
+ *
12
+ * A plan is folded from `plan.revised` records on every read; the records are the only state.
13
+ */
14
+
15
+ import { fileURLToPath } from "node:url";
16
+
17
+ import { CatchableError, NotSent, RecordRefused, action, recordId, resolveQuery, stableJson } from "@niwa-labs/core";
18
+ import type { JournalReader } from "@niwa-labs/core";
19
+ import { COCKPIT_MODULE, plugin } from "@niwa-labs/plugin";
20
+ import type { Plugin } from "@niwa-labs/plugin";
21
+
22
+ import { PLAN_TYPES, PlanRevised, PlanUnchanged, planGet, planList, planSet } from "./records.ts";
23
+ import type { PlanRevisedData, PlanSummary, PlanView } from "./records.ts";
24
+
25
+ export * from "./records.ts";
26
+
27
+ /** Why a plan, or a revision of it, was refused. */
28
+ export type PlanRefusalCode = "unknown-plan" | "unknown-revision" | "stale";
29
+
30
+ /**
31
+ * A plan, or a revision of it, that cannot be had: the caller asked for what is not there, or for a
32
+ * change on a revision that is no longer the latest. It is the caller's to catch, and `code` says
33
+ * which; nothing was written.
34
+ */
35
+ export class PlanRefusal extends CatchableError {
36
+ override name = "PlanRefusal";
37
+ override readonly code: PlanRefusalCode;
38
+ readonly effectPossible = false;
39
+ constructor(code: PlanRefusalCode, message: string) {
40
+ super(message);
41
+ this.code = code;
42
+ }
43
+ }
44
+
45
+ interface Revision {
46
+ readonly data: PlanRevisedData;
47
+ readonly at: number;
48
+ }
49
+
50
+ /**
51
+ * The revisions of one plan, by the number they carry, lowest first. A number written twice is the
52
+ * one written first: a later record of the same number is never read.
53
+ */
54
+ function revisionsOf(rows: readonly { readonly data: unknown; readonly at: number }[]): Revision[] {
55
+ const byNumber = new Map<number, Revision>();
56
+ for (const row of rows) {
57
+ const data = row.data as PlanRevisedData;
58
+ if (!byNumber.has(data.rev)) byNumber.set(data.rev, { data, at: row.at });
59
+ }
60
+ return [...byNumber.values()].sort((a, b) => a.data.rev - b.data.rev);
61
+ }
62
+
63
+ /** What a set holds, as one text: equal text is the same revision. */
64
+ function contentOf(data: Pick<PlanRevisedData, "goal" | "items">): string {
65
+ return stableJson({ goal: data.goal ?? null, items: data.items });
66
+ }
67
+
68
+ function viewOf(list: readonly Revision[], revision: number): PlanView {
69
+ const found = list.find((one) => one.data.rev === revision);
70
+ if (found === undefined) throw new PlanRefusal("unknown-revision", `the plan has no revision ${revision}`);
71
+ const { of, rev, goal, items } = found.data;
72
+ return { of, rev, ...(goal === undefined ? {} : { goal }), items, revisions: list.length, at: found.at };
73
+ }
74
+
75
+ /** The plan plugin. */
76
+ export function plan(): Plugin {
77
+ return plugin("plan", (api) => {
78
+ api.declare(...PLAN_TYPES);
79
+ // The page of this plugin in the cockpit: a client module, offered by the path of its source.
80
+ api.offer(COCKPIT_MODULE, { id: "plan", entry: fileURLToPath(new URL("./cockpit/index.tsx", import.meta.url)) });
81
+
82
+ // The plans are read from the journal: with none to read there is no history, and that is said,
83
+ // not shown as a history with nothing in it.
84
+ const journal = (): JournalReader => {
85
+ const reader = api.journal?.();
86
+ if (reader === undefined) throw new NotSent("the plans are read from the journal, and the host is not serving it");
87
+ return reader;
88
+ };
89
+
90
+ /** The revisions of one plan. */
91
+ const historyOf = (of: string): Revision[] =>
92
+ revisionsOf(journal().query(resolveQuery({ types: [PlanRevised], filter: { of } })));
93
+
94
+ api.action(
95
+ action(planSet, {
96
+ // A call cut off before its outcome was known is made again under the same operation: it
97
+ // finds its recorded revision or its receipt for an unchanged plan.
98
+ recovery: "repeat",
99
+ effect: "record",
100
+ world: "niwa",
101
+ idempotent: true,
102
+ run: async (input, ctx) => {
103
+ // The revision this very operation wrote is the answer, whatever came after it.
104
+ const born = journal().get(recordId(`${ctx.operationId}/emit/1`));
105
+ if (born !== undefined && born.type === PlanRevised.name) {
106
+ const written = born.data as PlanRevisedData;
107
+ if (written.of === input.of) return { of: written.of, rev: written.rev, revised: true };
108
+ }
109
+ if (born?.type === PlanUnchanged.name) {
110
+ const { of, basedOn } = PlanUnchanged.schema.parse(born.data);
111
+ return { of, rev: basedOn, revised: false };
112
+ }
113
+ const head = historyOf(input.of).at(-1);
114
+ const rev = head?.data.rev ?? 0;
115
+ const basedOn = input.expect ?? rev;
116
+ try {
117
+ if (basedOn === rev && head && contentOf(head.data) === contentOf(input)) {
118
+ await ctx.emit(PlanUnchanged, { of: input.of, basedOn });
119
+ return { of: input.of, rev, revised: false };
120
+ }
121
+ await ctx.emit(PlanRevised, {
122
+ of: input.of, basedOn, rev: basedOn + 1,
123
+ ...(input.goal === undefined ? {} : { goal: input.goal }),
124
+ items: input.items,
125
+ });
126
+ return { of: input.of, rev: basedOn + 1, revised: true };
127
+ } catch (error) {
128
+ if (error instanceof RecordRefused && error.code === "stale") throw new PlanRefusal("stale", error.reason);
129
+ throw error;
130
+ }
131
+ },
132
+ }),
133
+ );
134
+
135
+ api.action(
136
+ action(planGet, {
137
+ recovery: "repeat",
138
+ effect: "read",
139
+ world: "niwa",
140
+ run: (input) => {
141
+ const list = historyOf(input.of);
142
+ const head = list.at(-1);
143
+ if (head === undefined) throw new PlanRefusal("unknown-plan", `there is no plan of "${input.of}"`);
144
+ return viewOf(list, input.rev ?? head.data.rev);
145
+ },
146
+ }),
147
+ );
148
+
149
+ api.action(
150
+ action(planList, {
151
+ recovery: "repeat",
152
+ effect: "read",
153
+ world: "niwa",
154
+ run: (input) => {
155
+ // Only the latest revision of each plan is kept while reading: the older ones are dropped.
156
+ const heads = new Map<string, PlanRevisedData>();
157
+ for (const row of journal().query(resolveQuery({ types: [PlanRevised] }))) {
158
+ const data = row.data as PlanRevisedData;
159
+ const kept = heads.get(data.of);
160
+ if (kept === undefined || data.rev > kept.rev) heads.set(data.of, data);
161
+ }
162
+ const plans: PlanSummary[] = [];
163
+ for (const head of heads.values()) {
164
+ const open = head.items.filter((item) => item.state === "open").length;
165
+ if (input.open === true && open === 0) continue;
166
+ plans.push({
167
+ of: head.of,
168
+ rev: head.rev,
169
+ ...(head.goal === undefined ? {} : { goal: head.goal }),
170
+ items: head.items.length,
171
+ open,
172
+ });
173
+ }
174
+ return { plans };
175
+ },
176
+ }),
177
+ );
178
+ });
179
+ }
package/src/records.ts ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * The records of the plan plugin, and the typed references of its actions.
3
+ *
4
+ * A plan is what is to be done about something and in which order. Each revision is written whole,
5
+ * so a plan is read at any revision without folding the ones before it.
6
+ */
7
+
8
+ import { z } from "zod";
9
+
10
+ import { actionRef, queryOf, record } from "@niwa-labs/core";
11
+ import type { TypeQuery } from "@niwa-labs/core";
12
+
13
+ /**
14
+ * Where an item stands. `open` is a decision still ahead: the plan cannot go on past it until
15
+ * somebody decides. The others say what became of work that is already decided.
16
+ */
17
+ export const ItemState = z.enum(["open", "planned", "done", "dropped"]);
18
+ export type ItemState = z.infer<typeof ItemState>;
19
+
20
+ /** One step of a plan. */
21
+ export const PlanItem = z.object({
22
+ /** Names the item across revisions; unique inside one plan. */
23
+ id: z.string().trim().min(1),
24
+ /** What is to be done, or what is to be decided. */
25
+ text: z.string().trim().min(1),
26
+ state: ItemState,
27
+ /** Why it stands where it does: the decision taken, the reason it was dropped. */
28
+ note: z.string().trim().min(1).optional(),
29
+ });
30
+ export type PlanItem = z.infer<typeof PlanItem>;
31
+
32
+ /** The items of a plan: one list, in the order the work goes in, with no id twice. */
33
+ export const PlanItems = z.array(PlanItem).superRefine((items, ctx) => {
34
+ const seen = new Set<string>();
35
+ for (const [index, item] of items.entries()) {
36
+ if (seen.has(item.id)) ctx.addIssue({ code: "custom", message: `the item id "${item.id}" is used twice`, path: [index, "id"] });
37
+ seen.add(item.id);
38
+ }
39
+ });
40
+
41
+ /**
42
+ * What a plan is of: a task, a run, a branch, anything the writer names.
43
+ *
44
+ * The text is trimmed and must be well-formed Unicode, so the subject an action works with and the
45
+ * one a grant names (`planTarget`) are the same text, and encoding it cannot fail.
46
+ */
47
+ export const PlanSubject = z
48
+ .string()
49
+ .trim()
50
+ .min(1)
51
+ .refine((text) => text.isWellFormed(), { message: "a plan is of text with no unpaired UTF-16 surrogate" });
52
+
53
+ const planGuard = {
54
+ group: "plan", key: (data: { of: string }) => data.of,
55
+ initial: () => 0,
56
+ };
57
+
58
+ function stale(revision: number, data: { of: string; basedOn: number }) {
59
+ return { code: "stale", reason: `the plan of "${data.of}" is at revision ${revision}, not ${data.basedOn}: read it again before revising` };
60
+ }
61
+
62
+ /** A set observed identical contents at this revision. Replay returns that same result. */
63
+ export const PlanUnchanged = record("plan.unchanged", z.object({
64
+ of: PlanSubject, basedOn: z.number().int().positive(),
65
+ }), { guard: {
66
+ ...planGuard,
67
+ admit: (revision, data) => revision === data.basedOn ? undefined : stale(revision, data),
68
+ fold: revision => revision,
69
+ } });
70
+
71
+ /** A revision of a plan was written: the whole plan as it stands from `rev` on. */
72
+ export const PlanRevised = record(
73
+ "plan.revised",
74
+ z.object({
75
+ /** What the plan is of. */
76
+ of: PlanSubject,
77
+ basedOn: z.number().int().nonnegative(),
78
+ /** The number of the revision, from 1, one more than the revision before it. */
79
+ rev: z.number().int().positive(),
80
+ /** What the plan is for, when it says. */
81
+ goal: z.string().trim().min(1).optional(),
82
+ items: PlanItems,
83
+ }),
84
+ { guard: {
85
+ ...planGuard,
86
+ admit: (revision, data) => data.basedOn === revision && data.rev === revision + 1
87
+ ? undefined : stale(revision, data),
88
+ fold: (_revision, data) => data.rev,
89
+ } },
90
+ );
91
+ export type PlanRevisedData = z.infer<typeof PlanRevised.schema>;
92
+
93
+ /**
94
+ * The revisions of the plan of one subject, as a script waits for or reads them with their data
95
+ * typed: `await wait(planRevised(task.id), { timeout: "1h" })`. With `rev`, only that revision.
96
+ */
97
+ export function planRevised(of: string, rev?: number): TypeQuery<PlanRevisedData> {
98
+ return queryOf(PlanRevised, { of: PlanSubject.parse(of), ...(rev === undefined ? {} : { rev: z.number().int().positive().parse(rev) }) });
99
+ }
100
+
101
+ /** The record types the plan plugin declares. */
102
+ export const PLAN_TYPES = [PlanRevised, PlanUnchanged] as const;
103
+
104
+ /** A plan at one revision, as `plan.get` shows it. */
105
+ export const PlanView = z.object({
106
+ of: PlanSubject,
107
+ rev: z.number().int().positive(),
108
+ goal: z.string().optional(),
109
+ items: PlanItems,
110
+ /** How many revisions the plan has had, the latest included. */
111
+ revisions: z.number().int().positive(),
112
+ /** When this revision was written, in milliseconds since the epoch. */
113
+ at: z.number().int().nonnegative(),
114
+ });
115
+ export type PlanView = z.infer<typeof PlanView>;
116
+
117
+ /** What `plan.list` shows of each plan: where it stands, not its items. */
118
+ export const PlanSummary = z.object({
119
+ of: PlanSubject,
120
+ rev: z.number().int().positive(),
121
+ goal: z.string().optional(),
122
+ /** How many items the latest revision has, and how many of them are decisions still ahead. */
123
+ items: z.number().int().nonnegative(),
124
+ open: z.number().int().nonnegative(),
125
+ });
126
+ export type PlanSummary = z.infer<typeof PlanSummary>;
127
+
128
+ /**
129
+ * What a grant's `@target` names a plan by: one segment, so any text a plan is of stays one place.
130
+ *
131
+ * The subject is read as the actions read it, so a grant built here matches the call it is for.
132
+ */
133
+ export function planTarget(of: string): string {
134
+ return encodeURIComponent(PlanSubject.parse(of)).replace(/\*/g, "%2A");
135
+ }
136
+
137
+ export const planSet = actionRef("plan.set", {
138
+ description:
139
+ "Write a revision of the plan of `of`: its goal and the whole list of items, each with a state (`open` is a decision still ahead). " +
140
+ "The revision is numbered by the plan, one after the last. Items equal to the latest revision return it without creating a revision. " +
141
+ "Give `expect` the revision you based the change on to refuse it when someone revised the plan since.",
142
+ input: z.object({
143
+ of: PlanSubject,
144
+ goal: z.string().trim().min(1).optional(),
145
+ items: PlanItems,
146
+ expect: z.number().int().nonnegative().optional(),
147
+ }),
148
+ output: z.object({ of: PlanSubject, rev: z.number().int().positive(), revised: z.boolean() }),
149
+ target: (input) => planTarget(input.of),
150
+ });
151
+
152
+ export const planGet = actionRef("plan.get", {
153
+ description: "Read the plan of `of`: its latest revision, or the one asked for with `rev`.",
154
+ input: z.object({ of: PlanSubject, rev: z.number().int().positive().optional() }),
155
+ output: PlanView,
156
+ target: (input) => planTarget(input.of),
157
+ });
158
+
159
+ export const planList = actionRef("plan.list", {
160
+ description:
161
+ "List the plans: what each is of, its latest revision and how many of its items are decisions still ahead. " +
162
+ "`open: true` keeps the plans that have at least one.",
163
+ input: z.object({ open: z.boolean().optional() }),
164
+ output: z.object({ plans: z.array(PlanSummary) }),
165
+ });
@@ -0,0 +1,33 @@
1
+ // The copy of the plan actions the cockpit module keeps reads what the host answers, and the host lists the module.
2
+
3
+ import { expect, test } from "bun:test";
4
+ import { actionName } from "@niwa-labs/core";
5
+ import { createNiwa, tempHome, unreadable, unsendable } from "@niwa-labs/testing";
6
+
7
+ import { plan } from "../src/index.ts";
8
+ import { planGet, planList } from "../src/records.ts";
9
+ import { getAction, listAction } from "../src/cockpit/actions.ts";
10
+
11
+ test.each([
12
+ ["plan.list", listAction, planList],
13
+ ["plan.get", getAction, planGet],
14
+ ] as const)("%s is sent as the host takes it and its answer is read", (name, copy, real) => {
15
+ expect(String(copy.name)).toBe(name);
16
+ expect(String(real.name)).toBe(name);
17
+ expect(unsendable(copy.input, real.input)).toEqual([]);
18
+ expect(unreadable(copy.output, real.output)).toEqual([]);
19
+ });
20
+
21
+ test("the plugin offers its page to the cockpit", async () => {
22
+ const home = await tempHome();
23
+ const niwa = createNiwa({ home: home.path });
24
+ try {
25
+ niwa.use(plan());
26
+ await niwa.serve();
27
+ const catalog = (await niwa.call(actionName("niwa.cockpit.catalog"), {})) as { modules: Array<{ id: string; plugin: string }> };
28
+ expect(catalog.modules).toContainEqual(expect.objectContaining({ id: "plan", plugin: "plan" }));
29
+ } finally {
30
+ await niwa.close();
31
+ await home.cleanup();
32
+ }
33
+ });
@@ -0,0 +1,52 @@
1
+ // The plan page: how far a plan has come, what a revision changed, and which revision an address asks for.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import type { PlanItem, PlanSummary } from "../src/cockpit/actions.ts";
6
+ import { changeText, changesBetween, plansInOrder, progressOf, revisionOf } from "../src/cockpit/revisions.ts";
7
+
8
+ const item = (id: string, state: PlanItem["state"], extra: Partial<PlanItem> = {}): PlanItem => ({ id, text: `do ${id}`, state, ...extra });
9
+
10
+ test("dropped work is no longer owed, so it leaves the total", () => {
11
+ const progress = progressOf([item("a", "done"), item("b", "planned"), item("c", "dropped"), item("d", "open")]);
12
+ expect(progress).toMatchObject({ done: 1, total: 3, counts: { open: 1, planned: 1, done: 1, dropped: 1 } });
13
+ });
14
+
15
+ test("plans with a decision ahead come first, then by name", () => {
16
+ const plan = (of: string, open: number): PlanSummary => ({ of, rev: 1, items: 3, open });
17
+ expect(plansInOrder([plan("b", 0), plan("z", 2), plan("a", 0), plan("m", 1)]).map((one) => one.of)).toEqual(["m", "z", "a", "b"]);
18
+ });
19
+
20
+ test("a revision shows the items it added, changed and removed, and the ones it left alone", () => {
21
+ const before = [item("a", "open"), item("b", "planned"), item("c", "planned")];
22
+ const after = [item("b", "planned"), item("a", "done", { note: "chose one table" }), item("d", "planned")];
23
+ const changes = changesBetween(before, after);
24
+ expect(changes.map((one) => [one.kind, one.item.id])).toEqual([
25
+ ["same", "b"],
26
+ ["changed", "a"],
27
+ ["added", "d"],
28
+ ["removed", "c"],
29
+ ]);
30
+ const changed = changes[1];
31
+ if (changed?.kind !== "changed") throw new Error("a was not shown as changed");
32
+ expect(changeText(changed)).toBe("Ждёт решения → Выполнен, Заметка обновлена");
33
+ });
34
+
35
+ test("rewording an item is a change, and so is taking its note away", () => {
36
+ const [reworded] = changesBetween([item("a", "planned")], [item("a", "planned", { text: "do a differently" })]);
37
+ if (reworded?.kind !== "changed") throw new Error("a was not shown as changed");
38
+ expect(changeText(reworded)).toBe("Текст обновлён");
39
+ const [unnoted] = changesBetween([item("a", "dropped", { note: "no longer needed" })], [item("a", "dropped")]);
40
+ if (unnoted?.kind !== "changed") throw new Error("a was not shown as changed");
41
+ expect(changeText(unnoted)).toBe("Заметка удалена");
42
+ });
43
+
44
+ test("an address asks for a whole revision the plan has, and anything else is the latest", () => {
45
+ expect(revisionOf("2", 3)).toBe(2);
46
+ expect(revisionOf("3", 3)).toBe(3);
47
+ expect(revisionOf("4", 3)).toBeUndefined();
48
+ expect(revisionOf("0", 3)).toBeUndefined();
49
+ expect(revisionOf("1.5", 3)).toBeUndefined();
50
+ expect(revisionOf("two", 3)).toBeUndefined();
51
+ expect(revisionOf(undefined, 3)).toBeUndefined();
52
+ });
@@ -0,0 +1,343 @@
1
+ import { expect, test } from "bun:test";
2
+
3
+ import { CatchableError, IntegrityError, NotSent, effectPossibleAfter, isCallTarget, matchesQuery, recordId, stableJson } from "@niwa-labs/core";
4
+ import type { Action, ActionContext, JournalReader, NewRecord, OperationId, ResolvedQuery, StoredRecord } from "@niwa-labs/core";
5
+ import { createNiwa, tempHome, testClock } from "@niwa-labs/testing";
6
+ import type { Plugin, PluginApi } from "@niwa-labs/plugin";
7
+
8
+ import { PlanRefusal, plan } from "../src/index.ts";
9
+ import { PlanRevised, planGet, planList, planSet, planTarget } from "../src/records.ts";
10
+ import type { PlanItem } from "../src/records.ts";
11
+
12
+ const decide: PlanItem = { id: "shape", text: "Choose the storage shape", state: "open" };
13
+ const build: PlanItem = { id: "build", text: "Build the reader", state: "planned" };
14
+
15
+ async function withPlans(run: (niwa: ReturnType<typeof createNiwa>) => Promise<void>): Promise<void> {
16
+ const home = await tempHome();
17
+ const niwa = createNiwa({ home: home.path, clock: testClock(1_000_000) });
18
+ try {
19
+ niwa.use(plan());
20
+ await niwa.serve();
21
+ await run(niwa);
22
+ } finally {
23
+ await niwa.close();
24
+ await home.cleanup();
25
+ }
26
+ }
27
+
28
+ test("each set is the next revision, and any revision can be read back", async () => {
29
+ await withPlans(async (niwa) => {
30
+ expect(await niwa.call(planSet, { of: "task-1", goal: "Ship the reader", items: [decide, build] })).toEqual({
31
+ of: "task-1",
32
+ rev: 1,
33
+ revised: true,
34
+ });
35
+ const second = [{ ...decide, state: "done" as const, note: "one table" }, build];
36
+ expect(await niwa.call(planSet, { of: "task-1", items: second })).toEqual({ of: "task-1", rev: 2, revised: true });
37
+
38
+ const latest = await niwa.call(planGet, { of: "task-1" });
39
+ expect(latest).toMatchObject({ of: "task-1", rev: 2, revisions: 2, items: second });
40
+ expect(latest.goal).toBeUndefined();
41
+ const first = await niwa.call(planGet, { of: "task-1", rev: 1 });
42
+ expect(first).toMatchObject({ rev: 1, revisions: 2, goal: "Ship the reader", items: [decide, build] });
43
+ expect(latest.at).toBe(1_000_000);
44
+ });
45
+ });
46
+
47
+ test("a set equal to the latest revision writes nothing", async () => {
48
+ await withPlans(async (niwa) => {
49
+ await niwa.call(planSet, { of: "p", goal: "g", items: [build] });
50
+ expect(await niwa.call(planSet, { of: "p", goal: "g", items: [build] })).toEqual({ of: "p", rev: 1, revised: false });
51
+ const written = (await niwa.records.read()).filter((row) => row.type === "plan.revised");
52
+ expect(written).toHaveLength(1);
53
+ // A different goal over the same items is a revision.
54
+ expect(await niwa.call(planSet, { of: "p", goal: "other", items: [build] })).toMatchObject({ rev: 2, revised: true });
55
+ });
56
+ });
57
+
58
+ test("two sets at once are revisions 1 and 2, never the same number twice", async () => {
59
+ await withPlans(async (niwa) => {
60
+ const results = await Promise.all([
61
+ niwa.call(planSet, { of: "race", items: [build] }),
62
+ niwa.call(planSet, { of: "race", items: [decide] }),
63
+ ]);
64
+ expect(results.map((one) => one.rev).sort()).toEqual([1, 2]);
65
+ const written = (await niwa.records.read()).filter((row) => row.type === "plan.revised");
66
+ expect(written.map((row) => (row.data as { rev: number }).rev)).toEqual([1, 2]);
67
+ });
68
+ });
69
+
70
+ test("expect refuses a set made on a revision that is no longer the latest", async () => {
71
+ await withPlans(async (niwa) => {
72
+ await expect(niwa.call(planSet, { of: "p", items: [build], expect: 3 })).rejects.toThrow(/revision 0/);
73
+ await niwa.call(planSet, { of: "p", items: [build], expect: 0 });
74
+ await niwa.call(planSet, { of: "p", items: [decide], expect: 1 });
75
+ await expect(niwa.call(planSet, { of: "p", items: [build, decide], expect: 1 })).rejects.toThrow(/revision 2/);
76
+ expect(await niwa.call(planGet, { of: "p" })).toMatchObject({ rev: 2, items: [decide] });
77
+ });
78
+ });
79
+
80
+ test("a plan that does not exist, or a revision it never had, is refused", async () => {
81
+ await withPlans(async (niwa) => {
82
+ await expect(niwa.call(planGet, { of: "nothing" })).rejects.toThrow(/no plan/);
83
+ await niwa.call(planSet, { of: "p", items: [] });
84
+ await expect(niwa.call(planGet, { of: "p", rev: 2 })).rejects.toThrow(/no revision 2/);
85
+ });
86
+ });
87
+
88
+ test("two items with one id are refused", async () => {
89
+ await withPlans(async (niwa) => {
90
+ await expect(niwa.call(planSet, { of: "p", items: [build, { ...decide, id: "build" }] })).rejects.toThrow(/used twice/);
91
+ });
92
+ });
93
+
94
+ test("list shows each plan at its latest revision, and keeps those with a decision ahead", async () => {
95
+ await withPlans(async (niwa) => {
96
+ await niwa.call(planSet, { of: "a", goal: "A", items: [decide, build] });
97
+ await niwa.call(planSet, { of: "b", items: [build] });
98
+ await niwa.call(planSet, { of: "a", goal: "A", items: [{ ...decide, state: "done" }, build] });
99
+ await niwa.call(planSet, { of: "c", items: [decide, { ...decide, id: "other" }] });
100
+
101
+ const all = await niwa.call(planList, {});
102
+ expect(all.plans).toEqual([
103
+ { of: "a", rev: 2, goal: "A", items: 2, open: 0 },
104
+ { of: "b", rev: 1, items: 1, open: 0 },
105
+ { of: "c", rev: 1, items: 2, open: 2 },
106
+ ]);
107
+ const ahead = await niwa.call(planList, { open: true });
108
+ expect(ahead.plans.map((one) => one.of)).toEqual(["c"]);
109
+ });
110
+ });
111
+
112
+ test("the plan survives a restart of the host", async () => {
113
+ const home = await tempHome();
114
+ try {
115
+ const first = createNiwa({ home: home.path });
116
+ first.use(plan());
117
+ await first.serve();
118
+ await first.call(planSet, { of: "p", items: [build] });
119
+ await first.close();
120
+
121
+ const second = createNiwa({ home: home.path });
122
+ second.use(plan());
123
+ await second.serve();
124
+ try {
125
+ expect(await second.call(planSet, { of: "p", items: [decide] })).toMatchObject({ rev: 2 });
126
+ } finally {
127
+ await second.close();
128
+ }
129
+ } finally {
130
+ await home.cleanup();
131
+ }
132
+ });
133
+
134
+ /** The actions a plugin registers, read by running its setup against a recording api. */
135
+ function actionsOf(source: Plugin): Map<string, Action<any, any, any>> {
136
+ const found = new Map<string, Action<any, any, any>>();
137
+ const api = new Proxy({} as PluginApi, {
138
+ get: (_target, name) =>
139
+ name === "action" ? (one: Action<any, any, any>) => void found.set(one.name, one) : () => undefined,
140
+ });
141
+ source.setup(api);
142
+ return found;
143
+ }
144
+
145
+ test("setting a plan is a record of niwa's own, and reading is a read", () => {
146
+ const actions = actionsOf(plan());
147
+ const set = actions.get("plan.set");
148
+ expect(set).toMatchObject({ effect: "record", world: "niwa", idempotent: true });
149
+ expect(actions.get("plan.get")).toMatchObject({ effect: "read", world: "niwa" });
150
+ expect(actions.get("plan.list")).toMatchObject({ effect: "read", world: "niwa" });
151
+ expect(set?.target?.({ of: "task-1", items: [] })).toBe("task-1");
152
+ });
153
+
154
+ test("the target of a plan is one a grant can name, whatever the plan is of", () => {
155
+ for (const of of ["task-1", "a b", "feature/x", "star*", "{id}@host:1"]) expect(isCallTarget(planTarget(of))).toBe(true);
156
+ expect(planTarget("feature/x*")).toBe("feature%2Fx%2A");
157
+ });
158
+
159
+ test("a set equal to the latest revision still answers to expect", async () => {
160
+ await withPlans(async (niwa) => {
161
+ await niwa.call(planSet, { of: "p", items: [build] });
162
+ await expect(niwa.call(planSet, { of: "p", items: [build], expect: 90 })).rejects.toThrow(/revision 1, not 90/);
163
+ await expect(niwa.call(planSet, { of: "p", items: [build], expect: 0 })).rejects.toThrow(/revision 1, not 0/);
164
+ expect(await niwa.call(planSet, { of: "p", items: [build], expect: 1 })).toEqual({ of: "p", rev: 1, revised: false });
165
+ });
166
+ });
167
+
168
+ test("a stale write records its refusal and leaves the plan unchanged", async () => {
169
+ await withPlans(async (niwa) => {
170
+ await niwa.call(planSet, { of: "p", items: [build] });
171
+ const stale = await niwa.call(planSet, { of: "p", items: [decide], expect: 0 }).catch((error: unknown) => error);
172
+ expect(stale).toBeInstanceOf(PlanRefusal);
173
+ expect(stale).toBeInstanceOf(CatchableError);
174
+ expect(stale).toMatchObject({ code: "stale", effectPossible: false });
175
+ expect(effectPossibleAfter(stale)).toBe(false);
176
+ expect(await niwa.records.read({ types: ["niwa.record.refused"] })).toHaveLength(1);
177
+ expect(await niwa.call(planGet, { of: "nothing" }).catch((error: unknown) => error)).toMatchObject({ code: "unknown-plan" });
178
+ expect(await niwa.call(planGet, { of: "p", rev: 9 }).catch((error: unknown) => error)).toMatchObject({ code: "unknown-revision" });
179
+ });
180
+ });
181
+
182
+ test("a subject is read the way a grant names it, and text that cannot be encoded is refused", async () => {
183
+ expect(planTarget(" p ")).toBe("p");
184
+ expect(planTarget(" a b ")).toBe("a%20b");
185
+ expect(() => planTarget("bad\ud800")).toThrow(/surrogate/);
186
+ await withPlans(async (niwa) => {
187
+ await expect(niwa.call(planSet, { of: "bad\udc00", items: [] })).rejects.toThrow(/surrogate/);
188
+ await expect(niwa.call(planGet, { of: "\ud800x" })).rejects.toThrow(/surrogate/);
189
+ await niwa.call(planSet, { of: " spaced ", items: [build] });
190
+ expect(await niwa.call(planGet, { of: "spaced" })).toMatchObject({ of: "spaced", rev: 1 });
191
+ });
192
+ });
193
+
194
+ /** A journal in memory that keeps what the real one keeps: records in commit order, written once by id. */
195
+ class MemoryJournal {
196
+ readonly rows: StoredRecord[] = [];
197
+
198
+ append(record: NewRecord): StoredRecord {
199
+ const same = this.rows.find((row) => row.id === record.id);
200
+ if (same !== undefined) {
201
+ if (stableJson(same.data) !== stableJson(record.data)) throw new IntegrityError(record.id);
202
+ return same;
203
+ }
204
+ const stored = { ...record, seq: this.rows.length + 1, at: 1_000_000 } as unknown as StoredRecord;
205
+ this.rows.push(stored);
206
+ return stored;
207
+ }
208
+
209
+ reader(): JournalReader {
210
+ return {
211
+ get: (id: string) => this.rows.find((row) => row.id === id),
212
+ query: (query: ResolvedQuery) => this.rows.filter((row) => matchesQuery(query, row)),
213
+ } as unknown as JournalReader;
214
+ }
215
+ }
216
+
217
+ /** The plan actions run by hand over a journal of their own, as the host would run them. */
218
+ async function withJournal(
219
+ run: (probe: {
220
+ readonly journal: MemoryJournal;
221
+ write(rev: number, items: PlanItem[], id: string): void;
222
+ set(operation: string, input: Parameters<typeof planSet.input.parse>[0]): Promise<unknown>;
223
+ get(input: Parameters<typeof planGet.input.parse>[0]): Promise<unknown>;
224
+ list(input?: Parameters<typeof planList.input.parse>[0]): Promise<unknown>;
225
+ }) => Promise<void>,
226
+ ): Promise<void> {
227
+ const journal = new MemoryJournal();
228
+ const reader = journal.reader();
229
+ const found = new Map<string, Action<any, any, any>>();
230
+ const api = new Proxy({} as PluginApi, {
231
+ get: (_target, name) => {
232
+ if (name === "action") return (one: Action<any, any, any>) => void found.set(one.name, one);
233
+ if (name === "journal") return () => reader;
234
+ return () => undefined;
235
+ },
236
+ });
237
+ plan().setup(api);
238
+ // The context of one call: a call made again is a new context under the same operation.
239
+ const context = (operationId: string): ActionContext => {
240
+ let ordinal = 0;
241
+ return {
242
+ operationId: operationId as OperationId,
243
+ caller: { kind: "host" },
244
+ emit: async (type: { name: string; version: number }, data: unknown) => {
245
+ ordinal += 1;
246
+ const id = recordId(`${operationId}/emit/${ordinal}`);
247
+ return journal.append({ id, stream: `input:${type.name}`, type: type.name, schema: type.version, data, actor: { kind: "host" }, cause: null, root: id } as unknown as NewRecord);
248
+ },
249
+ } as unknown as ActionContext;
250
+ };
251
+ const called = (name: string, input: unknown, operation: string): Promise<unknown> =>
252
+ Promise.resolve(found.get(name)?.run(input, context(operation)));
253
+ await run({
254
+ journal,
255
+ write: (rev, items, id) =>
256
+ void journal.append({
257
+ id: recordId(id),
258
+ stream: "input:plan.revised",
259
+ type: PlanRevised.name,
260
+ schema: PlanRevised.version,
261
+ data: { of: "p", rev, items },
262
+ actor: { kind: "host" },
263
+ cause: null,
264
+ root: recordId(id),
265
+ } as unknown as NewRecord),
266
+ set: (operation, input) => called("plan.set", planSet.input.parse(input), operation),
267
+ get: (input) => called("plan.get", planGet.input.parse(input), "op-get"),
268
+ list: (input = {}) => called("plan.list", planList.input.parse(input), "op-list"),
269
+ });
270
+ }
271
+
272
+ test("a set made again finds the revision it wrote, after another writer revised the plan", async () => {
273
+ await withJournal(async (probe) => {
274
+ expect(await probe.set("op-a", { of: "p", items: [build] })).toEqual({ of: "p", rev: 1, revised: true });
275
+ // The call is made again at once: it is the same write, not a set that changes nothing.
276
+ expect(await probe.set("op-a", { of: "p", items: [build] })).toEqual({ of: "p", rev: 1, revised: true });
277
+ expect(await probe.set("op-b", { of: "p", items: [decide] })).toEqual({ of: "p", rev: 2, revised: true });
278
+ // Made again after that, with and without the revision it was based on.
279
+ expect(await probe.set("op-a", { of: "p", items: [build] })).toEqual({ of: "p", rev: 1, revised: true });
280
+ expect(await probe.set("op-a", { of: "p", items: [build], expect: 0 })).toEqual({ of: "p", rev: 1, revised: true });
281
+ expect(probe.journal.rows).toHaveLength(2);
282
+ });
283
+ });
284
+
285
+ test("a revision is read by the number it carries, and the first of a number written twice stands", async () => {
286
+ await withJournal(async (probe) => {
287
+ const write = probe.write;
288
+ write(7, [build], "seven");
289
+ write(7, [decide], "seven-again");
290
+ write(9, [decide], "nine");
291
+ write(8, [build, decide], "eight");
292
+
293
+ expect(await probe.get({ of: "p" })).toMatchObject({ rev: 9, items: [decide], revisions: 3 });
294
+ expect(await probe.get({ of: "p", rev: 7 })).toMatchObject({ rev: 7, items: [build] });
295
+ expect(await probe.get({ of: "p", rev: 8 })).toMatchObject({ rev: 8, items: [build, decide] });
296
+ await expect(probe.get({ of: "p", rev: 1 })).rejects.toThrow(/no revision 1/);
297
+ expect(await probe.list()).toEqual({ plans: [{ of: "p", rev: 9, items: 1, open: 1 }] });
298
+ // The next revision follows the highest number, not the last record written.
299
+ expect(await probe.set("op-next", { of: "p", items: [build] })).toEqual({ of: "p", rev: 10, revised: true });
300
+ });
301
+ });
302
+
303
+ test("another plan's records are not read for this one", async () => {
304
+ await withJournal(async (probe) => {
305
+ await probe.set("op-1", { of: "a", items: [build] });
306
+ await probe.set("op-2", { of: "b", items: [decide] });
307
+ expect(await probe.get({ of: "a" })).toMatchObject({ rev: 1, revisions: 1, items: [build] });
308
+ await expect(probe.get({ of: "c" })).rejects.toThrow(/no plan/);
309
+ });
310
+ });
311
+
312
+ test("with no journal to read, the actions say so instead of showing no plans", async () => {
313
+ const found = actionsOf(plan());
314
+ const run = (name: string, input: unknown) => Promise.resolve(found.get(name)?.run(input, { operationId: "op" } as unknown as ActionContext));
315
+ for (const [name, input] of [
316
+ ["plan.list", {}],
317
+ ["plan.get", { of: "p" }],
318
+ ["plan.set", { of: "p", items: [] }],
319
+ ] as const) {
320
+ const error = await run(name, input).catch((thrown: unknown) => thrown);
321
+ expect(error).toBeInstanceOf(NotSent);
322
+ expect(error).toMatchObject({ message: expect.stringContaining("not serving") });
323
+ }
324
+ });
325
+
326
+ test("two writers of the same expected revision cannot both commit", async () => {
327
+ await withPlans(async niwa => {
328
+ const results = await Promise.allSettled([build, decide].map(item =>
329
+ niwa.call(planSet, { of: "shared", expect: 0, items: [item] })));
330
+ expect(results.filter(result => result.status === "fulfilled")).toHaveLength(1);
331
+ expect(await niwa.call(planGet, { of: "shared" })).toMatchObject({ rev: 1, revisions: 1 });
332
+ });
333
+ });
334
+
335
+ test("an unchanged plan returns its original revision after another writer revises it", async () => {
336
+ await withJournal(async probe => {
337
+ await probe.set("create", { of: "p", items: [build] });
338
+ const first = await probe.set("equal", { of: "p", items: [build] });
339
+ await probe.set("change", { of: "p", items: [decide] });
340
+ expect(await probe.set("equal", { of: "p", items: [build] })).toEqual(first);
341
+ expect(await probe.get({ of: "p" })).toMatchObject({ rev: 2 });
342
+ });
343
+ });
@@ -0,0 +1,19 @@
1
+ // The query builder of the plan records: what a script waits for when it waits for a plan to be revised.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { resolveQuery } from "@niwa-labs/core";
6
+
7
+ import { PlanRevised, planRevised } from "../src/records.ts";
8
+
9
+ test("the revisions of a plan are a query of their type, filtered on what the plan is of", () => {
10
+ expect(planRevised("task-3fa9c2")).toEqual({ types: [PlanRevised], filter: { of: "task-3fa9c2" } });
11
+ expect(resolveQuery(planRevised("task-3fa9c2")).types?.map(String)).toEqual(["plan.revised"]);
12
+ expect(planRevised("task-3fa9c2", 3).filter).toEqual({ of: "task-3fa9c2", rev: 3 });
13
+ });
14
+
15
+ test("the subject is read as an action reads it, trimmed, and a bad one is refused", () => {
16
+ expect(planRevised(" task-3fa9c2 ").filter).toEqual({ of: "task-3fa9c2" });
17
+ expect(() => planRevised(" ")).toThrow();
18
+ expect(() => planRevised("task-3fa9c2", 0)).toThrow();
19
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "lib": [
5
+ "ESNext",
6
+ "DOM",
7
+ "DOM.Iterable",
8
+ "DOM.AsyncIterable"
9
+ ],
10
+ "jsx": "react-jsx"
11
+ },
12
+ "include": [
13
+ "src"
14
+ ]
15
+ }