Navigation
ELOWEN · Documentation

Last updated: October 27, 2026

Browse documentation · todo implementation
Developer reference

todo implementation

The manifest declares provides.literalArgumentTools: ["TaskCreate", "TaskUpdate"] because saved task text is reused in turn and step context. At the raw-tool boundary, core preserves every argument instead of persisting substituted vault values; output, error and live-update scrubbing and ordinary access checks remain active. Read/delete tools retain ordinary substitution. This uses the core vault metadata seam without raising the coordinated core 0.30.47 floor with no plugin-owned placeholder parser or extra inference. tests/todoVaultArguments.test.ts loads the real manifest, composes the actual tools with the account vault, checks both SQL writers byte-for-byte and renders subsequent turn context.

Migration entry

The manifest entry exports migrate(db: PluginDb<never>): Promise<void> beside register. The daemon loader always awaits it before registration for this reads: ['db'] plugin; the DB CLI calls the same export without registering tools, routes, timers or services. The export runs transactional plugin SQL through db.migrate, including the one-time legacy ownership cut at version 6. A failed step rolls back its SQL and ledger entry and prevents registration. Repeated calls skip applied versions. Runtime store construction never invokes migrations. Tests that bypass the loader explicitly await this export before using their fixture.

One-time legacy ownership cut

Migration 6 deletes only these historically written non-account shapes, in task_blockers, then tasks, then task_lists:

  • Account predicate: list_key ~ '^u[0-9]+#'.
  • Shared predicate: list_key LIKE 'shared#%'.
  • Platform-sender predicate: list_key ~ '^[a-z][a-z0-9_-]{0,31}:[^#]+#'.

Each table receives one DELETE per legacy shape, and every DELETE explicitly includes AND list_key !~ '^u[0-9]+#'. No account is inferred from a sender or current conversation. After those six deletes, each table is checked with the exact unknown predicate: list_key !~ '^u[0-9]+#' AND list_key NOT LIKE 'shared#%' AND list_key !~ '^[a-z][a-z0-9_-]{0,31}:[^#]+#'. Any unknown row throws and rolls back the entire step. Diagnostics contain only the total unknown row count across the three tables and counts of those rows containing a colon or starting with u; no keys, sessions or sender identifiers are logged. A key present in multiple tables contributes one count per row, not one distinct-key count.

The existing host runner holds its schema advisory transaction lock, rechecks the ledger, awaits the SQL-only migration and inserts elowen.plugin_migrations('todo', 6) in that same transaction. Native SQL errors and unknown-shape refusal leave all three tables and the ledger unchanged and prevent registration. Concurrent/repeated migration calls skip the applied step. Legacy rows inserted after it are not swept: no tool, route or context provider reads, adopts or cleans them. Account rows retain keys, IDs, blocker edges, next_id, timestamps and stored text bytes. Historical core transcript/card snapshots are not plugin list rows and stay intact; a stale card action may answer task-not-found.

Required activation evidence, outside the plugin: count account/shared/platform/unknown rows in all three tables with the predicates above and stop the upgrade for any unknown shape. A live preflight is a warning only, not a stable snapshot. Before candidate startup, quiesce the old daemon and every runner/writer; use one direct, read-only REPEATABLE READ transaction to export the doomed rows from all three tables. Preserve full columns, keys, IDs and edges, table counts, distinct key-set size and timestamp in private recovery storage. Compare exported row counts with the transaction's counts and verify restoration in an isolated scratch database. Repeat eligibility/count checks while still quiesced, immediately before activation; any changed count/key set, unverifiable export or failed restore stops the upgrade. Identify the remaining writer rather than blindly re-exporting. After the authorized startup, verify the version-6 ledger row, zero known legacy rows in all tables and unchanged account rows before accepting the upgrade.

There is no down migration. Recovery is a matched version rollback: stop all writers, restore the old plugin payload and its paired core, then restore the verified exported rows without changing keys, IDs or dependencies. Revert the version-6 ledger entry only as part of that old-version restoration, never alone while new code is deployed. Before accepting work, verify the old runtime serves and can update a restored list. A code-only rollback does not recover deleted data. Operator export/quiescence/restore and deployed UI evidence remain separate release gates; fixture tests do not satisfy them.

tests/todoLegacyCut.test.ts uses the real host migrator and disposable PostgreSQL fixtures to prove selectors, preservation, ledger idempotence, unknown-row rollback and native SQL failure rollback. tests/todoApiIdentity.test.ts checks canonical tool/API parity, accountless refusal, human-only mutations and absence of per-turn host-store access.

Browser display contract

