@oisin-ee/pi-dogsled 0.34.2 → 0.35.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.
@@ -0,0 +1,141 @@
1
+ import type { ReminderFact, TodoList } from "./wasm.ts";
2
+ import { STATE_ENTRY, branchList, branchSnapshot, latestSnapshot, stateChange } from "./state.ts";
3
+ import { apply, completionReminder, parse } from "./wasm.ts";
4
+ import { contract, first, firstId, fixture, last } from "./contract-fixture.ts";
5
+ import {
6
+ referenceFacts,
7
+ referenceLatest,
8
+ referenceSnapshot,
9
+ } from "./snapshot-reference-fixture.ts";
10
+ import { reminder, reminderFacts } from "./reminder.ts";
11
+ import type { Immutable } from "./delta.ts";
12
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
13
+ import type { TodoParams } from "./tool.ts";
14
+
15
+ interface SnapshotPair {
16
+ readonly actual: TodoList;
17
+ readonly expected: TodoList;
18
+ }
19
+ const snapshotLists = (facts: readonly Immutable<ReminderFact>[]): unknown[] => {
20
+ const lists: unknown[] = [];
21
+ for (const fact of facts) {
22
+ if (fact.kind === "snapshot") {
23
+ lists.push(fact.list);
24
+ }
25
+ }
26
+ return lists;
27
+ },
28
+ deltaCount = (branch: readonly SessionEntry[]): number =>
29
+ branch.filter((item) => item.type === "custom" && item.customType === "todo-delta").length,
30
+ taskAt = (list: TodoList, index = first): NonNullable<TodoList["tasks"][number]> => {
31
+ const task = list.tasks.at(index);
32
+ if (task === undefined) {
33
+ throw new Error("Missing fixture root");
34
+ }
35
+ return task;
36
+ },
37
+ storedData = (branch: readonly SessionEntry[]): { data: unknown; customType: string } => {
38
+ const stored = branch.at(last);
39
+ if (stored?.type !== "custom") {
40
+ throw new Error("Missing custom state entry");
41
+ }
42
+ return { customType: stored.customType, data: stored.data };
43
+ },
44
+ taskCount = 192,
45
+ entry = (id: string, customType: string, data: unknown): SessionEntry => ({
46
+ customType,
47
+ data,
48
+ id,
49
+ parentId: null,
50
+ timestamp: "2026-11-10T00:00:00Z",
51
+ type: "custom",
52
+ }),
53
+ initial = (count: number): TodoList =>
54
+ apply(
55
+ { tasks: [] },
56
+ {
57
+ items: Array.from({ length: count }, (_unused, index) => ({
58
+ content: `Task ${index}`,
59
+ contract: contract(),
60
+ })),
61
+ op: "init",
62
+ },
63
+ { mutationId: "initial", sessionId: "test-session" },
64
+ ).list,
65
+ statusSizes = (count: number): { delta: number; full: number; type: string } => {
66
+ const caller = fixture(),
67
+ before = caller.call({
68
+ items: Array.from({ length: count }, (_unused, index) => ({
69
+ content: `Task ${index}`,
70
+ contract: contract(),
71
+ })),
72
+ op: "init",
73
+ }),
74
+ after = caller.call({ op: "start", task: firstId(before) }),
75
+ change = storedData(caller.entries),
76
+ encoder = new TextEncoder();
77
+ return {
78
+ delta: encoder.encode(JSON.stringify(change.data)).length,
79
+ full: encoder.encode(JSON.stringify(after)).length,
80
+ type: change.customType,
81
+ };
82
+ };
83
+
84
+ /** Paired old and new writers, with a provenance observation at each mutation. */
85
+ class Replay {
86
+ public readonly branch: SessionEntry[] = [];
87
+ public readonly full: SessionEntry[] = [];
88
+ readonly #observed: SnapshotPair[] = [];
89
+
90
+ public save(list: TodoList, forceFull = false): void {
91
+ const id = `entry-${this.full.length}`,
92
+ change = forceFull
93
+ ? { customType: STATE_ENTRY, data: list }
94
+ : stateChange(branchSnapshot(this.branch), list),
95
+ parentId = this.full.at(last)?.id ?? null,
96
+ changedData = structuredClone(change.data),
97
+ fullData = structuredClone(list),
98
+ deltaEntry = Object.assign(entry(id, change.customType, changedData), { parentId }),
99
+ fullEntry = Object.assign(entry(id, STATE_ENTRY, fullData), { parentId });
100
+ this.branch.push(deltaEntry);
101
+ this.full.push(fullEntry);
102
+ this.#observed.push({
103
+ actual: branchSnapshot(this.branch),
104
+ expected: referenceSnapshot(this.full),
105
+ });
106
+ }
107
+
108
+ public call(params: TodoParams): void {
109
+ const context = { mutationId: `change-${this.full.length}`, sessionId: "test-session" },
110
+ expected = apply(referenceSnapshot(this.full), params, context),
111
+ actual = apply(branchSnapshot(this.branch), params, context);
112
+ this.#observed.push({ actual: actual.list, expected: expected.list });
113
+ this.save(actual.list);
114
+ }
115
+
116
+ public compare(): { actual: unknown; expected: unknown } {
117
+ const facts = referenceFacts(this.full);
118
+ return {
119
+ actual: {
120
+ derived: branchSnapshot(this.branch),
121
+ facts: completionReminder({ facts: reminderFacts(this.branch, []) }),
122
+ frames: [...branchList(this.branch)].map((frame) => frame.list),
123
+ full: branchSnapshot(this.full),
124
+ latest: latestSnapshot(this.branch),
125
+ observed: this.#observed.map((pair) => pair.actual),
126
+ reminder: reminder(this.branch, []),
127
+ },
128
+ expected: {
129
+ derived: referenceSnapshot(this.full),
130
+ facts: completionReminder({ facts }),
131
+ frames: snapshotLists(facts),
132
+ full: referenceSnapshot(this.full),
133
+ latest: parse(referenceLatest(this.full)),
134
+ observed: this.#observed.map((pair) => pair.expected),
135
+ reminder: completionReminder({ facts }),
136
+ },
137
+ };
138
+ }
139
+ }
140
+
141
+ export { Replay, deltaCount, entry, initial, statusSizes, storedData, taskAt, taskCount };
@@ -0,0 +1,63 @@
1
+ import { DELTA_ENTRY, STATE_ENTRY, stateChange } from "./state.ts";
2
+ import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import { entry, initial, taskAt } from "./delta-fixture.ts";
4
+ import { TaskProvider } from "./old-provider-fixture.ts";
5
+ import { leafTask } from "./delta.ts";
6
+ import { runtimeFixture } from "./runtime-fixture.ts";
7
+
8
+ const count = 100,
9
+ changes = 20,
10
+ first = 0,
11
+ step = 1,
12
+ replayBranch = (): SessionEntry[] => {
13
+ const list = initial(count),
14
+ branch = [entry("base", STATE_ENTRY, list)];
15
+ let current = list;
16
+ for (let index = first; index < changes; index += step) {
17
+ const next = structuredClone(current);
18
+ taskAt(next).description = `Change ${index}`;
19
+ const change = stateChange(current, next);
20
+ branch.push(entry(`change-${index}`, change.customType, change.data));
21
+ current = next;
22
+ }
23
+ return branch;
24
+ },
25
+ intermediateBranch = (changed: unknown): SessionEntry[] => {
26
+ const list = initial(count),
27
+ task = leafTask(taskAt(list)),
28
+ id = task.unit?.reference.unitId,
29
+ delta = (value: unknown): unknown => ({
30
+ changed: [{ id, task: value }],
31
+ orders: [],
32
+ removed: [],
33
+ version: step,
34
+ });
35
+ return [
36
+ entry("base", STATE_ENTRY, list),
37
+ entry("bad", DELTA_ENTRY, delta(changed)),
38
+ entry("fixed", DELTA_ENTRY, delta(task)),
39
+ ];
40
+ },
41
+ oldRuntime = async (): Promise<{
42
+ runtime: Awaited<ReturnType<typeof runtimeFixture>>;
43
+ provider: TaskProvider;
44
+ context: ExtensionContext;
45
+ }> => {
46
+ const captured: { provider?: TaskProvider; context?: ExtensionContext } = {},
47
+ runtime = await runtimeFixture((pi) => {
48
+ captured.provider = new TaskProvider(pi);
49
+ pi.on("session_start", (_event, ctx) => {
50
+ captured.context = ctx;
51
+ captured.provider?.context(ctx);
52
+ });
53
+ }),
54
+ { provider, context } = captured;
55
+ if (provider === undefined || context === undefined) {
56
+ runtime.session.dispose();
57
+ throw new Error("Missing retained provider context");
58
+ }
59
+ return { context, provider, runtime };
60
+ };
61
+
62
+ export { count, changes, intermediateBranch, oldRuntime, replayBranch };
63
+ export { show as oldShow } from "./old-lifecycle-fixture.ts";
@@ -0,0 +1,59 @@
1
+ import { Replay, initial, taskCount } from "./delta-fixture.ts";
2
+ import { REMINDER_ENTRY } from "./reminder.ts";
3
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
4
+ import { branchSnapshot } from "./state.ts";
5
+
6
+ const changes = 60,
7
+ rounds = 20,
8
+ first = 0,
9
+ step = 1,
10
+ reminderInterval = 5,
11
+ userInterval = 7,
12
+ boundaryEntries = (index: number): SessionEntry[] => {
13
+ const entries: SessionEntry[] = [];
14
+ if (index % reminderInterval === first) {
15
+ entries.push({
16
+ content: "Earlier reminder",
17
+ customType: REMINDER_ENTRY,
18
+ display: false,
19
+ id: `reminder-${index}`,
20
+ parentId: null,
21
+ timestamp: "2026-11-10T00:00:00Z",
22
+ type: "custom_message",
23
+ });
24
+ }
25
+ if (index % userInterval === first) {
26
+ entries.push({
27
+ id: `user-${index}`,
28
+ message: { content: "Continue", role: "user", timestamp: first },
29
+ parentId: null,
30
+ timestamp: "2026-11-10T00:00:00Z",
31
+ type: "message",
32
+ });
33
+ }
34
+ return entries;
35
+ },
36
+ changeRound = (
37
+ replay: { readonly branch: readonly SessionEntry[]; readonly call: Replay["call"] },
38
+ index: number,
39
+ ): void => {
40
+ const id = branchSnapshot(replay.branch).tasks.at(index)?.unit?.reference.unitId;
41
+ if (id === undefined) {
42
+ throw new Error("Missing scripted task");
43
+ }
44
+ replay.call({ description: `Revision ${index}`, op: "update", task: id });
45
+ replay.call({ op: "start", task: id });
46
+ replay.call({ evidence: "Relevant unit checks pass", op: "done", task: id });
47
+ },
48
+ sequence = (): Replay => {
49
+ const replay = new Replay();
50
+ replay.save(initial(taskCount), true);
51
+ for (let index = first; index < rounds; index += step) {
52
+ changeRound(replay, index);
53
+ replay.branch.push(...boundaryEntries(index));
54
+ replay.full.push(...boundaryEntries(index));
55
+ }
56
+ return replay;
57
+ };
58
+
59
+ export { changes, sequence };
@@ -0,0 +1,78 @@
1
+ import type { Task, TodoList } from "./wasm.ts";
2
+ import type { TaskChange, TodoDelta } from "./delta.ts";
3
+ import { deltaVersion, leafTask } from "./delta.ts";
4
+ import { parse, validateTask } from "./wasm.ts";
5
+ import type { OrderChange } from "./order-index.ts";
6
+
7
+ const record = (data: unknown): data is Readonly<Record<string, unknown>> =>
8
+ typeof data === "object" && data !== null,
9
+ nullableId = (data: unknown): data is string | null => data === null || typeof data === "string",
10
+ taskChange = (data: unknown): data is TaskChange =>
11
+ record(data) &&
12
+ typeof data["id"] === "string" &&
13
+ record(data["task"]) &&
14
+ !("subtasks" in data["task"]) &&
15
+ Object.keys(data).every((key) => key === "id" || key === "task"),
16
+ orderChange = (data: unknown): data is OrderChange =>
17
+ record(data) &&
18
+ typeof data["id"] === "string" &&
19
+ nullableId(data["parent"]) &&
20
+ nullableId(data["after"]) &&
21
+ Object.keys(data).every((key) => ["id", "parent", "after"].includes(key)),
22
+ envelope = (data: unknown): data is TodoDelta =>
23
+ record(data) &&
24
+ data["version"] === deltaVersion &&
25
+ Object.keys(data).every((key) => ["version", "changed", "orders", "removed"].includes(key)) &&
26
+ Array.isArray(data["changed"]) &&
27
+ data["changed"].every((change: unknown) => taskChange(change)) &&
28
+ Array.isArray(data["removed"]) &&
29
+ data["removed"].every((unitId: unknown) => typeof unitId === "string") &&
30
+ Array.isArray(data["orders"]) &&
31
+ data["orders"].every((order: unknown) => orderChange(order)),
32
+ changedTask = (data: unknown): Task => {
33
+ try {
34
+ return validateTask(data);
35
+ } catch (error: unknown) {
36
+ const message = error instanceof Error ? error.message : String(error);
37
+ throw new Error(`INVALID_TODO_DELTA: ${message}`, { cause: error });
38
+ }
39
+ },
40
+ deltaData = (data: unknown): TodoDelta => {
41
+ if (!envelope(data)) {
42
+ throw new Error("INVALID_TODO_DELTA: unsupported or malformed delta");
43
+ }
44
+ const removed = new Set(data.removed);
45
+ if (
46
+ new Set(data.changed.map((change) => change.id)).size !== data.changed.length ||
47
+ removed.size !== data.removed.length ||
48
+ data.changed.some((change) => removed.has(change.id))
49
+ ) {
50
+ throw new Error("INVALID_TODO_DELTA: repeated or conflicting task changes");
51
+ }
52
+ const changed = data.changed.map((change): TaskChange => {
53
+ const task = changedTask(change.task);
54
+ if (change.id !== task.unit?.reference.unitId) {
55
+ throw new Error("INVALID_TODO_DELTA: changed task identity differs");
56
+ }
57
+ return { id: change.id, task: leafTask(task) };
58
+ });
59
+ return Object.assign({}, data, { changed });
60
+ },
61
+ snapshotData = (data: unknown): { readonly fenced: boolean; readonly list: TodoList } => {
62
+ const fenced = record(data) && "format" in data;
63
+ if (fenced && data["format"] !== "todo-delta/1") {
64
+ throw new Error("INVALID_TODO_DELTA: unsupported snapshot format");
65
+ }
66
+ return {
67
+ fenced,
68
+ list: parse(
69
+ fenced
70
+ ? Object.fromEntries(
71
+ Object.entries(data).filter(([key]: readonly [string, unknown]) => key !== "format"),
72
+ )
73
+ : data,
74
+ ),
75
+ };
76
+ };
77
+
78
+ export { deltaData, snapshotData };
@@ -0,0 +1,102 @@
1
+ import { DELTA_ENTRY, branchSnapshot } from "./state.ts";
2
+ import { contract, first, firstId, last } from "./contract-fixture.ts";
3
+ import type { RuntimeFixture } from "./runtime-fixture.ts";
4
+ import { apply } from "./wasm.ts";
5
+ import { importFixture } from "./import-fixture.ts";
6
+ import { leafTask } from "./delta.ts";
7
+ import { runtimeFixture } from "./runtime-fixture.ts";
8
+ import { value } from "./provider-fixture.ts";
9
+
10
+ const workers = 100,
11
+ workerDrafts = (): { content: string; contract: ReturnType<typeof contract> }[] =>
12
+ Array.from({ length: workers }, (_unused, index) => ({
13
+ content: `Worker ${index}`,
14
+ contract: Object.assign(contract(), {
15
+ assignment: { kind: "worker" as const, profile: "general" },
16
+ }),
17
+ })),
18
+ claimScenario = async (): Promise<{ actual: unknown; origin: string }> => {
19
+ const runtime = await runtimeFixture();
20
+ try {
21
+ await runtime.todo({ items: workerDrafts(), op: "init" });
22
+ const unitId = firstId(branchSnapshot(runtime.manager.getBranch())),
23
+ provider = runtime.provider(),
24
+ inspected = value(provider.inspect(unitId)),
25
+ claimed = value(
26
+ provider.claim({
27
+ execution: { executor: "dogsled", ownerId: "owner", requestId: "delta-claim" },
28
+ expected: inspected.ref,
29
+ }),
30
+ ),
31
+ claimEntry = runtime.manager.getBranch().at(last),
32
+ settled = provider.settle({
33
+ binding: claimed.binding,
34
+ eventId: "delta-returned",
35
+ result: {
36
+ evidence: {
37
+ execution: claimed.binding.execution,
38
+ resultId: "reply",
39
+ summary: "Worker result",
40
+ },
41
+ kind: "returned",
42
+ },
43
+ version: 1,
44
+ }),
45
+ settleEntry = runtime.manager.getBranch().at(last),
46
+ task = branchSnapshot(runtime.manager.getBranch()).tasks.at(first);
47
+ return {
48
+ actual: {
49
+ claimEntry,
50
+ evidence: task?.unit?.evidence?.length,
51
+ origin: task?.unit?.reference.contractEntryId,
52
+ settleEntry,
53
+ settled,
54
+ task,
55
+ },
56
+ origin: inspected.ref.contractEntryId,
57
+ };
58
+ } finally {
59
+ runtime.session.dispose();
60
+ }
61
+ },
62
+ rewind = (
63
+ runtime: Readonly<Pick<RuntimeFixture, "provider">> & {
64
+ readonly manager: Readonly<Pick<RuntimeFixture["manager"], "branch" | "resetLeaf">>;
65
+ },
66
+ origin: string,
67
+ ): { active: unknown; imported: unknown } => {
68
+ runtime.manager.branch(origin);
69
+ const active = runtime.provider().active();
70
+ runtime.manager.resetLeaf();
71
+ return { active, imported: runtime.provider().imported() };
72
+ },
73
+ sealScenario = async (): Promise<{ receipt: unknown; rewound: unknown; sealId: string }> => {
74
+ const fixture = await importFixture(),
75
+ runtime = await runtimeFixture(undefined, false, fixture),
76
+ { manager } = runtime,
77
+ origin = manager.getLeafId();
78
+ try {
79
+ const sealed = apply(
80
+ branchSnapshot(manager.getBranch()),
81
+ { evidence: "Reviewed delta seal", op: "done", task: fixture.origin.id },
82
+ { mutationId: "delta-seal", sessionId: manager.getSessionId() },
83
+ ).list,
84
+ root = sealed.tasks.at(first);
85
+ if (root === undefined || origin === null) {
86
+ throw new Error("Missing imported root");
87
+ }
88
+ const sealId = manager.appendCustomEntry(DELTA_ENTRY, {
89
+ changed: [{ id: fixture.origin.id, task: leafTask(root) }],
90
+ orders: [],
91
+ removed: [],
92
+ version: 1,
93
+ }),
94
+ receipt = value(runtime.provider().imported());
95
+ return { receipt, rewound: rewind(runtime, origin), sealId };
96
+ } finally {
97
+ runtime.session.dispose();
98
+ await fixture.close();
99
+ }
100
+ };
101
+
102
+ export { claimScenario, sealScenario };
@@ -0,0 +1,152 @@
1
+ import type { Subtask, Task, TodoList } from "./wasm.ts";
2
+ import type { OrderChange } from "./order-index.ts";
3
+
4
+ type Immutable<Value> = { readonly [Key in keyof Value]: Immutable<Value[Key]> };
5
+ interface TaskChange {
6
+ readonly id: string;
7
+ readonly task: Immutable<Subtask>;
8
+ }
9
+ interface TodoDelta {
10
+ readonly changed: readonly TaskChange[];
11
+ readonly orders: readonly OrderChange[];
12
+ readonly removed: readonly string[];
13
+ readonly version: typeof deltaVersion;
14
+ }
15
+ interface ListIndex {
16
+ readonly orders: Readonly<Map<string | null, readonly string[]>>;
17
+ readonly tasks: Readonly<Map<string, Immutable<Subtask>>>;
18
+ }
19
+ const STATE_ENTRY = "todo-state",
20
+ DELTA_ENTRY = "todo-delta",
21
+ deltaVersion = 1,
22
+ first = 0,
23
+ step = 1,
24
+ halves = 2,
25
+ last = -1;
26
+ type StoredChange =
27
+ | { readonly customType: typeof STATE_ENTRY; readonly data: TodoList }
28
+ | { readonly customType: typeof DELTA_ENTRY; readonly data: TodoDelta };
29
+
30
+ // A child and a root carry the same fields, excluding nested children.
31
+ const leafTask = (task: Task | Immutable<Subtask>): Immutable<Subtask> =>
32
+ Object.assign(
33
+ { content: task.content, status: task.status },
34
+ task.description === undefined ? {} : { description: task.description },
35
+ task.unit === undefined ? {} : { unit: task.unit },
36
+ ),
37
+ childIndex = (
38
+ root: Task,
39
+ tasks: Readonly<Map<string, Immutable<Subtask>>>,
40
+ ): string[] | undefined => {
41
+ const children: string[] = [];
42
+ for (const child of root.subtasks ?? []) {
43
+ const childId = child.unit?.reference.unitId;
44
+ if (childId === undefined) {
45
+ return undefined;
46
+ }
47
+ children.push(childId);
48
+ tasks.set(childId, child);
49
+ }
50
+ return children;
51
+ },
52
+ indexed = (list: TodoList): ListIndex | undefined => {
53
+ const tasks = new Map<string, Immutable<Subtask>>(),
54
+ orders = new Map<string | null, readonly string[]>(),
55
+ roots: string[] = [];
56
+ for (const root of list.tasks) {
57
+ const unitId = root.unit?.reference.unitId,
58
+ children = childIndex(root, tasks);
59
+ if (unitId === undefined || children === undefined) {
60
+ return undefined;
61
+ }
62
+ roots.push(unitId);
63
+ tasks.set(unitId, leafTask(root));
64
+ orders.set(unitId, children);
65
+ }
66
+ orders.set(null, roots);
67
+ return { orders, tasks };
68
+ },
69
+ insertion = (tails: readonly { readonly position: number }[], position: number): number => {
70
+ let lower = first,
71
+ upper = tails.length;
72
+ while (lower < upper) {
73
+ const middle = Math.floor((lower + upper) / halves);
74
+ if ((tails.at(middle)?.position ?? Infinity) < position) {
75
+ lower = middle + step;
76
+ } else {
77
+ upper = middle;
78
+ }
79
+ }
80
+ return lower;
81
+ },
82
+ predecessorsFor = (
83
+ start: string | undefined,
84
+ predecessors: Readonly<Map<string, string | undefined>>,
85
+ ): ReadonlySet<string> => {
86
+ const stable = new Set<string>();
87
+ let current = start;
88
+ while (current !== undefined) {
89
+ stable.add(current);
90
+ current = predecessors.get(current);
91
+ }
92
+ return stable;
93
+ },
94
+ stableOrder = (before: readonly string[], after: readonly string[]): ReadonlySet<string> => {
95
+ const positions = new Map(before.map((unitId, index) => [unitId, index])),
96
+ tails: { readonly id: string; readonly position: number }[] = [],
97
+ predecessors = new Map<string, string | undefined>();
98
+ for (const unitId of after) {
99
+ const position = positions.get(unitId);
100
+ if (position !== undefined) {
101
+ const offset = insertion(tails, position);
102
+ predecessors.set(unitId, offset === first ? undefined : tails.at(offset - step)?.id);
103
+ tails[offset] = { id: unitId, position };
104
+ }
105
+ }
106
+ return predecessorsFor(tails.at(last)?.id, predecessors);
107
+ },
108
+ orderChanges = (before: Readonly<ListIndex>, after: Readonly<ListIndex>): OrderChange[] => {
109
+ const orders: OrderChange[] = [];
110
+ for (const [parent, ids] of after.orders) {
111
+ const stable = stableOrder(before.orders.get(parent) ?? [], ids);
112
+ let previous: string | null = null;
113
+ for (const unitId of ids) {
114
+ if (!stable.has(unitId)) {
115
+ orders.push({ after: previous, id: unitId, parent });
116
+ }
117
+ previous = unitId;
118
+ }
119
+ }
120
+ return orders;
121
+ },
122
+ changedTasks = (before: Readonly<ListIndex>, after: Readonly<ListIndex>): TaskChange[] => {
123
+ const changes: TaskChange[] = [];
124
+ for (const [unitId, task] of after.tasks) {
125
+ if (JSON.stringify(before.tasks.get(unitId)) !== JSON.stringify(task)) {
126
+ changes.push({ id: unitId, task });
127
+ }
128
+ }
129
+ return changes;
130
+ },
131
+ deltaBetween = (before: Readonly<ListIndex>, after: Readonly<ListIndex>): TodoDelta => ({
132
+ changed: changedTasks(before, after),
133
+ orders: orderChanges(before, after),
134
+ removed: [...before.tasks.keys()].filter((unitId) => !after.tasks.has(unitId)),
135
+ version: deltaVersion,
136
+ }),
137
+ stateChange = (before: TodoList, after: TodoList): StoredChange => {
138
+ const previous = indexed(before),
139
+ next = indexed(after);
140
+ if (previous === undefined || next === undefined) {
141
+ return { customType: STATE_ENTRY, data: after };
142
+ }
143
+ const data = deltaBetween(previous, next),
144
+ encoder = new TextEncoder();
145
+ return encoder.encode(JSON.stringify(data)).length <
146
+ encoder.encode(JSON.stringify(after)).length
147
+ ? { customType: DELTA_ENTRY, data }
148
+ : { customType: STATE_ENTRY, data: after };
149
+ };
150
+
151
+ export { DELTA_ENTRY, STATE_ENTRY, deltaVersion, indexed, leafTask, stateChange };
152
+ export type { Immutable, ListIndex, TaskChange, TodoDelta };
@@ -507,6 +507,14 @@ export function sections(list: TodoList): TodoSection[];
507
507
  */
