@indexyz/pi-todo 0.0.0 → 0.1.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/CHANGELOG.md +8 -0
- package/README.md +81 -2
- package/config.ts +141 -0
- package/docs/configuration.md +108 -0
- package/docs/overlay.md +128 -0
- package/docs/tool-schema.md +191 -0
- package/index.ts +302 -0
- package/locales/de.json +19 -0
- package/locales/en.json +17 -0
- package/locales/es.json +19 -0
- package/locales/fr.json +19 -0
- package/locales/pt-BR.json +19 -0
- package/locales/pt.json +19 -0
- package/locales/ru.json +19 -0
- package/locales/uk.json +19 -0
- package/locales/zh.json +19 -0
- package/package.json +78 -8
- package/state/i18n-bridge.ts +64 -0
- package/state/invariants.ts +20 -0
- package/state/replay.ts +142 -0
- package/state/selectors.ts +108 -0
- package/state/state-reducer.ts +324 -0
- package/state/state.ts +18 -0
- package/state/store.ts +125 -0
- package/state/task-graph.ts +61 -0
- package/todo-overlay.ts +255 -0
- package/todo.ts +168 -0
- package/tool/normalize-params.ts +44 -0
- package/tool/response-envelope.ts +114 -0
- package/tool/sanitize.ts +34 -0
- package/tool/types.ts +188 -0
- package/view/format.ts +202 -0
package/state/replay.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { Value } from "typebox/value";
|
|
2
|
+
import { STATE_ENTRY_TYPE, TOOL_NAME, TodoParamsSchema } from "../tool/types.ts";
|
|
3
|
+
import { applyTaskMutation } from "./state-reducer.ts";
|
|
4
|
+
import { EMPTY_STATE, type TaskState } from "./state.ts";
|
|
5
|
+
import type {
|
|
6
|
+
Task,
|
|
7
|
+
TaskAction,
|
|
8
|
+
TaskMutationParams,
|
|
9
|
+
TaskStatus,
|
|
10
|
+
CompactTaskDetails,
|
|
11
|
+
} from "../tool/types.ts";
|
|
12
|
+
|
|
13
|
+
const TASK_ACTIONS: ReadonlySet<string> = new Set<TaskAction>([
|
|
14
|
+
"create",
|
|
15
|
+
"update",
|
|
16
|
+
"list",
|
|
17
|
+
"get",
|
|
18
|
+
"delete",
|
|
19
|
+
"clear",
|
|
20
|
+
]);
|
|
21
|
+
const TASK_STATUSES: ReadonlySet<unknown> = new Set<TaskStatus>([
|
|
22
|
+
"pending",
|
|
23
|
+
"in_progress",
|
|
24
|
+
"completed",
|
|
25
|
+
"deleted",
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
29
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
30
|
+
|
|
31
|
+
const isTaskAction = (value: unknown): value is TaskAction =>
|
|
32
|
+
typeof value === "string" && TASK_ACTIONS.has(value);
|
|
33
|
+
|
|
34
|
+
function isTask(value: unknown): value is Task {
|
|
35
|
+
if (!isRecord(value)) return false;
|
|
36
|
+
return (
|
|
37
|
+
Number.isSafeInteger(value.id) &&
|
|
38
|
+
typeof value.subject === "string" &&
|
|
39
|
+
TASK_STATUSES.has(value.status) &&
|
|
40
|
+
(value.description === undefined || typeof value.description === "string") &&
|
|
41
|
+
(value.activeForm === undefined || typeof value.activeForm === "string") &&
|
|
42
|
+
(value.owner === undefined || typeof value.owner === "string") &&
|
|
43
|
+
(value.blockedBy === undefined ||
|
|
44
|
+
(Array.isArray(value.blockedBy) && value.blockedBy.every(Number.isSafeInteger))) &&
|
|
45
|
+
(value.metadata === undefined || isRecord(value.metadata))
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Discriminator for legacy details envelopes with a complete task snapshot.
|
|
51
|
+
* A malformed or partial snapshot is skipped so replay keeps the last valid
|
|
52
|
+
* state instead of replacing it with corrupt data.
|
|
53
|
+
*/
|
|
54
|
+
function isLegacySnapshot(value: unknown): value is TaskState {
|
|
55
|
+
if (!isRecord(value)) return false;
|
|
56
|
+
return (
|
|
57
|
+
Array.isArray(value.tasks) && value.tasks.every(isTask) && Number.isSafeInteger(value.nextId)
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Discriminator for the compact action-and-parameters persistence record. */
|
|
62
|
+
function isCompactTaskDetails(value: unknown): value is CompactTaskDetails {
|
|
63
|
+
if (!isRecord(value)) return false;
|
|
64
|
+
return (
|
|
65
|
+
isTaskAction(value.action) &&
|
|
66
|
+
isRecord(value.params) &&
|
|
67
|
+
!Object.hasOwn(value, "tasks") &&
|
|
68
|
+
!Object.hasOwn(value, "nextId") &&
|
|
69
|
+
value.error === undefined &&
|
|
70
|
+
Value.Check(TodoParamsSchema, { ...value.params, action: value.action })
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Fresh `TaskState` from a legacy persisted snapshot. */
|
|
75
|
+
function stateOf(details: TaskState): TaskState {
|
|
76
|
+
return { tasks: details.tasks.map((task) => ({ ...task })), nextId: details.nextId };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function applyRecords(records: unknown[], base: TaskState): TaskState {
|
|
80
|
+
// A full snapshot supersedes every earlier operation in this stream.
|
|
81
|
+
for (let i = records.length - 1; i >= 0; i--) {
|
|
82
|
+
const record = records[i];
|
|
83
|
+
if (!isLegacySnapshot(record)) continue;
|
|
84
|
+
base = stateOf(record);
|
|
85
|
+
records = records.slice(i + 1);
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
for (const record of records) {
|
|
89
|
+
if (isCompactTaskDetails(record)) {
|
|
90
|
+
base = applyTaskMutation(base, record.action, record.params as TaskMutationParams).state;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return base;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Walk the current branch in chronological order and reconstruct task state.
|
|
98
|
+
*
|
|
99
|
+
* New records contain only the action and parameters needed to replay the
|
|
100
|
+
* operation. Legacy records contain the full `tasks`/`nextId` snapshot. Custom
|
|
101
|
+
* entries remain authoritative when present because a nested tool call may not
|
|
102
|
+
* have a standalone toolResult message. Tool results preceding the first valid
|
|
103
|
+
* custom entry can seed old branches, but later results duplicate the custom stream.
|
|
104
|
+
*/
|
|
105
|
+
export function replayFromBranch(ctx: {
|
|
106
|
+
sessionManager: { getBranch(): Iterable<unknown> };
|
|
107
|
+
}): TaskState {
|
|
108
|
+
const customRecords: unknown[] = [];
|
|
109
|
+
const toolResultRecords: unknown[] = [];
|
|
110
|
+
|
|
111
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
112
|
+
const value = entry as {
|
|
113
|
+
type?: string;
|
|
114
|
+
customType?: string;
|
|
115
|
+
data?: unknown;
|
|
116
|
+
message?: { role?: string; toolName?: string; details?: unknown };
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
if (value.type === "custom") {
|
|
120
|
+
if (
|
|
121
|
+
value.customType === STATE_ENTRY_TYPE &&
|
|
122
|
+
(customRecords.length > 0 ||
|
|
123
|
+
isCompactTaskDetails(value.data) ||
|
|
124
|
+
isLegacySnapshot(value.data))
|
|
125
|
+
) {
|
|
126
|
+
customRecords.push(value.data);
|
|
127
|
+
}
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (customRecords.length > 0 || value.type !== "message") continue;
|
|
132
|
+
const message = value.message;
|
|
133
|
+
if (message?.role === "toolResult" && message.toolName === TOOL_NAME) {
|
|
134
|
+
toolResultRecords.push(message.details);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const empty = { tasks: [...EMPTY_STATE.tasks], nextId: EMPTY_STATE.nextId };
|
|
139
|
+
const first = customRecords[0];
|
|
140
|
+
const base = isLegacySnapshot(first) ? empty : applyRecords(toolResultRecords, empty);
|
|
141
|
+
return applyRecords(customRecords, base);
|
|
142
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { Task, TaskStatus } from "../tool/types.ts";
|
|
2
|
+
import type { TaskState } from "./state.ts";
|
|
3
|
+
|
|
4
|
+
/** Tasks excluding deleted tombstones — the canonical "what's visible". */
|
|
5
|
+
export function selectVisibleTasks(state: TaskState): readonly Task[] {
|
|
6
|
+
return state.tasks.filter((t) => t.status !== "deleted");
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Group visible tasks by status. Iteration order at the call site uses
|
|
11
|
+
* (`completed`, `inProgress`, `pending`) to match the `/todos` header part
|
|
12
|
+
* order pinned by `todo.command.test.ts`.
|
|
13
|
+
*/
|
|
14
|
+
export interface TasksByStatus {
|
|
15
|
+
pending: readonly Task[];
|
|
16
|
+
inProgress: readonly Task[];
|
|
17
|
+
completed: readonly Task[];
|
|
18
|
+
}
|
|
19
|
+
export function selectTasksByStatus(state: TaskState): TasksByStatus {
|
|
20
|
+
const visible = selectVisibleTasks(state);
|
|
21
|
+
return {
|
|
22
|
+
pending: visible.filter((t) => t.status === "pending"),
|
|
23
|
+
inProgress: visible.filter((t) => t.status === "in_progress"),
|
|
24
|
+
completed: visible.filter((t) => t.status === "completed"),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Total counts for the overlay heading (`Todos (n/m)`) and `/todos` header. */
|
|
29
|
+
export interface TodoCounts {
|
|
30
|
+
total: number;
|
|
31
|
+
pending: number;
|
|
32
|
+
inProgress: number;
|
|
33
|
+
completed: number;
|
|
34
|
+
}
|
|
35
|
+
export function selectTodoCounts(state: TaskState): TodoCounts {
|
|
36
|
+
const groups = selectTasksByStatus(state);
|
|
37
|
+
return {
|
|
38
|
+
total: groups.pending.length + groups.inProgress.length + groups.completed.length,
|
|
39
|
+
pending: groups.pending.length,
|
|
40
|
+
inProgress: groups.inProgress.length,
|
|
41
|
+
completed: groups.completed.length,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Whether any visible task carries a `blockedBy` reference. The overlay uses
|
|
47
|
+
* this to gate the `#id` prefix on per-task rows — without at least one
|
|
48
|
+
* `⛓ #N` suffix, the per-row id has no anchor.
|
|
49
|
+
*/
|
|
50
|
+
export function selectShowTaskIds(state: TaskState): boolean {
|
|
51
|
+
return selectVisibleTasks(state).some((t) => t.blockedBy && t.blockedBy.length > 0);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Resolve a task's subject by id from the live state for renderCall's
|
|
56
|
+
* accent label. `undefined` when the id is unknown — caller falls back to
|
|
57
|
+
* `#id` plain rendering.
|
|
58
|
+
*/
|
|
59
|
+
export function selectTaskSubjectById(state: TaskState, id: number): string | undefined {
|
|
60
|
+
return state.tasks.find((t) => t.id === id)?.subject;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Overlay layout decision. Encapsulates the "drop completed first, then
|
|
65
|
+
* truncate non-completed tail" rule. `budget` is the body-slot count (caller passes
|
|
66
|
+
* `getMaxWidgetLines() - 1` to reserve the heading row); on overflow the
|
|
67
|
+
* selector reserves one more slot internally for the summary row. Returns
|
|
68
|
+
* the visible task slice plus the overflow summary parts.
|
|
69
|
+
*/
|
|
70
|
+
export interface OverlayLayout {
|
|
71
|
+
visible: readonly Task[];
|
|
72
|
+
hiddenCompleted: number;
|
|
73
|
+
truncatedTail: number;
|
|
74
|
+
}
|
|
75
|
+
export function selectOverlayLayout(state: TaskState, budget: number): OverlayLayout {
|
|
76
|
+
const all = selectVisibleTasks(state);
|
|
77
|
+
if (all.length <= budget) {
|
|
78
|
+
return { visible: all, hiddenCompleted: 0, truncatedTail: 0 };
|
|
79
|
+
}
|
|
80
|
+
const innerBudget = budget - 1;
|
|
81
|
+
const nonCompleted = all.filter((t) => t.status !== "completed");
|
|
82
|
+
const totalCompleted = all.length - nonCompleted.length;
|
|
83
|
+
if (nonCompleted.length <= innerBudget) {
|
|
84
|
+
const kept = new Set<Task>(nonCompleted);
|
|
85
|
+
for (const t of all) {
|
|
86
|
+
if (kept.size >= innerBudget) break;
|
|
87
|
+
if (t.status === "completed") kept.add(t);
|
|
88
|
+
}
|
|
89
|
+
const visible = all.filter((t) => kept.has(t));
|
|
90
|
+
const shownCompleted = visible.filter((t) => t.status === "completed").length;
|
|
91
|
+
return { visible, hiddenCompleted: totalCompleted - shownCompleted, truncatedTail: 0 };
|
|
92
|
+
}
|
|
93
|
+
const visible = nonCompleted.slice(0, innerBudget);
|
|
94
|
+
const truncatedTail = nonCompleted.length - innerBudget;
|
|
95
|
+
return { visible, hiddenCompleted: totalCompleted, truncatedTail };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Helper: whether any visible task is `pending` or `in_progress`. The overlay
|
|
100
|
+
* uses this to pick the heading icon (`accent`+`●` vs `dim`+`○`).
|
|
101
|
+
*/
|
|
102
|
+
export function selectHasActive(state: TaskState): boolean {
|
|
103
|
+
return selectVisibleTasks(state).some(
|
|
104
|
+
(t) => t.status === "in_progress" || t.status === "pending",
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export const ACTIVE_STATUSES: ReadonlySet<TaskStatus> = new Set(["pending", "in_progress"]);
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import type { Task, TaskAction, TaskMutationParams, TaskStatus } from "../tool/types.ts";
|
|
2
|
+
import { isTransitionValid } from "./invariants.ts";
|
|
3
|
+
import type { TaskState } from "./state.ts";
|
|
4
|
+
import { detectCycle } from "./task-graph.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Reducer outcome. Closed tagged union — adding a new action requires extending
|
|
8
|
+
* this union AND the response-envelope's `formatContent` switch (compiler-
|
|
9
|
+
* enforced exhaustive). Mirrors the `Effect` pattern in
|
|
10
|
+
* `packages/rpiv-ask-user-question/state/state-reducer.ts:14-30`.
|
|
11
|
+
*
|
|
12
|
+
* `error` carries the message in-band so callers can pattern-match on
|
|
13
|
+
* `op.kind === "error"` without a side-channel boolean.
|
|
14
|
+
*/
|
|
15
|
+
export type Op =
|
|
16
|
+
| { kind: "create"; taskIds: number[] }
|
|
17
|
+
| { kind: "update"; id: number; fromStatus: TaskStatus; toStatus: TaskStatus; changed: boolean }
|
|
18
|
+
| { kind: "delete"; id: number; subject: string }
|
|
19
|
+
| { kind: "list"; statusFilter?: TaskStatus; includeDeleted: boolean }
|
|
20
|
+
| { kind: "get"; task: Task }
|
|
21
|
+
| { kind: "clear"; count: number }
|
|
22
|
+
| { kind: "error"; message: string };
|
|
23
|
+
|
|
24
|
+
export interface ApplyResult {
|
|
25
|
+
state: TaskState;
|
|
26
|
+
op: Op;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* True when `op` changed the task state — the calls whose post-commit snapshot
|
|
31
|
+
* must be persisted for replay. Reads (`list`/`get`), failures, and a no-effect
|
|
32
|
+
* `update` leave state untouched. Exhaustive over `Op` (compiler-enforced), so a
|
|
33
|
+
* new action must decide here whether it persists.
|
|
34
|
+
*/
|
|
35
|
+
export function changesState(op: Op): boolean {
|
|
36
|
+
switch (op.kind) {
|
|
37
|
+
case "create":
|
|
38
|
+
case "delete":
|
|
39
|
+
case "clear":
|
|
40
|
+
return true;
|
|
41
|
+
case "update":
|
|
42
|
+
return op.changed;
|
|
43
|
+
case "list":
|
|
44
|
+
case "get":
|
|
45
|
+
case "error":
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function errorResult(state: TaskState, message: string): ApplyResult {
|
|
51
|
+
return { state, op: { kind: "error", message } };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Per-task create fields: on a batch they belong to each `tasks[]` item. */
|
|
55
|
+
const BATCH_ITEM_FIELDS = ["description", "activeForm", "blockedBy", "owner", "metadata"] as const;
|
|
56
|
+
|
|
57
|
+
function asCreateItem(value: unknown): TaskMutationParams | undefined {
|
|
58
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
|
|
59
|
+
return value as TaskMutationParams;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function buildCreatedTask(id: number, spec: TaskMutationParams, subject: string): Task {
|
|
63
|
+
const newTask: Task = {
|
|
64
|
+
id,
|
|
65
|
+
subject,
|
|
66
|
+
status: "pending",
|
|
67
|
+
};
|
|
68
|
+
if (spec.description) newTask.description = spec.description;
|
|
69
|
+
if (spec.activeForm) newTask.activeForm = spec.activeForm;
|
|
70
|
+
if (spec.blockedBy?.length) newTask.blockedBy = [...spec.blockedBy];
|
|
71
|
+
if (spec.owner) newTask.owner = spec.owner;
|
|
72
|
+
if (spec.metadata) newTask.metadata = { ...spec.metadata };
|
|
73
|
+
return newTask;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function validateCreateBlockedBy(
|
|
77
|
+
state: TaskState,
|
|
78
|
+
blockedBy: number[] | undefined,
|
|
79
|
+
siblingIds: ReadonlySet<number>,
|
|
80
|
+
): string | undefined {
|
|
81
|
+
if (!blockedBy?.length) return undefined;
|
|
82
|
+
for (const dep of blockedBy) {
|
|
83
|
+
if (siblingIds.has(dep)) {
|
|
84
|
+
return `blockedBy: #${dep} is another item in this batch; create the prerequisite first, then the dependent with blockedBy`;
|
|
85
|
+
}
|
|
86
|
+
const depTask = state.tasks.find((t) => t.id === dep);
|
|
87
|
+
if (!depTask) return `blockedBy: #${dep} not found`;
|
|
88
|
+
if (depTask.status === "deleted") return `blockedBy: #${dep} is deleted`;
|
|
89
|
+
}
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function sameNumberList(a: number[] | undefined, b: number[] | undefined): boolean {
|
|
94
|
+
const x = a ?? [];
|
|
95
|
+
const y = b ?? [];
|
|
96
|
+
return x.length === y.length && x.every((v, i) => v === y[i]);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function sameRecord(
|
|
100
|
+
a: Record<string, unknown> | undefined,
|
|
101
|
+
b: Record<string, unknown> | undefined,
|
|
102
|
+
): boolean {
|
|
103
|
+
return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Did this `update` change anything? Compares the task before/after the params
|
|
108
|
+
* are applied. A no-effect update — `status` set to its current value, or any
|
|
109
|
+
* field re-sent unchanged — returns false, letting the response envelope say
|
|
110
|
+
* "No change" instead of "Updated #N". Without this, a no-op update is
|
|
111
|
+
* indistinguishable from a real mutation, which can drive a model to re-issue
|
|
112
|
+
* the same call in a loop.
|
|
113
|
+
*
|
|
114
|
+
* blockedBy is order-sensitive (the reducer preserves insertion order);
|
|
115
|
+
* metadata round-trips through JSON persistence, so JSON-equality is the
|
|
116
|
+
* operative notion of "changed".
|
|
117
|
+
*/
|
|
118
|
+
function taskChanged(before: Task, after: Task): boolean {
|
|
119
|
+
return (
|
|
120
|
+
before.subject !== after.subject ||
|
|
121
|
+
before.status !== after.status ||
|
|
122
|
+
before.description !== after.description ||
|
|
123
|
+
before.activeForm !== after.activeForm ||
|
|
124
|
+
before.owner !== after.owner ||
|
|
125
|
+
!sameNumberList(before.blockedBy, after.blockedBy) ||
|
|
126
|
+
!sameRecord(before.metadata, after.metadata)
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Pure reducer: (state, action, params) → (state, op). The response envelope (`tool/response-envelope.ts`) owns
|
|
132
|
+
* formatting, the store (`state/store.ts`) owns commit.
|
|
133
|
+
*
|
|
134
|
+
* Validation is in-line: structural guards (`subject required`, `id required`,
|
|
135
|
+
* `at least one mutable field`) plus state-aware checks (transition legality,
|
|
136
|
+
* dangling/deleted blockedBy, self-block, cycles). Decision: validation stays
|
|
137
|
+
* in-reducer.
|
|
138
|
+
*/
|
|
139
|
+
export function applyTaskMutation(
|
|
140
|
+
state: TaskState,
|
|
141
|
+
action: TaskAction,
|
|
142
|
+
params: TaskMutationParams,
|
|
143
|
+
): ApplyResult {
|
|
144
|
+
switch (action) {
|
|
145
|
+
case "create": {
|
|
146
|
+
const batch = params.tasks;
|
|
147
|
+
|
|
148
|
+
if (Array.isArray(batch) && params.subject !== undefined) {
|
|
149
|
+
return errorResult(state, "create requires subject or tasks[], not both");
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (Array.isArray(batch)) {
|
|
153
|
+
// Each item carries its own fields; a top-level one would apply to no item.
|
|
154
|
+
const topLevel = BATCH_ITEM_FIELDS.filter((field) => params[field] !== undefined);
|
|
155
|
+
if (topLevel.length) {
|
|
156
|
+
return errorResult(
|
|
157
|
+
state,
|
|
158
|
+
`create with tasks[] takes ${topLevel.join(", ")} on each item, not at the top level`,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
if (batch.length === 0) {
|
|
162
|
+
return errorResult(state, "tasks[] must be non-empty");
|
|
163
|
+
}
|
|
164
|
+
const items: Array<{ spec: TaskMutationParams; subject: string }> = [];
|
|
165
|
+
for (let i = 0; i < batch.length; i++) {
|
|
166
|
+
const spec = asCreateItem(batch[i]);
|
|
167
|
+
const subject = spec?.subject;
|
|
168
|
+
if (!spec || !subject?.trim()) {
|
|
169
|
+
return errorResult(state, `tasks[${i}]: subject required for create`);
|
|
170
|
+
}
|
|
171
|
+
items.push({ spec, subject });
|
|
172
|
+
}
|
|
173
|
+
const siblingIds = new Set(items.map((_, i) => state.nextId + i));
|
|
174
|
+
for (const item of items) {
|
|
175
|
+
const blockedError = validateCreateBlockedBy(state, item.spec.blockedBy, siblingIds);
|
|
176
|
+
if (blockedError) return errorResult(state, blockedError);
|
|
177
|
+
}
|
|
178
|
+
const created = items.map((item, i) =>
|
|
179
|
+
buildCreatedTask(state.nextId + i, item.spec, item.subject),
|
|
180
|
+
);
|
|
181
|
+
return {
|
|
182
|
+
state: { tasks: [...state.tasks, ...created], nextId: state.nextId + created.length },
|
|
183
|
+
op: { kind: "create", taskIds: created.map((t) => t.id) },
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (!params.subject?.trim()) {
|
|
188
|
+
return errorResult(state, "subject required for create");
|
|
189
|
+
}
|
|
190
|
+
const blockedError = validateCreateBlockedBy(state, params.blockedBy, new Set());
|
|
191
|
+
if (blockedError) return errorResult(state, blockedError);
|
|
192
|
+
const newTask = buildCreatedTask(state.nextId, params, params.subject);
|
|
193
|
+
return {
|
|
194
|
+
state: { tasks: [...state.tasks, newTask], nextId: state.nextId + 1 },
|
|
195
|
+
op: { kind: "create", taskIds: [newTask.id] },
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
case "update": {
|
|
200
|
+
if (params.id === undefined) return errorResult(state, "id required for update");
|
|
201
|
+
const idx = state.tasks.findIndex((t) => t.id === params.id);
|
|
202
|
+
if (idx === -1) return errorResult(state, `#${params.id} not found`);
|
|
203
|
+
const current = state.tasks[idx];
|
|
204
|
+
|
|
205
|
+
const hasMutation =
|
|
206
|
+
params.subject !== undefined ||
|
|
207
|
+
params.description !== undefined ||
|
|
208
|
+
params.activeForm !== undefined ||
|
|
209
|
+
params.status !== undefined ||
|
|
210
|
+
params.owner !== undefined ||
|
|
211
|
+
params.metadata !== undefined ||
|
|
212
|
+
(params.addBlockedBy && params.addBlockedBy.length > 0) ||
|
|
213
|
+
(params.removeBlockedBy && params.removeBlockedBy.length > 0);
|
|
214
|
+
if (!hasMutation)
|
|
215
|
+
return errorResult(
|
|
216
|
+
state,
|
|
217
|
+
"update requires at least one mutable field: subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy",
|
|
218
|
+
);
|
|
219
|
+
|
|
220
|
+
let newStatus = current.status;
|
|
221
|
+
if (params.status !== undefined) {
|
|
222
|
+
if (!isTransitionValid(current.status, params.status)) {
|
|
223
|
+
return errorResult(state, `illegal transition ${current.status} → ${params.status}`);
|
|
224
|
+
}
|
|
225
|
+
newStatus = params.status;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
let newBlockedBy = current.blockedBy ? [...current.blockedBy] : [];
|
|
229
|
+
if (params.removeBlockedBy?.length) {
|
|
230
|
+
const toRemove = new Set(params.removeBlockedBy);
|
|
231
|
+
newBlockedBy = newBlockedBy.filter((dep) => !toRemove.has(dep));
|
|
232
|
+
}
|
|
233
|
+
if (params.addBlockedBy?.length) {
|
|
234
|
+
for (const dep of params.addBlockedBy) {
|
|
235
|
+
if (dep === current.id)
|
|
236
|
+
return errorResult(state, `cannot block #${current.id} on itself`);
|
|
237
|
+
const depTask = state.tasks.find((t) => t.id === dep);
|
|
238
|
+
if (!depTask) return errorResult(state, `addBlockedBy: #${dep} not found`);
|
|
239
|
+
if (depTask.status === "deleted")
|
|
240
|
+
return errorResult(state, `addBlockedBy: #${dep} is deleted`);
|
|
241
|
+
if (!newBlockedBy.includes(dep)) newBlockedBy.push(dep);
|
|
242
|
+
}
|
|
243
|
+
if (detectCycle(state.tasks, current.id, newBlockedBy)) {
|
|
244
|
+
return errorResult(state, "addBlockedBy would create a cycle in the blockedBy graph");
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
let newMetadata = current.metadata;
|
|
249
|
+
if (params.metadata !== undefined) {
|
|
250
|
+
const merged: Record<string, unknown> = { ...current.metadata };
|
|
251
|
+
for (const [k, v] of Object.entries(params.metadata)) {
|
|
252
|
+
if (v === null) delete merged[k];
|
|
253
|
+
else merged[k] = v;
|
|
254
|
+
}
|
|
255
|
+
newMetadata = Object.keys(merged).length ? merged : undefined;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const updated: Task = { ...current, status: newStatus };
|
|
259
|
+
if (params.subject !== undefined) updated.subject = params.subject;
|
|
260
|
+
if (params.description !== undefined) updated.description = params.description;
|
|
261
|
+
if (params.activeForm !== undefined) updated.activeForm = params.activeForm;
|
|
262
|
+
if (params.owner !== undefined) updated.owner = params.owner;
|
|
263
|
+
if (newBlockedBy.length) updated.blockedBy = newBlockedBy;
|
|
264
|
+
else delete updated.blockedBy;
|
|
265
|
+
if (newMetadata === undefined) delete updated.metadata;
|
|
266
|
+
else updated.metadata = newMetadata;
|
|
267
|
+
|
|
268
|
+
const newTasks = [...state.tasks];
|
|
269
|
+
newTasks[idx] = updated;
|
|
270
|
+
return {
|
|
271
|
+
state: { tasks: newTasks, nextId: state.nextId },
|
|
272
|
+
op: {
|
|
273
|
+
kind: "update",
|
|
274
|
+
id: updated.id,
|
|
275
|
+
fromStatus: current.status,
|
|
276
|
+
toStatus: newStatus,
|
|
277
|
+
changed: taskChanged(current, updated),
|
|
278
|
+
},
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
case "list": {
|
|
283
|
+
return {
|
|
284
|
+
state,
|
|
285
|
+
op: {
|
|
286
|
+
kind: "list",
|
|
287
|
+
includeDeleted: params.includeDeleted === true,
|
|
288
|
+
...(params.status !== undefined ? { statusFilter: params.status } : {}),
|
|
289
|
+
},
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
case "get": {
|
|
294
|
+
if (params.id === undefined) return errorResult(state, "id required for get");
|
|
295
|
+
const task = state.tasks.find((t) => t.id === params.id);
|
|
296
|
+
if (!task) return errorResult(state, `#${params.id} not found`);
|
|
297
|
+
return { state, op: { kind: "get", task } };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
case "delete": {
|
|
301
|
+
if (params.id === undefined) return errorResult(state, "id required for delete");
|
|
302
|
+
const idx = state.tasks.findIndex((t) => t.id === params.id);
|
|
303
|
+
if (idx === -1) return errorResult(state, `#${params.id} not found`);
|
|
304
|
+
const current = state.tasks[idx];
|
|
305
|
+
if (current.status === "deleted")
|
|
306
|
+
return errorResult(state, `#${current.id} is already deleted`);
|
|
307
|
+
const updated: Task = { ...current, status: "deleted" };
|
|
308
|
+
const newTasks = [...state.tasks];
|
|
309
|
+
newTasks[idx] = updated;
|
|
310
|
+
return {
|
|
311
|
+
state: { tasks: newTasks, nextId: state.nextId },
|
|
312
|
+
op: { kind: "delete", id: updated.id, subject: updated.subject },
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
case "clear": {
|
|
317
|
+
const count = state.tasks.length;
|
|
318
|
+
return {
|
|
319
|
+
state: { tasks: [], nextId: 1 },
|
|
320
|
+
op: { kind: "clear", count },
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
package/state/state.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Task } from "../tool/types.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Canonical state for the todo tool. Single source of truth — both the reducer
|
|
5
|
+
* (`state/state-reducer.ts`) and the live store cell (`state/store.ts`) read
|
|
6
|
+
* this shape. Replay (`state/replay.ts`) returns a fresh `TaskState`; the
|
|
7
|
+
* lifecycle handlers in `index.ts` write it via `replaceState`.
|
|
8
|
+
*
|
|
9
|
+
* The shape is intentionally minimal — no derived caches or runtime cells.
|
|
10
|
+
* Selectors in `state/selectors.ts` are pure of `TaskState` and own all
|
|
11
|
+
* derivations (visible/grouped/counted/etc).
|
|
12
|
+
*/
|
|
13
|
+
export interface TaskState {
|
|
14
|
+
tasks: Task[];
|
|
15
|
+
nextId: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const EMPTY_STATE: TaskState = { tasks: [], nextId: 1 };
|