The coordinated browser cut requires UI API 73 and a matching Todo bundle. The registration claims only chatRailCards: { todo: ['todos'] }; source and manifest require that same API. Historical handleless or partially addressable rows remain visible as read-only content rather than disappearing. Only the host's addressability guard enables mutations. The host's ElowenUiRuntime.utils.cardTasks([card], 'todos') projects the pushed Todo card once, preserving owner, unresolved blockers, running labels and measured times. The card uses that helper and the host's cardTasksAddressable guard; the rail passes the host's already-projected TaskRailData.tasks directly to TaskList. Neither surface reinterprets glued text or polls the task route. The host normalizes incoming plugin cards at the emit boundary; the rail payload is internal host data. Missing cards yield no rows and empty or partially unaddressable lists have no interactive controls. The projection is linear in the supplied cards and Todo rows and adds no network request. Missing or incompatible bundles retain the host's fallback. The Tasks management picker still reads its authorized route on demand.

The browser bundle requires the host's hooks.useNow member. TodoCard calls hooks.useNow(1000, enabled) only for a live card with a running timestamp; the rail subscribes while one of its rows has a running timestamp. One host heartbeat serves both surfaces, pauses notifications while the tab is hidden, catches up on visibility and stops after the last subscriber leaves. The rail evaluates the current time on each render, including the render requested by a status action. No plugin timer or network request is added. A host missing the hook fails explicitly instead of starting a local clock. Registry UI tests install the candidate's actual hook.

The runtime narrowing uses the published kit's task-row, rail and projection types; no old-kit compatibility mirror remains. UI tests use a test-only host projection port, never plugin logic.

Browser data ownership

web-src/taskData.ts owns Todo's REST rows, patch DTO, one list query and three mutations. TasksPicker reads the selected session and uses all three mutations; TodoCard and TasksRail only mutate their passed session and keep rendering pushed rows. They never GET a list just to render a card or rail, including a child transcript. A null session disables the list query and exposes no task mutation controls.

The module calls only runtime().api(path, init) and the host's generic useQuery, useMutation and useQueryClient, with their published native React Query types. The host owns authentication, account-generation rejection, HTTP errors and the single cache; no plugin QueryClient, fetch wrapper, token, retry loop or account identity reconstruction is introduced. Paths omit the BFF /api prefix; JSON writes use { method: 'PATCH', json: body }.

  • GET /plugins/todo/api/tasks?session=<encoded> returns { tasks }.
  • PATCH /plugins/todo/api/task?session=<encoded> sends { taskId, ...patch } and returns { task, tasks }; patch fields are status, subject and owner, with no bare-status overload.
  • DELETE the task path adds encoded taskId and returns { success, taskId, tasks }.
  • DELETE the tasks path adds scope=completed|all and returns { success, removed, tasks }.

The local SessionTask preserves the server's complete row: id, subject, private description, activeForm, status, startedAt, durationMs, completedAt, owner, metadata, metadataCorrupt, blockedBy and blocks, with optional fields remaining optional. It is separate from the host's public display-row contract.

All operations retain ['session-tasks', sessionId]. Before a PATCH, cancel that session's query, capture its snapshot and optimistically apply only supplied status/subject/owner fields. A null or empty owner becomes absent on the cached row. Rejection restores the snapshot; settlement invalidates that exact session. Successful delete/clear invalidates the same key. Other sessions and other rows stay unchanged. Without a mounted consumer there is no request; errors remain errors rather than fabricated empty lists.

tests/todo-client.test.tsx carries wire encoding, patch-object, owner-clear, rollback, shared-cache, session-isolation and invalidation regressions formerly owned by core's task client/mutation tests. Both it and tests/todo-tasks-ui.test.tsx remove private Todo hooks from the test host, so copied host domain hooks cannot make a broken plugin pass. Clock/blocker, read-only, confirmation and error assertions stay with the actual plugin surfaces. Removing old core hooks requires the paired artifact update and content-hash reload: a minimum API number does not itself reject an old bundle on a newer host.

Storage contract

The pure root apiContract.mjs exports apiRoutes for all four registrations. Descriptors own method, path, access, summary, canonical Zod wire inputs or null, existing credential policy and JSON transport. lib/tasks.mjs spreads them and parses through the exact registered schema instances at the original read sites. The contract imports no store, handler or startup code. Its body transform owns the existing HTTP patch normalizer, including ordered field refusals and ignored unknown fields. The shared control-character validator lives in the existing pure common module and is used by both this parser and TaskStore; tool and HTTP writes retain one rule without importing persistence into the contract.

