/** * The shared session hub: one loaded task record file per session, handed to * every kind of task store. * * Both kinds live in one `tasks.json` (ADR-0005). Loading it once here means a * loop-tool call and a process-task call see the same records, and a save from * either kind writes the whole map — a process task finishing can never drop a * loop record, and a loop update can never drop a process record. * * @author mystery4f <40482524+mystery4f@users.noreply.github.com> */ import { randomInt } from "node:crypto"; import type { TaskScope } from "./runtime-state.js"; import { sessionTaskDirectory } from "./runtime-state.js"; import type { Task, TaskKind } from "./task.js"; import { TaskStore } from "./task-store.js"; /** * One session's loaded records: where they came from, and the map every store * shares, so a save from one kind never drops another kind's record. */ export interface TaskSession { readonly directory: string; /** Every record of the session, both kinds. */ readonly tasks: Map; } /** * A session this extension runs in. Only this kind can be written and only this * kind may be pumped: a session that was merely looked at must never fire, wake * or save. The store lives here rather than on {@link TaskSession} so the wrong * one cannot be persisted by accident — the mistake this split exists to stop. */ export interface OwnedTaskSession extends TaskSession { readonly owned: true; readonly store: TaskStore; } /** * A session that was only looked at: read from disk on request, never adopted by * the hub, never written, and its directory is not even made. */ export interface PeekedTaskSession extends TaskSession { readonly owned: false; } /** What a read path accepts: either ownership, since it only looks. */ export type AnyTaskSession = OwnedTaskSession | PeekedTaskSession; export interface TaskSessionsOptions { /** Clock seam for tests; defaults to `Date.now`. */ now?: () => number; /** Random source for id suffixes; tests pin it to prove collisions are skipped. */ randomInt?: (max: number) => number; } /** No 0/O/1/l: an id is meant to be retyped by a human into a later message. */ const ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"; /** Five random characters after the kind prefix (ADR-0011). */ const ID_SUFFIX_LENGTH = 5; /** * The first characters of an id say which kind of task it names, so a quoted id * (`bg-1a2cf`, `lp-1a2cf`, `lc-1a2cf`, `ch-1a2cf`) is readable without the panel * in front of you. */ const ID_PREFIX = { process: "bg-", "prompt-loop": "lp-", "cmd-loop": "lc-", chain: "ch-", } satisfies Record; export class TaskSessions { private readonly now: () => number; private readonly randomInt: (max: number) => number; /** * Keyed by state directory, not session id: the directory already encodes cwd * and session, and the promise keeps two calls from loading the same history * twice. */ private readonly sessions = new Map>(); constructor(options: TaskSessionsOptions = {}) { this.now = options.now ?? Date.now; this.randomInt = options.randomInt ?? randomInt; } /** * The session's records, adopted by this hub: the map is shared with every * other store, and it may be persisted and fired. Its directory is not made * here — the store makes it when something is actually written. */ session(scope: TaskScope): Promise { const directory = sessionTaskDirectory(scope.cwd, scope.sessionId); const existing = this.sessions.get(directory); if (existing !== undefined) return existing; const opened = this.adopt(directory); this.sessions.set(directory, opened); return opened; } /** * The session's records read from disk without joining the shared map, and * without making its directory. Looking at another session's records goes * through here: a session this extension is not running in must never become * one it holds, pumps or writes. */ read(scope: TaskScope): Promise { return this.peek(sessionTaskDirectory(scope.cwd, scope.sessionId)); } /** * Every session this hub holds, own and merely visited. Work that belongs to no * single turn (a chain step ending) looks a record up here; the loop pump does * not, because a session that was only ever looked at must never be fired. */ loaded(): Promise { // pi-lens-ignore: no-single-promise-in-promise-methods -- a Map's values spread to one promise per session, not a single promise return Promise.all([...this.sessions.values()]); } /** Write the whole record set; queued and best effort in the store itself. */ persist(session: OwnedTaskSession): Promise { return session.store.save([...session.tasks.values()]); } /** * A fresh id that is free in this session, whatever the kind. The prefix * carries the kind and the five random characters keep an id short enough to * retype; the collision check spans the whole id, so kind prefixes never * compete (ADR-0011). Records written before the prefix existed keep their * six-character ids: an id is a reference a later message may quote, and * rewriting one would break that reference. */ createId(session: TaskSession, kind: TaskKind): string { const prefix = ID_PREFIX[kind]; for (;;) { let id = prefix; for (let index = 0; index < ID_SUFFIX_LENGTH; index += 1) { id += ID_ALPHABET.charAt(this.randomInt(ID_ALPHABET.length)); } if (!session.tasks.has(id)) return id; } } /** The records of one directory, with the store that owns the file itself. */ private async fill(directory: string): Promise<{ store: TaskStore; tasks: Map }> { const store = new TaskStore(directory, { now: this.now }); const tasks = new Map(); for (const record of await store.load()) tasks.set(record.id, record); return { store, tasks }; } /** Adopt: keep the store, share the map, and leave the directory to the first write. */ private async adopt(directory: string): Promise { const { store, tasks } = await this.fill(directory); return { directory, store, tasks, owned: true }; } /** * Look: parse the file and keep nothing, so a session this extension is not * running in leaves the filesystem exactly as it was. */ private async peek(directory: string): Promise { const { tasks } = await this.fill(directory); return { directory, tasks, owned: false }; } }