508
508
  export function settle(list: TodoList, input: string, session_id: string): SettlementChange;
509
509
 
510
+ /**
511
+ * Validates one changed task without whole-list dependency checks.
512
+ *
513
+ * # Errors
514
+ * Throws for malformed shape, status, content, unit or binding fields.
515
+ */
516
+ export function validateTask(task: unknown): Task;
517
+
510
518
  /**
511
519
  * The model-facing summary of `list`.
512
520
  *
@@ -541,6 +549,7 @@ export interface InitOutput {
541
549
  readonly protect: (a: number, b: number, c: number, d: number, e: number) => void;
542
550
  readonly sections: (a: number, b: number) => void;
543
551
  readonly settle: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
552
+ readonly validateTask: (a: number, b: number) => void;
544
553
  readonly view: (a: number, b: number) => void;
545
554
  readonly widget: (a: number, b: number, c: number) => void;
546
555
  readonly __wbindgen_export: (a: number, b: number) => number;
@@ -350,6 +350,30 @@ export function settle(list, input, session_id) {
350
350
  }
351
351
  }
352
352
 
353
+ /**
354
+ * Validates one changed task without whole-list dependency checks.
355
+ *
356
+ * # Errors
357
+ * Throws for malformed shape, status, content, unit or binding fields.
358
+ * @param {unknown} task
359
+ * @returns {Task}
360
+ */
361
+ export function validateTask(task) {
362
+ try {
363
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
364
+ wasm.validateTask(retptr, addHeapObject(task));
365
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
366
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
367
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
368
+ if (r2) {
369
+ throw takeObject(r1);
370
+ }
371
+ return takeObject(r0);
372
+ } finally {
373
+ wasm.__wbindgen_add_to_stack_pointer(16);
374
+ }
375
+ }
376
+
353
377
  /**
354
378
  * The model-facing summary of `list`.
355
379
  *
@@ -13,6 +13,7 @@ export const parse: (a: number, b: number) => void;
13
13
  export const protect: (a: number, b: number, c: number, d: number, e: number) => void;
14
14
  export const sections: (a: number, b: number) => void;
15
15
  export const settle: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
16
+ export const validateTask: (a: number, b: number) => void;
16
17
  export const view: (a: number, b: number) => void;
17
18
  export const widget: (a: number, b: number, c: number) => void;
18
19
  export const __wbindgen_export: (a: number, b: number) => number;