Mutations evaluate the host-bound lazy req.credentialsAllowed() at the original agent gate, before query or JSON parsing, and retain the same custom 403. GET permits agents; personal API tokens remain permitted for mutations. JSON syntax errors still return 400 { error: 'invalid JSON' }; invalid fields keep their specific 400 messages, and store failures are not relabeled as generic validation.

All three mutating HTTP handlers await ctx.writeCard after committing their task changes. A rejected panel write logs todo.panel_write_failed before returning the successful mutation response, including a clear request for a missing conversation.

The internal lib/taskStore.mjs module owns the native PostgreSQL migration, task rows, dependency graph, metadata and completed-list aging. The host awaits the entry export migrate(db) before registration; registration awaits ctx.db() and constructs TaskStore before publishing tools, routes or context providers. Every database operation returns a Promise and uses only PluginDb.query, one, run and the transaction-bound handle. SQL explicitly qualifies the quoted host-selected db.schema; there is no session search path. Account and conversation authorization stays at the registration boundary: listKey(ctx, sessionId) derives u<account>#<session> exclusively from the awaited ctx.currentAccountUserId(). Tools pass the current conversation; HTTP handlers pass the trimmed, non-empty query session (at most 256 characters). The authenticated dispatcher already supplies the account scope, so HTTP never derives ownership from req.auth.userId. Delegated turns retain their canonical contribution account; no plugin identity, platform or shared fallback exists and no per-turn host-store lookup is added.

Without an account, every task tool refuses with a task list needs an account, both context providers return an empty string and HTTP answers 403 { error: 'tasks need an account' }. The HTTP branch is reachable during first-run setup before any account exists; after the first account the host refuses unauthenticated requests before dispatch. Missing-conversation tool behavior remains unchanged. The three mutating HTTP handlers evaluate the host-bound req.credentialsAllowed() at their existing agent gate and reject agent credentials with 403 { error: 'tasks can only be changed from the app' } before parsing or writing. Agent GET remains allowed, and browser, CLI login and personal API-token mutations retain their ordinary account checks. This guard does not replace tool admission or the host's route access policy.

The PostgreSQL baseline creates task_lists, tasks and task_blockers in plugin_todo, with a unique row_id bigint identity on each table for bounded cleanup. started_at and completed_at are timestamptz; the store returns milliseconds to existing consumers, and duration_ms remains bigint. The five existing schema steps retain ledger versions 1–5 unchanged; version 6 is the data-only ownership cut described above. The host ledger controls whether each step applies. Completed rows written before completion times were recorded keep a null completed_at. metadata_json stays text because unreadable stored bytes have an explicit preservation contract.

Completion records the time once; a repeated completed update or label edit does not restart it, and reopening clears it. ageCompletedAtTurnBoundary uses the live completedRetentionHours setting with its 4-hour default and 1–168-hour bounds, pruning only dated expired completed rows in the current conversation through the existing transactional deletion owner. It removes resolved edges and retains the list's monotonic ID counter. The all-completed grace still uses the existing turn count. Mid-turn rendering remains read-only. Before a write, aging reads the list and eligible task state. A missing list, an empty list with a zero grace counter, or unfinished work with no expired completion and a zero counter takes no write transaction. The turn-context provider awaits aging and its refreshed snapshot. All conditions are read again after acquiring the list row with SELECT FOR UPDATE; expired task and edge deletion uses that same transaction without nesting.

Registration uses ctx.registerUserRemoved to await TaskStore.removeUser(userId). Account lists have the exact u<id># key prefix. Indexed range predicates preserve other accounts. The shared drainDbRows seam receives schema: db.schema, the unqualified table name, identity: 'row_id', PostgreSQL $1 range parameters and an octet_length byte estimate. It removes dependency edges, tasks and list counters in that order, with at most 64 rows or 256 KiB per transaction and a yield between batches. Failures propagate to the host; a later invocation drains remaining rows. There is no core conversation-removed seam, so deleting a conversation does not remove its Todo rows.

Todo registers its step provider with afterTools naming TaskCreate, TaskUpdate and TaskDelete. Core owns the administrator interval, native provenance, restoration and activity gate. The provider emits conditional reconciliation guidance and a public ID/status/subject snapshot bounded below 900 bytes, omitting private descriptions and metadata. Core retains its 1024-byte final clamp and append-only prompt-cache behavior. Both context providers return Promises. The step provider captures its account and conversation on entry, then awaits a read-only snapshot; it never ages tasks or emits cards.

Batch creation, updates, deletion, clearing and aging lock the same list row before reading mutable task or graph state. Creation inserts the counter with ON CONFLICT DO NOTHING before locking, so simultaneous first batches reserve disjoint task IDs and choose at most one implicit running task. The lock protects partial metadata updates and cycle checks across awaits. Graph traversal stays inside the store, and HTTP and tool entry points share its control-character rule. Public list reads load tasks and edges in one read-only REPEATABLE READ transaction; mutation reads reuse their existing locked transaction. An unreadable metadata column is logged once per task and store instance and left byte-for-byte intact by unrelated updates; an explicit metadata patch replaces it.

The repository-level tests/todo-write-locks.test.mjs exercises idle-turn write avoidance, completed-list aging and bounded account cleanup. tests/todoConcurrency.test.mjs interleaves real transactions to pin ID allocation, partial updates, cycle rejection and snapshot consistency. Every todo database suite takes the repository's shared fixture, tests/helpers/pluginDb.mjs, which supplies the plugin database host binding, an independent database per fixture and its own pool and clone cleanup; it loads through the repository's register loader, so the normal node test command needs no core build. Set ELOWEN_CORE_ROOT to the candidate checkout. The existing node-test glob runs these files; no production module imports the fixtures. The main Vitest configuration resolves host modules to candidate source for the session-isolation and real-TypeBox suites, using the same PostgreSQL setup as the other adopted suites.

Rendering and update contracts

Import xmlEscape from elowen-plugin-shared/xml and call xmlEscape(value) when rendering XML text or attributes. It replaces XML 1.0-forbidden C0 characters, escapes markup and both quote kinds, and preserves Unicode, tab, LF, CR and DEL. It acts only at the XML rendering boundary and does not change stored values or network behavior. It is not single-line label validation: Todo still rejects controls in subjects and owners. Todo's turn context and Twilio's Stream URL attribute are real consumers. The runtime and declarations must be present in the containing core artifact.

Todo task diagnostics use errorText from elowen-plugin-shared/errors. errorText(error) retains Error.message and otherwise uses String(error); conversion failures propagate. It formats only an existing failure and does not log, retry or invent a success result. TaskStore owns UPDATABLE_FIELDS for both update admission and TaskUpdate's corrective hint: supplied scalar fields count as an update, while dependency arrays must be non-empty. Unknown tool keys remain ignored and a patch without a supported change is refused before persistence.

Todo's task picker mounts the shared Modal without the retired intent prop; the host owns overlay presentation and focus. In the turn context, at most 10 finished tasks are listed one by one; older finished tasks fold into one counted line, and their rows and IDs remain until the completed-list grace period ends.

Blockers and list rendering

The internal taskStore module exports unresolvedBlockers(blockedBy, statusById). Build one Map from task IDs to statuses for the current list and pass each row's blockedBy IDs to it. Only completed blockers are resolved; absent IDs remain unresolved, and an empty blocker list returns an empty array. TaskList, the next-runnable hint, taskCard, stalled-list reminders and batch creation use this same rule when producing their output or selecting initial work. The index is local to that operation, with linear setup cost and one lookup per dependency; it adds no query, persistent cache, timer or network request. taskCard is a real consumer and reuses the index for all rows.

The renderer's private displayLabel selects activeForm only for in-progress work with a non-empty activeForm, otherwise subject. taskCard keeps that label unbounded locally. The step snapshot uses public subjects capped at 70 code points. A list with no pending or in-progress task produces no step reminder. The snapshot's anomaly line uses the same counts and blocker index as the turn context. Rendering adds no I/O.

The Todo browser runtime declares only utilities it consumes; duration rendering belongs to the host TaskList and TaskRow components, not to a plugin-local formatDuration requirement. TasksRail uses the required railTitle string supplied by the manifest and cs/sk translations for both compact and expanded displays. Empty and fully completed lists remain hidden. The existing useNow heartbeat and read-only behavior without a sessionId remain unchanged; no timer or request is added. TasksRail is the real consumer of the title and host task-list contract.

Turn context reminders

A task that stays in progress for 20 minutes or more is flagged in the agent's turn context so the agent can confirm the work still matches the task. The flag changes no task state and issues no query.

The existing administrator reminder interval also controls Todo's sparse reminders. On a host with activity-based context it counts assistant messages since both a task mutation and the previous reminder; parallel calls count as one message, and thinking-only messages and list reads do not reset task activity. The reminder carries a bounded public snapshot, open work first, with a pointer to TaskList when more tasks exist, and stays within 900 bytes. A list with no pending or in-progress task produces no reminder. An older host retains its original tool-call cadence.

Next: Voice Calls