@raea/task and docs/plan.feature: a project's plan.org as typed tasks, read and written by task id (#154)

sdk/task reads and writes a project's plan.org (Org mode) as typed tasks: keywords, properties, kinds and views a plugin can add, React hooks and components. docs/plan.feature files the plan work, landed for 0.1.4. The skills submodule moves to raea-skills e249001 (#75: section 0 step 5, open or start the project's plan).
This commit is contained in:
shane authored and GitHub committed 2026-11-14 21:48:16 -05:00
1 parent 4d7fa914cc
commit d870159c46
19 files changed
+2224 -1

No files matched your search

+200
View File
@@ -0,0 +1,200 @@
@spec
Feature: Plans: a project's plan.org, kept by its agents
Shane, 2026-11-14: "create a subagent that can flesh out the skills needed for tasks/plannig to be fully carried out
by the agent right now its just blank and even if user doesnt touh it we need to have the againt use and maintain it
and actualy use it for project managemtn and make that project managemnt system extensible with the task SDK. as a
personal notel i liek or mode for managing projects so id liek to have that eb part of the base layer and make sure
it integrates well with typescript/react/jsx correctly and the larger project in a way that is integral to the system"
"or mode" is Emacs org-mode. A project's plan is one Org file, plan.org. It is the base layer: the app, raea's own
agents, agents outside raea (Claude Code in a terminal) and people in Emacs all read and write the same plain text.
The to-do list was blank because nothing wrote to it but the composer; now every agent plans in it, marks what it's
doing and closes what it made, whether or not the person ever opens it. @raea/task (sdk/task) reads and writes the
file without losing a byte, edits it by task id, lets a plugin add keywords, properties, kinds and views, and gives
React its hooks and components.
# Status 11-14: landed for 0.1.4. sdk/task (@raea/task) and this file in raea; the app in raea-feed (tasks-org merged
# into integration-014 at 1214a21: vitest 242 files, 1509 tests, e2e todo, outside, messages, primary, heads,
# consolidate 36 of 36); the skill in raea-skills #75 (skills/raea/plan.md).
# Checked after the review: sdk/task 32 bun tests (org, edit, extend, tools), 35 with its react
# tests under the app's vitest; the app's vitest 237 files, 1458 tests (base 229 files, 1403 tests, the same skips),
# src/plan/agent.test.ts driving a turn's plan tools end to end on a faked host; tsc -b clean; e2e todo.spec.ts and
# outside.spec.ts (7) and messages, primary, heads, consolidate (26) in Chrome; todo.spec.ts (4) and outside.spec.ts
# (3) in raea's window (BLITZ_E2E bundle, node blitz/pw-run.mjs). The board (feed/Board.tsx, board/Lanes.tsx,
# board/CardSheet.tsx) reads the plan now, but no route mounts it. Not done: `raea project new` writes no plan.org yet
# (Rust, engine/cli), so reference/files.md, generated from it, doesn't list one; the page makes it on the first
# write. The brief page (BriefView, unmounted) still draws a brief's own ## Tasks. Compositions can't import
# @raea/task until sdk/tsconfig.base.json and raea's bundler map it.
Background:
Given the app's code is apps/app (raea-feed), the SDK sdk/task, the skill skills/raea/plan.md in raea-skills
And the plan's tests: sdk/task/test/*.test.ts (PL2, PL3, PL5, PL6), apps/app src/plan/plan.test.ts (PL1c, PL4, PL4c,
PL5), src/plan/agent.test.ts (PL5a, PL5b), host/plan.test.ts (PL4, PL5), src/feed/todo.test.ts and outside.test.ts
(PL4b), e2e/todo.spec.ts (PL4b)
Rule: PL1. A project's plan is plan.org at the top of its folder
# Why there: it's the project's own file, versioned with it in the workspace's repo, found by anyone who opens the
# folder (a person, Emacs, an agent in a terminal). Not under .raea/, which is raea's state, not the person's. One
# file a project: the Inbox reads each project's in turn.
@done
Scenario: PL1a. The file says its title and raea's keywords
Given a project with no plan.org
When anything adds a task to it (the to-do list, the composer, an agent's plan_add)
Then <project>/plan.org is made, starting "#+TITLE: <project's name>" and "#+TODO: TODO MAKING REVIEW | DONE DROPPED"
And an Org reader (Emacs) cycles the same keywords: TODO, MAKING and REVIEW are open, DONE and DROPPED closed
And a keyword written into a plan whose #+TODO: lines don't name it (MAKING in a file written by hand, a plugin's
SHOT) adds its sequence's #+TODO: line to the head, so Emacs cycles it too; Org's own TODO and DONE need none
@done
Scenario: PL1b. The Org it uses
Given a plan.org
Then a headline with a keyword is a task; a headline with none is a heading: a stage that groups the tasks under it
And a task may carry a priority ([#A]), tags (:look:sound:; a dash is written _), a planning line (SCHEDULED,
DEADLINE, CLOSED), a PROPERTIES drawer, checkboxes (- [ ], - [X]), a progress cookie ([2/5] or [40%]) and links
And its properties are :ID: (t- and eight letters and digits), :ITEM: (the feed item it stands on), :AGENT: (who
has it), :FROM: (what asked for it), :KIND: and :VERB:; any other property is kept as written
And links name feed items and tasks by id: [[item:i-door-2]], [[id:t-ab12cd34]]
And a subtask is a task under a task; its parent's cookie counts its subtasks, or with none its checkboxes
@done
Scenario: PL1c. Everything is linked by id, never by name
Given a task typed with "@grade #look due 11-20 → i-hall" (the to-do list, the composer)
Then :AGENT: holds the agent's id; an @name no agent has yet is kept as @name, and shows that name
And :ITEM: holds the item's id, the tags are the task's tags, and DEADLINE is that day this year
And a task the composer writes for a message has :FROM: the message's id; one for a comment, ITEM#COMMENT
Rule: PL2. @raea/task reads a plan without losing a byte
@done
Scenario: PL2a. A round trip changes nothing
Given any text, Org or not: drawers it doesn't know, #+BEGIN blocks, tables, CRLF endings, tabs, no final newline
When it's read and printed with no edits
Then the text is the same, byte for byte
And a planning line with a stamp it can't wholly read (a range of days, a habit's .+2d/3d) is still the planning
line: the drawer under it, and its :ID:, are read, and the part it couldn't read is written back as it was
@done
Scenario: PL2b. A plan as values
Given a plan.org
Then readPlan gives every headline as an entry and the ones with a keyword as tasks, each with its state (todo,
making, review, done, dropped, whatever its keyword is called), priority, tags and inherited tags, dates,
properties, item, agents, from, parent and children, its stage, checkboxes, progress, links and body
And a plan's own #+TODO: lines add keywords; a word a plugin defined keeps its plugin's state
@done
Scenario: PL2c. A changed entry is written again part by part
Given an edit that changes one task's keyword
Then only its headline line is written again; its drawer, body and every other entry are as they were
And the headline keeps its own spacing and its tags end where they ended, as Org's org-todo leaves them; a
planning line written again keeps its parts' order, with a new CLOSED first
Rule: PL3. Every change is an edit by task id
@done
Scenario: PL3a. The edits
Then applyEdits(text, edits) makes add, set, state, move, remove and check, in order, each naming its task by
:ID: (or #N, its place among the headlines, for one that has no id yet)
And add goes under a heading by its words (made when there's none), under a task (a subtask), or before or
after a task; with none of them, at the end
And every task is given an :ID: it lacks, and every progress cookie counts again
@done
Scenario: PL3b. Closing stamps CLOSED; reopening takes it off
When a task's state becomes done or dropped
Then its planning line gets CLOSED: [YYYY-MM-DD Day HH:MM], as Org's org-log-done does
And opening it again removes CLOSED
@done
Scenario: PL3c. A wrong edit changes nothing
When an edit names a task that isn't there (under: a task id included, which never becomes a stage heading), a
day that isn't one, a keyword the plan doesn't know or a move into the task's own subtree
Then applyEdits throws, saying what's wrong and how to find the right id, and the text is as it was
Rule: PL4. The app keeps its tasks in the plan
@done
Scenario: PL4a. The host reads and writes plan.org whole
Given POST /host/plan {op: read | apply | put, workspace, project}
Then read answers the text and a stamp (same: true when the page's stamp still holds); a read for an agent
(name: true: its turn, its plan_read) first gives each task written without an :ID: one, and writes it
And apply makes the edits on the file (or on a new plan) and writes it through a temporary file, renamed over,
answering with the text they were made on; edits naming a task by its place (#N) carry the text that place
was counted in, and are refused when the file has changed since
And put writes an older text back for Undo only while the file is still the text the page last saw
And the e2e host (RAEA_FEED_KEEP=0) keeps nothing: the page's plan is the plan
@done
Scenario: PL4b. The to-do list, the composer and raea's own work write plan edits
Given the to-do list (feed/TodoPanel.tsx) open on a project or the Inbox
Then its rows are the plan's tasks as written (subtasks too) and the edits sent on the project's items
And a task linked to an item stands where the item does (the work is the truth)
And add, check off, reword, reorder and remove are plan edits made at once in the page and then on the file
And Undo puts the text back only while the plan hasn't changed since ("The plan has changed since: nothing
undone"), and puts back the file as the edit found it, so a task another writer added before the edit stays
And the list reads the plan again every few seconds and on focus, so an edit in Emacs or a terminal shows; an
agent's turn and its plan_read read it again first
And a message sent in the composer is a task in the plan: after the last task carrying the view's tags, held by the
agent it went to, :FROM: the message's id
And raea's shaping, storyboards, directions and renders are its tasks under Plan and Make, each :ITEM: the card it
waits on; a critique's gate is "<title> passes check and critique" with :ITEM: the newest critique
And an item carries the tags of the tasks linked to it, a workflow field places a channel by its plan's tasks, and
a session outside raea holds the tasks whose :AGENT: is @its-name or its inbox
And the board (feed/Board.tsx, board/Lanes.tsx, board/CardSheet.tsx) reads and edits the plan the same way, by
task id; no route mounts it yet
@done
Scenario: PL4c. A brief's tasks move into the plan once
Given a project whose brief.md still has ## Tasks (every brief before this, and the starter brief's "Write the plan")
When the page has read its kept brief
Then each task is added to the plan with its mark as its keyword, its ### stage as its heading, its @agents by id,
its #tags, its due day as DEADLINE, its → item as :ITEM: and its craft verb as :VERB:
And the task lines, the stages and an emptied ## Tasks leave the brief; everything else in it stays
And a brief the plan can't take (the host refused the write) keeps its tasks, and is tried again next load
And each task's id comes from its stage, its words and which of the same words it is, so a brief moved twice (two
pages open on it, a reload before the brief was saved) adds nothing the second time
@done
Scenario: PL4d. Comment tasks stay where they are
Given an edit sent on an item (model/tasks.ts, raea show --working/--done)
Then it is not copied into the plan; it shows in the same to-do list, under the plan's tasks, as it did
Rule: PL5. Agents use and maintain the plan, whether the person opens it or not
@done
Scenario: PL5a. The plan tools
Given an agent the raea app launches (the feed MCP server, apps/app host/acp/feed-mcp.ts)
Then it has plan_read (the open tasks by id; full: the whole file), plan_add (tasks under a stage or a task,
held by the agent unless it names others), plan_update (mark, tick or add a checkbox, change fields, move,
remove) and plan_close (DONE with CLOSED and the item it made, or dropped)
And the page answers them through its plans (@raea/task answerPlanTool), a headless run (host/acp/memory.ts) on
the folder's plan.org; a session with no project has no plan, and says so
@done
Scenario: PL5b. Every turn carries the plan
Given an agent's turn in a project (src/acp/session.ts prompt)
Then the prompt carries raea://plan/<project>: the rule to keep the plan, the task this message is (by :FROM:),
and the open tasks by id under their stages (planDigest)
And the rule: plan work of more than one step first, mark a task MAKING as you start it and REVIEW when it waits
on the person, close it as you finish with the item it made, add what's left, drop rather than remove
And every task it names has an id: a task written without one is given one before the plan is read for the turn
And an agent launched without the plan tools is told to keep plan.org as text; a message whose task is already
closed says so, rather than asking for it to be marked
Scenario: PL5c. An agent outside raea keeps the same file
Given Claude Code in a terminal in the project's folder, with the raea skill
Then it opens plan.org (skills/raea/plan.md), plans and marks there as plain Org text, keeping each :ID:
And the person sees its changes in the to-do list within a few seconds
Rule: PL6. A plugin extends plans; React and raea's window read them
@done
Scenario: PL6a. Keywords, properties, kinds and views
Then defineKeywords adds a sequence ("SHOT LIT GRADED | APPROVED") with each word's state; defineProperty a
property with a check; definePlanKind a kind (its keywords, required properties, a check, defaults an add
starts with; a new task of the kind starts at its sequence's first word); defineView a view any page can
build (view(plan, name)); createRegistry one of a plugin's own
And checkPlan says what's wrong by those rules: ids used twice, failing properties, unknown kinds, missing
properties, keywords outside a kind's sequence
And board, agenda and outline are the views raea ships
@done
Scenario: PL6b. React
Then usePlan(text or source) gives the plan, its text and edit; useView a registered view; TaskLine, PlanOutline,
Agenda and BoardLanes draw them, with toggled for a checkbox's edit
And none of it uses a dynamic import or dangerouslySetInnerHTML, so raea's window bundle (one IIFE) holds it
+18
View File
@@ -0,0 +1,18 @@
{
"name": "@raea/task",
"license": "FSL-1.1-ALv2",
"private": true,
"version": "0.1.0",
"description": "raea's plans and tasks (docs/plan.feature): a project's plan.org read and written losslessly, its tasks as typed values, every edit by task id, keyword sequences, properties, kinds and views a plugin can add, and React hooks and components. No runtime dependencies; React only for ./react.",
"type": "module",
"main": "src/index.ts",
"exports": {
".": "./src/index.ts",
"./org": "./src/org.ts",
"./react": "./src/react.tsx"
},
"scripts": {
"test": "bun test test/org test/edit test/extend test/tools"
},
"peerDependencies": { "react": "19.2.0" }
}
+37
View File
@@ -0,0 +1,37 @@
// A plan in a few lines for an agent's prompt (docs/plan.feature PL5): the open tasks with their ids, keywords,
// priorities, dates and links, under the headings they sit in, and how many are done. An agent reads this each turn
// and edits the plan by those ids.
import { isClosed, openTasks, type Plan, type Task } from "./model.ts"
/** One task as a line: its id, keyword, priority, words, tags, dates, item and who has it. */
export function taskLine(t: Task): string {
const bits = [t.ref, t.keyword ?? "", t.priority ? `[#${t.priority}]` : "", t.text]
if (t.tags.length) bits.push(`:${t.tags.join(":")}:`)
if (t.deadline) bits.push(`DEADLINE ${t.deadline.date}`)
if (t.scheduled) bits.push(`SCHEDULED ${t.scheduled.date}`)
if (t.progress) bits.push(`[${t.progress.done}/${t.progress.total}]`)
if (t.item) bits.push(`item ${t.item}`)
if (t.agents.length) bits.push(`agent ${t.agents.join(" ")}`)
if (t.from) bits.push(`from ${t.from}`)
return bits.filter(Boolean).join(" ")
}
/** The open tasks under their headings, at most `max` (40) of them, and a count of the closed ones. */
export function planDigest(plan: Plan, o: { max?: number } = {}): string {
const open = openTasks(plan)
const max = o.max ?? 40
const lines: string[] = []
let stage: string | undefined
for (const t of open.slice(0, max)) {
if (t.stage !== stage) {
stage = t.stage
if (stage) lines.push(`${stage}:`)
}
lines.push(`${" ".repeat(Math.max(0, t.level - 1))}- ${taskLine(t)}`)
}
if (open.length > max) lines.push(`... and ${open.length - max} more open`)
const closed = plan.tasks.filter((t) => isClosed(t.state)).length
if (!open.length) lines.push("No open tasks.")
if (closed) lines.push(`${closed} closed (done or dropped).`)
return lines.join("\n")
}
+357
View File
@@ -0,0 +1,357 @@
// Every change to a plan, as data (docs/plan.feature PL3): add, set, state, move, remove and check, each naming its
// task by :ID: (or #N for a headline that has none yet). applyEdits reads the text, makes the edits in order, gives
// every task an :ID: it lacks, brings progress cookies up to date and writes the text back; what no edit touched is
// as it was, byte for byte. The page, the host's tools and an agent's own script all change a plan this way.
import { plans, STATES, type PlanRegistry } from "./extend.ts"
import { isClosed, readPlan, type Plan, type State } from "./model.ts"
import { bare, checksOf, COOKIE, fileSequences, lineOf, printOrg, setCheck, type OrgDoc, type Planning, type Section } from "./org.ts"
import { dayOf, nowStamp } from "./time.ts"
export interface TaskFields {
title?: string
/** A, B or C (any capital or digit); null takes it off */
priority?: string | null
/** replaces its tags */
tags?: string[]
/** YYYY-MM-DD, MM-DD or an Org timestamp; null takes it off */
deadline?: string | null
scheduled?: string | null
/** the feed item it stands on */
item?: string | null
/** who has it, by agent id; [] takes them off */
agents?: string[]
from?: string | null
kind?: string | null
verb?: string | null
/** any other property; null takes it off */
props?: Record<string, string | null>
/** a line of text added under it */
note?: string
}
export type PlanEdit =
| ({ op: "add"; title: string; id?: string; state?: string; under?: string; before?: string; after?: string; checks?: string[] } & TaskFields)
| ({ op: "set"; ref: string } & TaskFields)
| { op: "state"; ref: string; state: string; item?: string; note?: string }
| { op: "move"; ref: string; before?: string; after?: string; under?: string }
| { op: "remove"; ref: string }
| { op: "check"; ref: string; index?: number; done?: boolean; add?: string }
export interface ApplyOptions {
now?: Date
newId?: (taken: ReadonlySet<string>) => string
registry?: PlanRegistry
}
export interface Applied {
text: string
/** each edit's task by its :ID: (an add's new id; a removed task's id as it was) */
refs: string[]
plan: Plan
}
/** A new task id: t- and eight letters and digits, unused in `taken`. */
export function newId(taken: ReadonlySet<string> = new Set()): string {
for (;;) {
const id = `t-${(Date.now() % 1e9).toString(36).padStart(6, "0")}${Math.floor(Math.random() * 1296).toString(36).padStart(2, "0")}`
if (!taken.has(id)) return id
}
}
/** A tag as Org reads one: letters, digits, _ @ # %. Anything else (a dash, a space) becomes _. */
export const tagOf = (s: string) => s.trim().replace(/^[#:]+/, "").replace(/[^\p{L}\p{N}_@#%]+/gu, "_").replace(/^_+|_+$/g, "")
/** The edit a checkbox makes: a closed task opens again, an open one is done. */
export const toggled = (t: { ref: string; state?: State }): PlanEdit => ({ op: "state", ref: t.ref, state: isClosed(t.state) ? "todo" : "done" })
/** A new project's plan: its title, and raea's keywords spelled out for Emacs and any other Org reader. */
export const newPlan = (title: string) => `#+TITLE: ${title.replace(/\s+/g, " ").trim()}\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n\n`
const oneLine = (s: string) => s.replace(/\s+/g, " ").trim()
const propOf = (s: Section, key: string) => s.props?.find(([k]) => k.toUpperCase() === key)?.[1]
function setProp(s: Section, key: string, value: string | null | undefined) {
const k = key.toUpperCase()
if (!/^[A-Z][\w-]*$/.test(k)) throw new Error(`a property is one word: ${key}`)
const at = s.props?.findIndex(([x]) => x.toUpperCase() === k) ?? -1
if (value === null || value === undefined || value === "") {
if (at >= 0) s.props = s.props!.filter((_, i) => i !== at)
if (s.props && !s.props.length) s.props = undefined
return
}
const v = oneLine(value)
if (at >= 0) s.props = s.props!.map((p, i) => (i === at ? [p[0], v] : p))
else s.props = [...(s.props ?? []), [k, v]]
}
/** A line added to an entry's own text, before the blank lines that end it. */
function addLine(doc: OrgDoc, s: Section, text: string, after?: number) {
let at = after ?? s.body.length
if (after === undefined) while (at > 0 && !bare(s.body[at - 1]).trim()) at--
s.body = [...s.body.slice(0, at), lineOf(doc, text), ...s.body.slice(at)]
}
interface Ctx {
doc: OrgDoc
words: Map<string, State>
now: Date
reg: PlanRegistry
mint: () => string
/** the headlines as they were before any edit, for #N */
initial: Section[]
}
/** The keyword for a state or a keyword: a plan's own #+TODO: words first, then raea's. */
function wordFor(c: Ctx, want: string): string {
if (c.words.has(want)) return want
if (c.words.has(want.toUpperCase())) return want.toUpperCase()
const state = want.toLowerCase() as State
if (!STATES.includes(state)) throw new Error(`${want} is neither a keyword nor a state: ${[...c.words.keys()].join(" ")}, or ${STATES.join(", ")}`)
for (const s of fileSequences(c.doc.head)) for (const w of [...s.open, ...s.done]) if (c.words.get(w) === state) return w
for (const [w, st] of c.words) if (st === state) return w
throw new Error(`no keyword in this plan means ${state}`)
}
/** The headline a ref names: an :ID:, or #N as the plan was before these edits. */
function find(c: Ctx, ref: string): Section | undefined {
const n = /^#(\d+)$/.exec(ref)
if (n) {
const s = c.initial[Number(n[1])]
return s && c.doc.sections.includes(s) ? s : undefined
}
return c.doc.sections.find((s) => propOf(s, "ID") === ref)
}
function must(c: Ctx, ref: string): Section {
const s = find(c, ref)
if (!s) throw new Error(`no task ${ref} in the plan; read the plan for its tasks' ids`)
return s
}
/** A heading by its words (no keyword), made at the end of the plan when there's none. */
function heading(c: Ctx, title: string): Section {
const words = oneLine(title).toLowerCase()
const had = c.doc.sections.find((s) => !s.keyword && oneLine(s.title).toLowerCase() === words)
if (had) return had
const s: Section = { level: 1, title: oneLine(title), tags: [], planning: {}, body: [] }
c.doc.sections.push(s)
return s
}
/** Where a headline's subtree ends: the next headline at its level or above. */
function subtreeEnd(doc: OrgDoc, at: number): number {
const level = doc.sections[at].level
let end = at + 1
while (end < doc.sections.length && doc.sections[end].level > level) end++
return end
}
function fields(c: Ctx, s: Section, f: TaskFields) {
if (f.title !== undefined) {
const t = oneLine(f.title)
if (!t) throw new Error("a task needs words")
s.title = t
}
if (f.priority !== undefined) {
const p = f.priority?.trim().toUpperCase()
if (p && !/^[A-Z0-9]$/.test(p)) throw new Error(`a priority is one letter or digit (A, B, C): ${f.priority}`)
s.priority = p || undefined
}
if (f.tags) s.tags = [...new Set(f.tags.map(tagOf).filter(Boolean))]
for (const k of ["deadline", "scheduled"] as const) {
const v = f[k]
if (v === undefined) continue
const { [k]: _, ...rest } = withoutRaw(s.planning, k)
if (v === null || v === "") {
s.planning = rest
continue
}
const t = dayOf(v, c.now)
if (!t) throw new Error(`${k}: a day as YYYY-MM-DD (or MM-DD this year): ${v}`)
s.planning = { ...rest, [k]: t }
}
if (f.item !== undefined) setProp(s, "ITEM", f.item)
if (f.agents) setProp(s, "AGENT", [...new Set(f.agents.map((a) => a.trim()).filter(Boolean))].join(" "))
if (f.from !== undefined) setProp(s, "FROM", f.from)
if (f.kind !== undefined) setProp(s, "KIND", f.kind)
if (f.verb !== undefined) setProp(s, "VERB", f.verb)
for (const [k, v] of Object.entries(f.props ?? {})) setProp(s, k, v)
if (f.note?.trim()) addLine(c.doc, s, oneLine(f.note))
}
/** A planning line without the parts of one key that raea kept as written: a value set for that key replaces them. */
function withoutRaw(p: Planning, key: keyof Omit<Planning, "rest">): Planning {
const rest = p.rest?.filter((r) => !r.toLowerCase().startsWith(`${key}:`))
const { rest: _, ...out } = p
return rest?.length ? { ...out, rest } : out
}
/** The file's #+TODO: lines name `word`'s sequence, so Emacs cycles it: a line is added after the head's last
* #+TODO: line (or its #+ lines) when a plugin's word is written into a file that doesn't name it. TODO and DONE, Org's
* own, need none in a file with no #+TODO: line. */
function declare(c: Ctx, word: string) {
const seqs = fileSequences(c.doc.head)
if (seqs.some((s) => s.open.includes(word) || s.done.includes(word))) return
if (!seqs.length && (word === "TODO" || word === "DONE")) return
const seq = [...c.reg.sequences.values()].find((s) => s.words.some((w) => w.word === word))
if (!seq) return
const open = seq.words.filter((w) => !isClosed(w.state)).map((w) => w.word)
const done = seq.words.filter((w) => isClosed(w.state)).map((w) => w.word)
const head = c.doc.head
let at = 0
head.forEach((l, i) => /^#\+(?:SEQ_|TYP_)?TODO:/i.test(bare(l)) && (at = i + 1))
if (!at) while (at < head.length && bare(head[at]).startsWith("#+")) at++
c.doc.head = [...head.slice(0, at), lineOf(c.doc, `#+TODO: ${open.join(" ")} | ${done.join(" ")}`), ...head.slice(at)]
}
/** A task's state set: closing it stamps CLOSED, reopening it takes CLOSED off (Org's org-log-done time). */
function mark(c: Ctx, s: Section, want: string) {
const to = wordFor(c, want)
const was = s.keyword ? c.words.get(s.keyword) : undefined
s.keyword = to
declare(c, to)
const now = c.words.get(to)
if (isClosed(now) && !isClosed(was)) s.planning = { ...withoutRaw(s.planning, "closed"), closed: nowStamp(c.now) }
if (!isClosed(now)) {
const { closed: _, ...rest } = withoutRaw(s.planning, "closed")
s.planning = rest
}
}
/** Where a block of headlines goes, and at what level: before or after a task, or last under a parent or heading. */
function place(c: Ctx, e: { before?: string; after?: string; under?: string }, level: number): { at: number; level: number } {
if (e.before) {
const t = must(c, e.before)
return { at: c.doc.sections.indexOf(t), level: t.level }
}
if (e.after) {
const t = must(c, e.after)
return { at: subtreeEnd(c.doc, c.doc.sections.indexOf(t)), level: t.level }
}
if (e.under) {
// a task's id that isn't there is a mistake, not a stage to make
const p = find(c, e.under) ?? (/^(?:t-[a-z0-9]+|#\d+)$/i.test(e.under.trim()) ? must(c, e.under.trim()) : heading(c, e.under))
return { at: subtreeEnd(c.doc, c.doc.sections.indexOf(p)), level: p.level + 1 }
}
return { at: c.doc.sections.length, level }
}
function one(c: Ctx, e: PlanEdit): Section | string {
switch (e.op) {
case "add": {
const kind = e.kind ? c.reg.kinds.get(e.kind) : undefined
const f: TaskFields = { ...kind?.defaults, ...e }
const id = e.id?.trim() || c.mint()
if (find(c, id)) throw new Error(`a task already has the id ${id}`)
const s: Section = { level: 1, title: "", tags: [], planning: {}, props: [["ID", id]], body: [] }
fields(c, s, { ...f, title: e.title })
// a kind with a sequence of its own starts at that sequence's first word
const first = kind?.keywords ? c.reg.sequences.get(kind.keywords)?.words[0]?.word : undefined
mark(c, s, e.state ?? first ?? "todo")
for (const check of e.checks ?? []) addLine(c.doc, s, `- [ ] ${oneLine(check)}`)
const { at, level } = place(c, e, 1)
s.level = level
c.doc.sections.splice(at, 0, s)
return s
}
case "set": {
const s = must(c, e.ref)
fields(c, s, e)
return s
}
case "state": {
const s = must(c, e.ref)
mark(c, s, e.state)
fields(c, s, { item: e.item, note: e.note })
return s
}
case "move": {
const s = must(c, e.ref)
if (!e.before && !e.after && !e.under) throw new Error("a move needs before, after or under")
const from = c.doc.sections.indexOf(s)
const block = c.doc.sections.slice(from, subtreeEnd(c.doc, from))
for (const r of [e.before, e.after, e.under]) if (r && block.some((b) => b === find(c, r))) throw new Error("a task can't move into itself")
c.doc.sections.splice(from, block.length)
const { at, level } = place(c, e, s.level)
const delta = level - s.level
for (const b of block) b.level = Math.max(1, b.level + delta)
c.doc.sections.splice(at, 0, ...block)
return s
}
case "remove": {
const s = must(c, e.ref)
const from = c.doc.sections.indexOf(s)
c.doc.sections.splice(from, subtreeEnd(c.doc, from) - from)
return propOf(s, "ID") ?? e.ref
}
case "check": {
const s = must(c, e.ref)
const checks = checksOf(s.body)
if (e.add?.trim()) {
const last = checks.at(-1)
const indent = last ? bare(s.body[last.line]).match(/^[ \t]*/)![0] : ""
addLine(c.doc, s, `${indent}- [ ] ${oneLine(e.add)}`, last ? last.line + 1 : undefined)
return s
}
const ch = e.index === undefined ? undefined : checks[e.index]
if (!ch) throw new Error(`no checkbox ${e.index} under ${e.ref}: it has ${checks.length}`)
s.body = s.body.map((l, i) => (i === ch.line ? setCheck(l, e.done ?? !ch.done) : l))
return s
}
}
}
/** Each [n/m] or [n%] cookie counts again: the tasks right under its headline, or, with none, its checkboxes. */
function cookies(c: Ctx) {
const parents: number[] = []
const stack: number[] = []
c.doc.sections.forEach((s, i) => {
while (stack.length && c.doc.sections[stack.at(-1)!].level >= s.level) stack.pop()
parents[i] = stack.at(-1) ?? -1
stack.push(i)
})
c.doc.sections.forEach((s, i) => {
const m = COOKIE.exec(s.title)
if (!m) return
const kids = c.doc.sections.filter((k, j) => parents[j] === i && k.keyword)
let done: number
let total: number
if (kids.length) {
done = kids.filter((k) => isClosed(c.words.get(k.keyword!))).length
total = kids.length
} else {
const checks = checksOf(s.body)
const top = Math.min(...checks.map((x) => x.indent))
const own = checks.filter((x) => x.indent === top)
done = own.filter((x) => x.done).length
total = own.length
}
const cookie = m[3] !== undefined ? `[${total ? Math.round((100 * done) / total) : 0}%]` : `[${done}/${total}]`
if (cookie !== m[0]) s.title = s.title.replace(COOKIE, cookie)
})
}
/** Makes the edits on the plan's text, in order, and answers with the new text. Throws, changing nothing, on an edit
* that names no task or a value that can't be written. */
export function applyEdits(text: string, edits: readonly PlanEdit[], o: ApplyOptions = {}): Applied {
const reg = o.registry ?? plans
const before = readPlan(text, reg)
const taken = new Set(before.entries.flatMap((t) => (t.id ? [t.id] : [])))
const c: Ctx = {
doc: before.doc,
words: before.words,
now: o.now ?? new Date(),
reg,
initial: [...before.doc.sections],
mint: () => {
const id = (o.newId ?? newId)(taken)
taken.add(id)
return id
},
}
const done = edits.map((e) => one(c, e))
for (const s of c.doc.sections) if (s.keyword && !propOf(s, "ID")) setProp(s, "ID", c.mint())
cookies(c)
const out = printOrg(c.doc)
return { text: out, refs: done.map((d) => (typeof d === "string" ? d : (propOf(d, "ID") ?? ""))), plan: readPlan(out, reg) }
}
+157
View File
@@ -0,0 +1,157 @@
// What a plugin adds to plans (docs/plan.feature PL6): TODO keyword sequences, properties with a check, kinds of task
// with the properties they need and a check of their own, and views (an agenda, board lanes, anything built from a
// plan). A registry holds them; `plans` is the one everything uses unless it's handed another. raea's own sequence
// (TODO MAKING REVIEW | DONE DROPPED), its properties and its views are in every registry from the start.
import type { TaskFields } from "./edit.ts"
import type { Plan, State, Task } from "./model.ts"
import { agenda, board, outline } from "./views.ts"
export const STATES: readonly State[] = ["todo", "making", "review", "done", "dropped"]
export interface KeywordSequence {
name: string
words: { word: string; state: State }[]
}
export interface PropertyDef {
/** as written in the drawer, upper case: SHOT, not :shot: */
key: string
about?: string
/** what is wrong with a value, or undefined when it's fine */
check?: (value: string) => string | undefined
}
export interface PlanKind {
/** what :KIND: says */
name: string
about?: string
/** the keyword sequence its tasks move through, by name */
keywords?: string
/** the properties a task of this kind must have */
props?: string[]
/** what is wrong with a task of this kind, or undefined */
check?: (task: Task, plan: Plan) => string | undefined
/** what a new task of this kind starts with (plan edits read it when an add names the kind) */
defaults?: Partial<TaskFields>
}
export interface PlanView<T = unknown, O = never> {
name: string
about?: string
build: (plan: Plan, options?: O) => T
}
export interface PlanRegistry {
sequences: Map<string, KeywordSequence>
/** every keyword any sequence has, with its state; the first sequence to name a word decides it */
words: Map<string, State>
props: Map<string, PropertyDef>
kinds: Map<string, PlanKind>
views: Map<string, PlanView<unknown, never>>
}
/** A sequence's states, Org's way when a word's state isn't given or known: before the bar, the first word is to do
* and the rest are under way; after it, the first is done and the rest dropped. */
export function sequence(name: string, open: string[], done: string[], states: Record<string, State> = {}, known?: ReadonlyMap<string, State>): KeywordSequence {
const pick = (word: string, fallback: State): State => states[word] ?? known?.get(word) ?? fallback
return { name, words: [...open.map((word, i) => ({ word, state: pick(word, i === 0 ? "todo" : "making") })), ...done.map((word, i) => ({ word, state: pick(word, i === 0 ? "done" : "dropped") }))] }
}
/** A sequence written the way a #+TODO: line writes it: "DRAFT CUT GRADE | DELIVERED". */
export function defineKeywords(def: { name: string; words: string; states?: Record<string, State> }, reg: PlanRegistry = plans): KeywordSequence {
const words = def.words.trim().split(/\s+/)
const bar = words.indexOf("|")
const open = bar >= 0 ? words.slice(0, bar) : words.slice(0, -1)
const done = bar >= 0 ? words.slice(bar + 1) : words.slice(-1)
for (const w of [...open, ...done]) if (!/^[A-Z][A-Z0-9_-]*$/.test(w)) throw new Error(`a TODO keyword is one word in capitals: ${w}`)
const seq = sequence(def.name, open, done, def.states, reg.words)
reg.sequences.set(seq.name, seq)
for (const { word, state } of seq.words) if (!reg.words.has(word)) reg.words.set(word, state)
return seq
}
export function defineProperty(def: PropertyDef, reg: PlanRegistry = plans): PropertyDef {
const key = def.key.toUpperCase()
if (!/^[A-Z][A-Z0-9_-]*$/.test(key)) throw new Error(`a property is one word: ${def.key}`)
const d = { ...def, key }
reg.props.set(key, d)
return d
}
export function definePlanKind(def: PlanKind, reg: PlanRegistry = plans): PlanKind {
if (!/^[a-z][\w-]*$/.test(def.name)) throw new Error(`a kind is one lower-case word: ${def.name}`)
if (def.keywords && !reg.sequences.has(def.keywords)) throw new Error(`no keyword sequence ${def.keywords}; defineKeywords it first`)
reg.kinds.set(def.name, def)
return def
}
export function defineView<T, O = never>(def: PlanView<T, O>, reg: PlanRegistry = plans): PlanView<T, O> {
reg.views.set(def.name, def as unknown as PlanView<unknown, never>)
return def
}
/** A view of a plan by name: what its build makes. */
export function view<T = unknown, O = never>(plan: Plan, name: string, options?: O, reg: PlanRegistry = plans): T {
const v = reg.views.get(name)
if (!v) throw new Error(`no plan view ${name}: ${[...reg.views.keys()].join(", ")}`)
return (v.build as (p: Plan, o?: O) => T)(plan, options)
}
/** A registry with raea's own sequence, properties and views. */
export function createRegistry(): PlanRegistry {
const reg: PlanRegistry = { sequences: new Map(), words: new Map(), props: new Map(), kinds: new Map(), views: new Map() }
// only raea's words: a plain heading such as "* NEXT steps" stays a heading unless the file's #+TODO: names NEXT
defineKeywords({ name: "raea", words: "TODO MAKING REVIEW | DONE DROPPED", states: { REVIEW: "review" } }, reg)
const id = (v: string) => (/^[\w.:#@-]+$/.test(v) ? undefined : "an id is letters, digits and . _ - : # @, no spaces")
defineProperty({ key: "ID", about: "the task's id, which never changes: everything links to a task by it", check: id }, reg)
defineProperty({ key: "ITEM", about: "the feed item the task stands on, by id: what was made", check: id }, reg)
defineProperty({ key: "AGENT", about: "who has it: agent ids, space-separated (an @name only until an agent has that name)" }, reg)
defineProperty({ key: "FROM", about: "what asked for it: a feed message's id, or ITEM#COMMENT for a comment" }, reg)
defineProperty({ key: "KIND", about: "the task's kind (definePlanKind)" }, reg)
defineProperty({ key: "VERB", about: "the craft verb it asks for (polish, recut, regrade ...)" }, reg)
defineView({ name: "board", about: "lanes by state: to do, making, to review, done", build: board }, reg)
defineView({ name: "agenda", about: "what's due or scheduled, day by day, and what's overdue", build: agenda }, reg)
defineView({ name: "outline", about: "the plan as a tree", build: outline }, reg)
return reg
}
/** The registry everything uses unless handed another. */
export const plans: PlanRegistry = createRegistry()
export interface Diagnostic {
ref: string
/** 0-based line of the headline in the file */
line: number
severity: "error" | "warning"
message: string
}
/** What is wrong in a plan by the registry's rules: ids used twice, properties that fail their check, kinds nobody
* defined, a kind's missing properties, keywords outside a kind's sequence, and the kinds' own checks. */
export function checkPlan(plan: Plan, reg: PlanRegistry = plans): Diagnostic[] {
const out: Diagnostic[] = []
const seen = new Map<string, Task>()
for (const t of plan.entries) {
const say = (message: string, severity: Diagnostic["severity"] = "warning") => out.push({ ref: t.ref, line: t.line, severity, message })
if (t.id) {
if (seen.has(t.id)) say(`:ID: ${t.id} is also ${seen.get(t.id)!.text}'s; an id is one task's`, "error")
else seen.set(t.id, t)
}
for (const [k, v] of Object.entries(t.props)) {
const why = reg.props.get(k)?.check?.(v)
if (why) say(`:${k}: ${why}`)
}
if (!t.kind) continue
const kind = reg.kinds.get(t.kind)
if (!kind) {
say(`no kind ${t.kind} is defined (${[...reg.kinds.keys()].join(", ") || "none yet"})`)
continue
}
for (const p of kind.props ?? []) if (!(p.toUpperCase() in t.props)) say(`a ${kind.name} needs :${p.toUpperCase()}:`)
const seq = kind.keywords ? reg.sequences.get(kind.keywords) : undefined
if (seq && t.keyword && !seq.words.some((w) => w.word === t.keyword)) say(`a ${kind.name} moves through ${seq.words.map((w) => w.word).join(" ")}, not ${t.keyword}`)
const why = kind.check?.(t, plan)
if (why) say(why)
}
return out
}
+11
View File
@@ -0,0 +1,11 @@
// @raea/task (docs/plan.feature): a project's plan.org as typed tasks. Org mode is the base layer, the file people,
// raea's agents and outside agents all read and write; this package reads it without losing a byte, edits it by task
// id, and lets a plugin add keywords, properties, kinds and views. React hooks and components are in ./react.
export { bare, checksOf, fileSequences, headValue, linksIn, linkText, parseOrg, printOrg, readHeadline, renderHeadline, setCheck, type Check, type Link, type OrgDoc, type Planning, type Props, type Section } from "./org.ts"
export { dateOf, dayName, dayOf, formatStamp, nowStamp, parseStamp, type Timestamp } from "./time.ts"
export { find, isClosed, keywordsOf, openTasks, planOf, readPlan, shortDay, type Plan, type State, type Task } from "./model.ts"
export { applyEdits, newId, newPlan, tagOf, toggled, type Applied, type ApplyOptions, type PlanEdit, type TaskFields } from "./edit.ts"
export { checkPlan, createRegistry, defineKeywords, definePlanKind, defineProperty, defineView, plans, sequence, STATES, view, type Diagnostic, type KeywordSequence, type PlanKind, type PlanRegistry, type PlanView, type PropertyDef } from "./extend.ts"
export { agenda, board, outline, type Agenda, type AgendaDay, type Lane, type OutlineNode } from "./views.ts"
export { planDigest, taskLine } from "./digest.ts"
export { answerPlanTool, PLAN_TOOLS, planToolEdits, type NewTaskInput, type PlanTool, type PlanToolHost, type TaskChange } from "./tools.ts"
+160
View File
@@ -0,0 +1,160 @@
// A plan as values (docs/plan.feature PL2): every headline of the plan.org as an entry, the ones with a TODO keyword
// as tasks, each with its state, priority, tags, dates, properties, checkboxes, progress and links. Read-only: edits
// go through edit.ts, by task id, and come back as text.
import { plans, sequence, type PlanRegistry } from "./extend.ts"
import { bare, checksOf, COOKIE, fileSequences, headValue, linksIn, linkText, parseOrg, printSection, type Check, type Link, type OrgDoc } from "./org.ts"
import type { Timestamp } from "./time.ts"
/** Where a task stands, whatever its keyword is called: the board's lanes, and done or dropped for closed. */
export type State = "todo" | "making" | "review" | "done" | "dropped"
/** Done and dropped are closed: Org's words after the bar. */
export const isClosed = (s: State | undefined) => s === "done" || s === "dropped"
export interface Task {
/** how an edit names it: its :ID:, or #N (its place among the headlines) for one that has none yet */
ref: string
id?: string
/** its place among the plan's headlines */
index: number
/** 0-based line of its headline in the file */
line: number
level: number
keyword?: string
/** undefined for a heading that only groups tasks */
state?: State
priority?: string
/** the headline as written: links and a progress cookie included */
title: string
/** the headline as a reader sees it: each link as its words, no cookie */
text: string
tags: string[]
/** tags from the headings above it and #+FILETAGS (Org's tag inheritance) */
inherited: string[]
scheduled?: Timestamp
deadline?: Timestamp
closed?: Timestamp
/** every property, keys in upper case */
props: Record<string, string>
/** :ITEM:, the feed item it stands on */
item?: string
/** :AGENT:, who has it, by id */
agents: string[]
/** :FROM:, what asked for it */
from?: string
kind?: string
verb?: string
parent?: string
children: string[]
/** the nearest heading above it that isn't a task ("" at the top): the stage it's in */
stage: string
checks: Check[]
/** its tasks under it, done of all; or, with none, its checkboxes */
progress?: { done: number; total: number }
links: Link[]
/** the text under it after its planning line and drawer, as written */
body: string
}
export interface Plan {
title?: string
filetags: string[]
/** every headline in file order: the tasks and the headings that group them */
entries: Task[]
/** the entries with a keyword */
tasks: Task[]
/** the keywords this plan knows, each with its state: the registry's and its own #+TODO: lines' */
words: Map<string, State>
doc: OrgDoc
}
/** The keywords a plan's head and the registry know, with their states (the registry's win). */
export function keywordsOf(head: readonly string[], reg: PlanRegistry = plans): Map<string, State> {
const words = new Map(reg.words)
for (const s of fileSequences(head)) for (const w of sequence("file", s.open, s.done, {}, reg.words).words) if (!words.has(w.word)) words.set(w.word, w.state)
return words
}
/** Reads a plan.org. Never throws: anything it doesn't read is kept as text. */
export function readPlan(text: string, reg: PlanRegistry = plans): Plan {
const lines = text.split("\n")
const first = lines.findIndex((l) => /^\*+[ \t]/.test(bare(l)))
const words = keywordsOf(first < 0 ? lines : lines.slice(0, first), reg)
return planOf(parseOrg(text, new Set(words.keys())), words)
}
const split = (v: string | undefined) => (v ? v.split(/[\s,]+/).filter(Boolean) : [])
const shown = (title: string) => linkText(title).replace(COOKIE, "").replace(/\s+/g, " ").trim()
/** The plan of an Org document already read. */
export function planOf(doc: OrgDoc, words: Map<string, State>): Plan {
const filetags = split(headValue(doc.head, "FILETAGS")?.replace(/:/g, " "))
const entries: Task[] = []
const stack: Task[] = []
let line = doc.head.length
doc.sections.forEach((s, index) => {
const props: Record<string, string> = {}
for (const [k, v] of s.props ?? []) props[k.toUpperCase()] = v
while (stack.length && stack.at(-1)!.level >= s.level) stack.pop()
const parent = stack.at(-1)
const heading = [...stack].reverse().find((t) => !t.state)
const id = props.ID || undefined
const t: Task = {
ref: id ?? `#${index}`,
...(id && { id }),
index,
line,
level: s.level,
...(s.keyword && { keyword: s.keyword, state: words.get(s.keyword) }),
...(s.priority && { priority: s.priority }),
title: s.title,
text: shown(s.title),
tags: s.tags,
inherited: [...new Set([...filetags, ...(parent ? [...parent.inherited, ...parent.tags] : [])])],
...(s.planning.scheduled && { scheduled: s.planning.scheduled }),
...(s.planning.deadline && { deadline: s.planning.deadline }),
...(s.planning.closed && { closed: s.planning.closed }),
props,
...(props.ITEM && { item: props.ITEM }),
agents: split(props.AGENT),
...(props.FROM && { from: props.FROM }),
...(props.KIND && { kind: props.KIND }),
...(props.VERB && { verb: props.VERB }),
...(parent && { parent: parent.ref }),
children: [],
stage: heading?.text ?? "",
checks: checksOf(s.body),
links: linksIn([s.title, ...s.body].join("\n")),
body: s.body.map(bare).join("\n"),
}
parent?.children.push(t.ref)
stack.push(t)
entries.push(t)
line += printSection(s, doc.cr).length
})
const byRef = new Map(entries.map((t) => [t.ref, t]))
for (const t of entries) {
const kids = t.children.map((r) => byRef.get(r)!).filter((c) => c.state)
if (kids.length) t.progress = { done: kids.filter((c) => isClosed(c.state)).length, total: kids.length }
else if (t.checks.length) {
const top = Math.min(...t.checks.map((c) => c.indent))
const own = t.checks.filter((c) => c.indent === top)
t.progress = { done: own.filter((c) => c.done).length, total: own.length }
}
}
return { title: headValue(doc.head, "TITLE"), filetags, entries, tasks: entries.filter((t) => t.state), words, doc }
}
/** An entry by its ref: its :ID:, or #N. */
export function find(plan: Plan, ref: string): Task | undefined {
return plan.entries.find((t) => t.ref === ref || t.id === ref)
}
/** The open tasks (not done or dropped), in the plan's order. */
export const openTasks = (plan: Plan) => plan.tasks.filter((t) => !isClosed(t.state))
/** A deadline or schedule as the app shows it: MM-DD this year, YYYY-MM-DD otherwise. */
export function shortDay(t: Timestamp | undefined, now = new Date()): string | undefined {
if (!t) return undefined
return t.date.startsWith(`${now.getFullYear()}-`) ? t.date.slice(5) : t.date
}
+329
View File
@@ -0,0 +1,329 @@
// A lossless reader and writer for the slice of Org mode (orgmode.org) a plan uses: headlines with a TODO keyword, a
// [#A] priority and :tags:, the planning line under them (SCHEDULED, DEADLINE, CLOSED), the PROPERTIES drawer, and
// everything else as the lines it was. printOrg(parseOrg(text)) is text, byte for byte. An entry that changed is
// written again part by part: a headline that didn't change keeps its line (one whose keyword or words changed keeps
// its spacing and tag column), a drawer keeps the lines of the properties that didn't change, a planning line keeps
// its order and what raea can't read, and body text (lists, other drawers, prose) is never rewritten.
import { formatStamp, parseStamp, type Timestamp } from "./time.ts"
export interface Planning {
closed?: Timestamp
deadline?: Timestamp
scheduled?: Timestamp
/** the parts raea doesn't read (a range across days, a stamp it can't parse, a key written twice), each as written
* ("SCHEDULED: <2026-11-20 Fri>--<2026-11-22 Sun>"), kept when the line is written again */
rest?: string[]
}
/** A PROPERTIES drawer, in order, keys as written. */
export type Props = [key: string, value: string][]
export interface Section {
level: number
keyword?: string
priority?: string
title: string
tags: string[]
planning: Planning
/** the PROPERTIES drawer; undefined when the entry has none */
props?: Props
/** every line after the headline, its planning line and its drawer, up to the next headline, as written */
body: string[]
/** how it was written, so what didn't change prints as it was; none on a new entry */
src?: Source
}
interface Source {
headline: string
/** the headline's parts as read */
head: Head
planning?: string
pk: string
drawer?: string[]
props: Props
/** the indentation of its planning line or drawer, kept for lines written into them */
indent: string
}
export interface OrgDoc {
/** the lines before the first headline (#+TITLE:, #+TODO:, text), as written */
head: string[]
sections: Section[]
/** lines end in CRLF: a line raea writes ends so too */
cr: boolean
/** the text ends with a line break */
final: boolean
}
const HEAD = /^(\*+)[ \t]+(.*)$/
const TAGS = /(?:^|[ \t]+)(:[\p{L}\p{N}_@#%:]+:)$/u
// a planning line's parts: each stamp may be a range of days, <2026-11-20 Fri>--<2026-11-22 Sun>
const STAMP_TEXT = String.raw`[<[][^>\]]*[>\]](?:--[<[][^>\]]*[>\]])?`
const PLAN_LINE = new RegExp(String.raw`^[ \t]*(?:(?:SCHEDULED|DEADLINE|CLOSED):[ \t]*${STAMP_TEXT}[ \t]*)+$`)
const PLAN_PART = new RegExp(String.raw`(SCHEDULED|DEADLINE|CLOSED):[ \t]*(${STAMP_TEXT})`, "g")
const PLAN_KEYS = ["closed", "deadline", "scheduled"] as const
const DRAWER_START = /^[ \t]*:PROPERTIES:[ \t]*$/i
const DRAWER_END = /^[ \t]*:END:[ \t]*$/i
const PROP = /^[ \t]*:([^\s:]+):(?:[ \t]+(.*?))?[ \t]*$/
/** A line without the \r of a CRLF ending. */
export const bare = (line: string) => (line.endsWith("\r") ? line.slice(0, -1) : line)
/** A headline's parts, or null when the line isn't a headline. `keywords` are the TODO keywords the file knows. */
export function readHeadline(line: string, keywords: ReadonlySet<string>): Omit<Section, "planning" | "body"> | null {
const m = HEAD.exec(bare(line))
if (!m) return null
let rest = m[2].trimEnd()
let keyword: string | undefined
const kw = /^(\S+)(?:[ \t]+|$)/.exec(rest)
if (kw && keywords.has(kw[1])) {
keyword = kw[1]
rest = rest.slice(kw[0].length)
}
let priority: string | undefined
const pr = /^\[#([A-Z0-9])\](?:[ \t]+|$)/.exec(rest)
if (pr) {
priority = pr[1]
rest = rest.slice(pr[0].length)
}
let tags: string[] = []
const tg = TAGS.exec(rest)
if (tg) {
tags = tg[1].split(":").filter(Boolean)
rest = rest.slice(0, tg.index)
}
return { level: m[1].length, ...(keyword && { keyword }), ...(priority && { priority }), title: rest.trim(), tags }
}
/** A planning line's stamps. Whatever it can't read is kept in `rest`, so the line is still the planning line and the
* drawer under it is still read. */
function readPlanning(line: string): Planning | null {
const b = bare(line)
if (!PLAN_LINE.test(b)) return null
const p: Planning = {}
const rest: string[] = []
for (const m of b.matchAll(PLAN_PART)) {
const key = m[1].toLowerCase() as (typeof PLAN_KEYS)[number]
const t = parseStamp(m[2])
if (t && !p[key]) p[key] = t
else rest.push(m[0])
}
if (rest.length) p.rest = rest
return p
}
/** The drawer starting at `at`: its properties and where it ends, or null when the lines there aren't one. */
function readDrawer(lines: string[], at: number, end: number): { props: Props; next: number } | null {
if (at >= end || !DRAWER_START.test(bare(lines[at]))) return null
const props: Props = []
for (let i = at + 1; i < end; i++) {
const b = bare(lines[i])
if (DRAWER_END.test(b)) return { props, next: i + 1 }
const m = PROP.exec(b)
if (!m) return null
props.push([m[1], m[2] ?? ""])
}
return null
}
type Head = Pick<Section, "level" | "keyword" | "priority" | "title" | "tags">
const headKey = (s: Head) => JSON.stringify([s.level, s.keyword ?? "", s.priority ?? "", s.title, s.tags])
const planKey = (p: Planning) => (p.closed || p.deadline || p.scheduled || p.rest?.length ? JSON.stringify([p.closed, p.deadline, p.scheduled, p.rest]) : "")
/** Reads an Org file. `keywords` are the TODO keywords to read headlines with (the file's #+TODO lines and the
* registry's; model.ts keywordsOf gathers them). */
export function parseOrg(text: string, keywords: ReadonlySet<string>): OrgDoc {
const final = text.endsWith("\n")
const lines = text === "" ? [] : text.split("\n")
if (final) lines.pop()
const doc: OrgDoc = { head: [], sections: [], cr: text.includes("\r\n"), final }
const starts: number[] = []
lines.forEach((l, i) => HEAD.test(bare(l)) && starts.push(i))
doc.head = lines.slice(0, starts[0] ?? lines.length)
starts.forEach((start, n) => {
const end = starts[n + 1] ?? lines.length
const h = readHeadline(lines[start], keywords)!
let at = start + 1
let planning: Planning = {}
let planningLine: string | undefined
const p = at < end ? readPlanning(lines[at]) : null
if (p) {
planning = p
planningLine = lines[at]
at++
}
const d = readDrawer(lines, at, end)
const drawer = d ? lines.slice(at, d.next) : undefined
if (d) at = d.next
const indent = /^[ \t]*/.exec(bare(planningLine ?? drawer?.[0] ?? ""))![0]
const s: Section = { ...h, planning, ...(d && { props: d.props }), body: lines.slice(at, end) }
s.src = { headline: lines[start], head: { level: h.level, keyword: h.keyword, priority: h.priority, title: h.title, tags: [...h.tags] }, planning: planningLine, pk: planKey(planning), drawer, props: d ? d.props.map(([k, v]) => [k, v]) : [], indent }
doc.sections.push(s)
})
return doc
}
/** A headline as Org writes it, its tags ending at column 77 (org-tags-column -77). */
export function renderHeadline(s: Head): string {
const left = [`${"*".repeat(s.level)}`, s.keyword, s.priority && `[#${s.priority}]`, s.title].filter(Boolean).join(" ")
if (!s.tags.length) return left
const tags = `:${s.tags.join(":")}:`
return `${left}${" ".repeat(Math.max(1, 77 - left.length - tags.length))}${tags}`
}
/** A headline whose keyword, priority or words changed, written into its old line the way Org's org-todo does: the
* line's own spacing kept, its tags ending where they ended. Undefined when its stars or tags changed too, or the
* old line can't be followed; renderHeadline writes it then. */
function editHeadline(line: string, was: Head, s: Head): string | undefined {
if (was.level !== s.level || was.tags.join(":") !== s.tags.join(":") || !was.title || !s.title) return undefined
let at = /^\*+[ \t]+/.exec(line)![0].length
const prefix = line.slice(0, at)
/** a part of the old line (its keyword, its priority) and the space after it */
const part = (text: string | undefined) => {
if (!text) return { gap: " " }
if (!line.startsWith(text, at)) return undefined
const gap = /^[ \t]*/.exec(line.slice(at + text.length))![0]
at += text.length + gap.length
return { gap }
}
const kw = part(was.keyword)
const pr = kw && part(was.priority && `[#${was.priority}]`)
if (!pr || !line.startsWith(was.title, at)) return undefined
const end = at + was.title.length
const left = `${prefix}${s.keyword ? s.keyword + kw!.gap : ""}${s.priority ? `[#${s.priority}]${pr.gap}` : ""}${s.title}`
const tail = line.slice(end)
const pad = /^[ \t]*/.exec(tail)![0]
const next = s.tags.length ? left + " ".repeat(Math.max(1, pad.length + end - left.length)) + tail.slice(pad.length) : left + tail
// read back as it was meant, or not used
const back = readHeadline(next, new Set(s.keyword ? [s.keyword] : []))
return back && headKey(back) === headKey(s) ? next : undefined
}
/** A planning line again: its parts in the order they were written, a new CLOSED first (as Org puts it) and a new
* DEADLINE or SCHEDULED last, then the parts raea doesn't read, as written. */
function renderPlanning(p: Planning, was?: string): string {
const order = was ? [...bare(was).matchAll(/(SCHEDULED|DEADLINE|CLOSED):/g)].map((m) => m[1].toLowerCase()) : []
const keys = [...PLAN_KEYS.filter((k) => k === "closed" && !order.includes(k)), ...order, ...PLAN_KEYS.filter((k) => k !== "closed" && !order.includes(k))]
const parts = [...new Set(keys)].flatMap((k) => {
const t = p[k as (typeof PLAN_KEYS)[number]]
return t ? [`${k.toUpperCase()}: ${formatStamp(t)}`] : []
})
return [...parts, ...(p.rest ?? [])].join(" ")
}
/** A property line the way Org's org-property-format writes it ("%-10s %s"). */
const renderProp = (indent: string, k: string, v: string) => `${indent}${`:${k}:`.padEnd(10)}${v ? ` ${v}` : ""}`.trimEnd()
/** One entry's lines: the parts that didn't change as they were written, the rest written again. */
export function printSection(s: Section, cr: boolean): string[] {
const nl = (l: string) => (cr ? `${l}\r` : l)
const src = s.src
const indent = src?.indent ?? ""
const out = [src && headKey(src.head) === headKey(s) ? src.headline : nl((src && editHeadline(bare(src.headline), src.head, s)) ?? renderHeadline(s))]
const pk = planKey(s.planning)
if (src?.planning !== undefined && src.pk === pk) out.push(src.planning)
else if (pk) out.push(nl(indent + renderPlanning(s.planning, src?.planning)))
if (s.props) {
const was = src?.drawer
if (was && JSON.stringify(src!.props) === JSON.stringify(s.props)) out.push(...was)
else {
// each property that is as it was keeps its line
const used = new Set<number>()
const lines = s.props.map(([k, v]) => {
const j = src ? src.props.findIndex(([k0, v0], i) => !used.has(i) && k0 === k && v0 === v) : -1
if (j >= 0 && was) {
used.add(j)
return was[j + 1]
}
return nl(renderProp(indent, k, v))
})
out.push(was?.[0] ?? nl(`${indent}:PROPERTIES:`), ...lines, was?.at(-1) ?? nl(`${indent}:END:`))
}
}
out.push(...s.body)
return out
}
/** The file again: what wasn't changed exactly as it was read. */
export function printOrg(doc: OrgDoc): string {
const lines = [...doc.head, ...doc.sections.flatMap((s) => printSection(s, doc.cr))]
return lines.join("\n") + (doc.final && lines.length ? "\n" : "")
}
/** A line to add to the file, with its line ending's \r when the file uses CRLF. */
export const lineOf = (doc: Pick<OrgDoc, "cr">, text: string) => (doc.cr ? `${text}\r` : text)
/** A #+KEY: line's value in the file's head (TITLE, FILETAGS), the last one when there are several. */
export function headValue(head: readonly string[], key: string): string | undefined {
const re = new RegExp(`^#\\+${key}:[ \\t]*(.*?)[ \\t]*$`, "i")
let v: string | undefined
for (const l of head) {
const m = re.exec(bare(l))
if (m) v = m[1]
}
return v
}
/** The keyword sequences the file declares with #+TODO:, #+SEQ_TODO: or #+TYP_TODO:, each as its words before and
* after the bar. Fast-access keys and logging marks ("DONE(d!)") are dropped. */
export function fileSequences(head: readonly string[]): { open: string[]; done: string[] }[] {
const out: { open: string[]; done: string[] }[] = []
for (const l of head) {
const m = /^#\+(?:SEQ_|TYP_)?TODO:[ \t]*(.*)$/i.exec(bare(l))
if (!m) continue
const words = m[1].trim().split(/[ \t]+/).filter(Boolean).map((w) => w.replace(/\(.*\)$/, ""))
const bar = words.indexOf("|")
if (bar >= 0) out.push({ open: words.slice(0, bar), done: words.slice(bar + 1).filter((w) => w !== "|") })
else if (words.length) out.push({ open: words.slice(0, -1), done: words.slice(-1) })
}
return out
}
export interface Check {
/** the line in the entry's body */
line: number
done: boolean
/** [-]: some of its own sub-items are done */
partial: boolean
text: string
indent: number
}
const CHECK = /^([ \t]*)(?:[-+*]|\d+[.)])[ \t]+\[([ xX-])\](?:[ \t]+(.*))?$/
/** The checkbox items in an entry's body: "- [ ] what", "- [X] what", "1. [-] what". */
export function checksOf(body: readonly string[]): Check[] {
return body.flatMap((l, line) => {
const m = CHECK.exec(bare(l))
return m ? [{ line, done: m[2] === "X" || m[2] === "x", partial: m[2] === "-", text: (m[3] ?? "").trim(), indent: m[1].replace(/\t/g, " ").length }] : []
})
}
/** The body line with its checkbox ticked or cleared. */
export const setCheck = (line: string, done: boolean) => line.replace(/\[[ xX-]\]/, done ? "[X]" : "[ ]")
export interface Link {
/** as written inside the brackets: item:i-abc, id:t-1, https://... */
target: string
desc?: string
/** its type before the colon (item, id, comment, agent, file, https), or "fuzzy" for a plain [[name]] */
type: string
/** what follows the type */
path: string
}
const LINK = /\[\[([^[\]]+)\](?:\[([^[\]]*)\])?\]/g
/** The links in a line of text: [[target]] and [[target][description]]. */
export function linksIn(text: string): Link[] {
return [...text.matchAll(LINK)].map((m) => {
const t = /^([a-z][\w+-]*):(.*)$/i.exec(m[1])
return { target: m[1], ...(m[2] !== undefined && { desc: m[2] }), type: t ? t[1].toLowerCase() : "fuzzy", path: t ? t[2] : m[1] }
})
}
/** Text with each link as its description (or its path), as a reader sees it. */
export const linkText = (text: string) => text.replace(LINK, (_, target: string, desc?: string) => desc ?? target.replace(/^[a-z][\w+-]*:/i, ""))
/** A progress cookie in a headline: [2/5] or [40%]. */
export const COOKIE = /\[(\d*)\/(\d*)\]|\[(\d*)%\]/
+182
View File
@@ -0,0 +1,182 @@
// React for plans (docs/plan.feature PL6): usePlan reads a plan from text or from a source that changes (the app's
// store, a file an agent edits), and edits it by task id; the components draw a task, the outline, an agenda and
// board lanes as plain elements with data- attributes to style, nothing else. They work in raea's own window too:
// no portals, no dangerouslySetInnerHTML, nothing loaded later.
import { useCallback, useMemo, useSyncExternalStore, type ReactNode } from "react"
import { applyEdits, toggled, type PlanEdit } from "./edit.ts"
import { plans, view, type PlanRegistry } from "./extend.ts"
import { isClosed, readPlan, type Plan, type State, type Task } from "./model.ts"
import { agenda, board, outline, type OutlineNode } from "./views.ts"
/** Where a plan's text lives: read it, hear when it changes, and (when it can be written) edit it. */
export interface PlanSource {
read(): string | undefined
subscribe(onChange: () => void): () => void
edit?(edits: PlanEdit[]): void
}
/** A plan kept in memory: a composition's own, or a test's. */
export function memorySource(text = ""): PlanSource & { text: string } {
const subs = new Set<() => void>()
const src = {
text,
read: () => src.text,
subscribe: (f: () => void) => (subs.add(f), () => void subs.delete(f)),
edit: (edits: PlanEdit[]) => {
src.text = applyEdits(src.text, edits).text
subs.forEach((f) => f())
},
}
return src
}
const fixed = (text: string | undefined): PlanSource => ({ read: () => text, subscribe: () => () => {} })
/** The plan, read again whenever its source changes, and its edits. Text alone is read-only. */
export function usePlan(source: string | PlanSource | undefined, registry: PlanRegistry = plans): { plan: Plan; text: string; edit: (edits: PlanEdit[]) => void } {
const src = useMemo(() => (source && typeof source === "object" ? source : fixed(source)), [source])
const subscribe = useCallback((f: () => void) => src.subscribe(f), [src])
const read = useCallback(() => src.read(), [src])
const text = useSyncExternalStore(subscribe, read, read) ?? ""
const plan = useMemo(() => readPlan(text, registry), [text, registry])
const edit = useCallback(
(edits: PlanEdit[]) => {
if (!src.edit) throw new Error("this plan is read-only: its source has no edit")
src.edit(edits)
},
[src],
)
return { plan, text, edit }
}
/** A view of the plan by name (extend.ts defineView), built again when the plan changes. */
export function useView<T = unknown, O = never>(plan: Plan, name: string, options?: O, registry: PlanRegistry = plans): T {
return useMemo(() => view<T, O>(plan, name, options, registry), [plan, name, options, registry])
}
export interface TaskProps {
task: Task
/** its checkbox: called with the task; edits(toggled(task)) is the usual answer */
onToggle?: (task: Task) => void
onOpen?: (task: Task) => void
className?: string
children?: ReactNode
}
/** One task on one line: its checkbox, priority, words, progress, deadline and tags. A heading has no checkbox. */
export function TaskLine({ task, onToggle, onOpen, className, children }: TaskProps) {
const done = isClosed(task.state)
return (
<div className={className} data-task={task.ref} data-state={task.state ?? "heading"} data-keyword={task.keyword} data-priority={task.priority}>
{task.state && (
<button type="button" role="checkbox" aria-checked={done} aria-label={`${done ? "Open again" : "Mark done"}: ${task.text}`} disabled={!onToggle} onClick={() => onToggle?.(task)} data-part="box">
{done ? "✓" : ""}
</button>
)}
{task.priority && <span data-part="priority">{task.priority}</span>}
{onOpen ? (
<button type="button" onClick={() => onOpen(task)} data-part="text">
{task.text}
</button>
) : (
<span data-part="text">{task.text}</span>
)}
{task.progress && <span data-part="progress">{`${task.progress.done}/${task.progress.total}`}</span>}
{task.deadline && <span data-part="deadline">{task.deadline.date}</span>}
{task.tags.map((t) => (
<span key={t} data-part="tag">
{t}
</span>
))}
{children}
</div>
)
}
type Render = (task: Task) => ReactNode
interface ListProps {
plan: Plan
onToggle?: (task: Task) => void
onOpen?: (task: Task) => void
/** draws a task in place of TaskLine */
renderTask?: Render
className?: string
}
function line(p: ListProps, task: Task) {
return p.renderTask ? p.renderTask(task) : <TaskLine task={task} onToggle={p.onToggle} onOpen={p.onOpen} />
}
/** The plan as a tree: each headline, the tasks under it nested. */
export function PlanOutline(p: ListProps & { filter?: (task: Task) => boolean }) {
const keep = (n: OutlineNode): boolean => !p.filter || p.filter(n.task) || n.children.some(keep)
const tree = (nodes: OutlineNode[]): ReactNode => (
<ul data-part="outline">
{nodes.filter(keep).map((n) => (
<li key={n.task.ref} data-task={n.task.ref}>
{line(p, n.task)}
{n.children.length > 0 && tree(n.children)}
</li>
))}
</ul>
)
return <div className={p.className}>{tree(outline(p.plan))}</div>
}
/** What's due and scheduled, day by day, with what's overdue first. */
export function Agenda(p: ListProps & { from?: string; days?: number; label?: (date: string) => ReactNode }) {
const a = agenda(p.plan, { from: p.from, days: p.days })
return (
<div className={p.className} data-part="agenda">
{a.overdue.length > 0 && (
<section data-part="overdue">
<h3>Overdue</h3>
<ul>
{a.overdue.map((e) => (
<li key={`${e.task.ref}-${e.why}`} data-why={e.why} data-date={e.date}>
{line(p, e.task)}
</li>
))}
</ul>
</section>
)}
{a.days.map((d) => (
<section key={d.date} data-part="day" data-date={d.date} data-empty={d.entries.length === 0 || undefined}>
<h3>{p.label ? p.label(d.date) : d.date}</h3>
<ul>
{d.entries.map((e) => (
<li key={`${e.task.ref}-${e.why}`} data-why={e.why}>
{line(p, e.task)}
</li>
))}
</ul>
</section>
))}
</div>
)
}
const LANE: Record<State, string> = { todo: "To do", making: "Making", review: "To review", done: "Done", dropped: "Dropped" }
/** Board lanes by state: to do, making, to review, done. */
export function BoardLanes(p: ListProps & { states?: State[]; labels?: Partial<Record<State, string>>; filter?: (task: Task) => boolean }) {
return (
<div className={p.className} data-part="board">
{board(p.plan, { states: p.states, filter: p.filter }).map((lane) => (
<section key={lane.state} data-part="lane" data-state={lane.state}>
<h3>
{p.labels?.[lane.state] ?? LANE[lane.state]} <span data-part="count">{lane.tasks.length}</span>
</h3>
<ul>
{lane.tasks.map((t) => (
<li key={t.ref}>{line(p, t)}</li>
))}
</ul>
</section>
))}
</div>
)
}
export { toggled }
+74
View File
@@ -0,0 +1,74 @@
// Org-mode timestamps (orgmode.org/manual/Timestamps.html): <2026-11-14 Sat> is active (it shows in an agenda),
// [2026-11-14 Sat 16:40] inactive (a record, like CLOSED). A time range, a repeater (+1w, .+1d, ++1m) and a warning
// (-2d) are read and written back; the day name is whatever was written, and English when raea writes one.
export interface Timestamp {
active: boolean
/** YYYY-MM-DD */
date: string
/** HH:MM */
time?: string
/** HH:MM, the end of a range on the same day */
end?: string
/** +1w, .+1d or ++1m; a habit's .+2d/3d */
repeat?: string
/** -2d or --2d */
warn?: string
}
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
const STAMP = /^([<[])(\d{4}-\d{2}-\d{2})(?:[ \t]+([^\s\d>\]+-][^\s>\]]*))?(?:[ \t]+(\d{1,2}:\d{2})(?:-(\d{1,2}:\d{2}))?)?((?:[ \t]+(?:\.\+|\+\+|\+|--|-)\d+[hdwmy](?:\/\d+[hdwmy])?)*)[ \t]*([>\]])$/
/** A timestamp as written, or undefined when it isn't one (its brackets must match). */
export function parseStamp(s: string): Timestamp | undefined {
const m = STAMP.exec(s.trim())
if (!m || (m[1] === "<") !== (m[7] === ">")) return undefined
const t: Timestamp = { active: m[1] === "<", date: m[2] }
if (m[4]) t.time = m[4].padStart(5, "0")
if (m[5]) t.end = m[5].padStart(5, "0")
for (const part of m[6].trim().split(/[ \t]+/).filter(Boolean)) {
if (part.startsWith("-")) t.warn = part
else t.repeat = part
}
return t
}
/** The English day name of a YYYY-MM-DD date. */
export function dayName(date: string): string {
const [y, m, d] = date.split("-").map(Number)
return DAYS[new Date(Date.UTC(y, m - 1, d)).getUTCDay()]
}
/** A timestamp written the way Org writes it: <2026-11-14 Sat 10:00-11:00 +1w -2d>. */
export function formatStamp(t: Timestamp): string {
const parts = [t.date, dayName(t.date)]
if (t.time) parts.push(t.end ? `${t.time}-${t.end}` : t.time)
if (t.repeat) parts.push(t.repeat)
if (t.warn) parts.push(t.warn)
return t.active ? `<${parts.join(" ")}>` : `[${parts.join(" ")}]`
}
const pad = (n: number) => String(n).padStart(2, "0")
/** A local date as YYYY-MM-DD. */
export const dateOf = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
/** Now as Org records a change: an inactive stamp with the time, [2026-11-14 Sat 16:40]. */
export function nowStamp(now = new Date()): Timestamp {
return { active: false, date: dateOf(now), time: `${pad(now.getHours())}:${pad(now.getMinutes())}` }
}
/** A day as a person or an agent writes it: YYYY-MM-DD, MM-DD (this year, as a brief wrote due dates), or an Org
* timestamp. Undefined when it is none of those. */
export function dayOf(s: string, now = new Date()): Timestamp | undefined {
const v = s.trim()
if (/^[<[]/.test(v)) return parseStamp(v)
const full = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v)
const short = /^(\d{2})-(\d{2})$/.exec(v)
const date = full ? v : short ? `${now.getFullYear()}-${short[1]}-${short[2]}` : undefined
if (!date) return undefined
const [y, m, d] = date.split("-").map(Number)
const back = new Date(Date.UTC(y, m - 1, d))
if (back.getUTCMonth() !== m - 1 || back.getUTCDate() !== d) return undefined
return { active: true, date }
}
+102
View File
@@ -0,0 +1,102 @@
// A plan's tools for an agent (docs/plan.feature PL5): plan_read, plan_add, plan_update and plan_close, as the raea
// app offers them to every agent it launches. Any host answers them the same way: it says how to read the plan's text
// and how to make edits on it, and these turn a tool's input into plan edits (edit.ts) and its answer into the open
// tasks with their ids. The app's page answers them through its plans, a headless run on the folder's plan.org.
import { planDigest } from "./digest.ts"
import type { PlanEdit, TaskFields } from "./edit.ts"
import { isClosed, readPlan } from "./model.ts"
export const PLAN_TOOLS = ["plan_read", "plan_add", "plan_update", "plan_close"] as const
export type PlanTool = (typeof PLAN_TOOLS)[number]
/** A task as plan_add takes it. Left without agents, it's the calling agent's. */
export interface NewTaskInput extends Omit<TaskFields, "title"> {
title: string
state?: string
under?: string
before?: string
after?: string
checks?: string[]
}
/** One change as plan_update takes it: fields to set, and at most one of state, check, move or remove. */
export interface TaskChange extends TaskFields {
id: string
state?: string
/** a checkbox under it, by its place (0 is the first): ticked, or as `done` says */
check?: number
done?: boolean
/** a checkbox added under it */
add_check?: string
move?: { before?: string; after?: string; under?: string }
remove?: boolean
}
export interface PlanToolHost {
/** the calling agent's id: a new task with no agents is its */
who: string
/** the plan's text now */
text(): string
/** the edits made on the plan: its text after, and each edit's task id */
apply(edits: PlanEdit[]): Promise<{ text: string; refs: string[] }> | { text: string; refs: string[] }
/** where the plan is, for the agent to say or open */
file?: string
}
const list = <T>(v: unknown, what: string): T[] => {
if (!Array.isArray(v) || !v.length) throw new Error(`${what}: a list, with at least one`)
return v as T[]
}
/** The fields of a change that set a task's own values (title, priority, tags, dates, item, agents, properties, note). */
function fieldsOf(c: TaskChange): TaskFields | undefined {
const { id: _, state: _s, check: _c, done: _d, add_check: _a, move: _m, remove: _r, ...f } = c
return Object.keys(f).length ? f : undefined
}
/** A tool's input as plan edits, in order. Throws, naming what's wrong, on an input that isn't one. */
export function planToolEdits(tool: Exclude<PlanTool, "plan_read">, input: Record<string, unknown>, who: string): PlanEdit[] {
if (tool === "plan_add")
return list<NewTaskInput>(input.tasks, "tasks").map((t) => {
if (!t || typeof t.title !== "string" || !t.title.trim()) throw new Error("each task needs a title")
return { ...t, op: "add" as const, agents: t.agents ?? [who] }
})
if (tool === "plan_close") {
if (typeof input.id !== "string") throw new Error("id: the task to close (plan_read lists them)")
const state = input.state === undefined ? "done" : String(input.state)
if (!/^(done|dropped)$/i.test(state) && state !== state.toUpperCase()) throw new Error(`state: done or dropped (or a closing keyword of the plan's), not ${state}`)
return [{ op: "state", ref: input.id, state, ...(typeof input.item === "string" && { item: input.item }), ...(typeof input.note === "string" && { note: input.note }) }]
}
return list<TaskChange>(input.changes, "changes").flatMap((c): PlanEdit[] => {
if (!c || typeof c.id !== "string") throw new Error("each change names its task by id (plan_read lists them)")
if (c.remove) return [{ op: "remove", ref: c.id }]
const out: PlanEdit[] = []
const f = fieldsOf(c)
if (f) out.push({ op: "set", ref: c.id, ...f })
if (c.state) out.push({ op: "state", ref: c.id, state: c.state })
if (c.check !== undefined) out.push({ op: "check", ref: c.id, index: c.check, ...(c.done !== undefined && { done: c.done }) })
if (c.add_check) out.push({ op: "check", ref: c.id, add: c.add_check })
if (c.move) out.push({ op: "move", ref: c.id, ...c.move })
if (!out.length) throw new Error(`nothing to change on ${c.id}: give a field, state, check, move or remove`)
return out
})
}
/** A tool answered: plan_read gives the open tasks by id (and the whole text with full), giving any task without an id
* one first; an edit gives the ids it touched and the open tasks after it. */
export async function answerPlanTool(tool: PlanTool, input: Record<string, unknown>, h: PlanToolHost): Promise<unknown> {
const file = h.file ?? "plan.org"
if (tool === "plan_read") {
let text = h.text()
// a task written without an id (by hand, in Emacs) is given one first: an agent names tasks by id, never by place
if (readPlan(text).tasks.some((t) => !t.id)) text = (await h.apply([])).text
return { file, open: planDigest(readPlan(text), { max: 200 }), ...(input.full ? { text } : {}) }
}
const edits = planToolEdits(tool, input, h.who)
// plan_close closes: a keyword of the plan's that isn't after its bar (MAKING) is plan_update's
const close = edits[0]
if (tool === "plan_close" && close.op === "state" && !/^(done|dropped)$/i.test(close.state) && !isClosed(readPlan(h.text()).words.get(close.state)))
throw new Error(`state: done or dropped, or a closing keyword of the plan's; ${close.state} doesn't close (plan_update sets it)`)
const r = await h.apply(edits)
return { file, ids: [...new Set(r.refs.filter(Boolean))], open: planDigest(readPlan(r.text)) }
}
+57
View File
@@ -0,0 +1,57 @@
// raea's own views of a plan (extend.ts registers them): board lanes by state, an agenda by day, and the outline as a
// tree. Pure functions of the plan; a plugin's views are built the same way (defineView).
import type { Plan, State, Task } from "./model.ts"
export interface Lane {
state: State
tasks: Task[]
}
/** Lanes by state, in the board's order. Dropped tasks are on no lane unless asked for. */
export function board(plan: Plan, options?: { states?: State[]; filter?: (t: Task) => boolean }): Lane[] {
const states = options?.states ?? ["todo", "making", "review", "done"]
const tasks = plan.tasks.filter((t) => !options?.filter || options.filter(t))
return states.map((state) => ({ state, tasks: tasks.filter((t) => t.state === state) }))
}
export interface AgendaDay {
date: string
entries: { task: Task; why: "deadline" | "scheduled" }[]
}
export interface Agenda {
/** open tasks whose deadline or schedule is before the first day */
overdue: { task: Task; why: "deadline" | "scheduled"; date: string }[]
days: AgendaDay[]
}
const addDays = (date: string, n: number) => {
const [y, m, d] = date.split("-").map(Number)
const t = new Date(Date.UTC(y, m - 1, d + n))
return t.toISOString().slice(0, 10)
}
/** What's due and scheduled day by day from `from` (YYYY-MM-DD, today by default) for `days` days, and what's
* overdue. Closed tasks are left out. */
export function agenda(plan: Plan, options?: { from?: string; days?: number }): Agenda {
const now = new Date()
const from = options?.from ?? `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`
const n = Math.max(1, options?.days ?? 7)
const open = plan.tasks.filter((t) => t.state !== "done" && t.state !== "dropped")
const dated = open.flatMap((task) => [...(task.deadline ? [{ task, why: "deadline" as const, date: task.deadline.date }] : []), ...(task.scheduled ? [{ task, why: "scheduled" as const, date: task.scheduled.date }] : [])])
const days = Array.from({ length: n }, (_, i) => addDays(from, i)).map((date) => ({ date, entries: dated.filter((e) => e.date === date).map(({ task, why }) => ({ task, why })) }))
return { overdue: dated.filter((e) => e.date < from).sort((a, b) => a.date.localeCompare(b.date)), days }
}
export interface OutlineNode {
task: Task
children: OutlineNode[]
}
/** The plan as a tree of its headlines. */
export function outline(plan: Plan): OutlineNode[] {
const nodes = new Map(plan.entries.map((t) => [t.ref, { task: t, children: [] as OutlineNode[] }]))
const roots: OutlineNode[] = []
for (const t of plan.entries) (t.parent ? nodes.get(t.parent)!.children : roots).push(nodes.get(t.ref)!)
return roots
}
+180
View File
@@ -0,0 +1,180 @@
// PL3: every change by task id, the rest of the file untouched (src/edit.ts), and the plan as values (src/model.ts).
import { describe, expect, test } from "vitest"
import { applyEdits, createRegistry, defineKeywords, find, newPlan, planDigest, readPlan, toggled, type PlanEdit } from "../src"
const NOW = new Date(2026, 10, 14, 16, 40)
let n = 0
const ids = () => `t-${++n}`
const apply = (text: string, edits: PlanEdit[]) => applyEdits(text, edits, { now: NOW, newId: ids })
const PLAN = `#+TITLE: Ides
#+TODO: TODO MAKING REVIEW | DONE DROPPED
* Act one
** TODO Rome storyboard [0/2]
:PROPERTIES:
:ID: t-rome
:END:
Notes a person wrote, kept.
*** TODO The forum
:PROPERTIES:
:ID: t-forum
:END:
*** TODO The steps
:PROPERTIES:
:ID: t-steps
:END:
** DONE Cast the narrator
CLOSED: [2026-11-02 Mon 10:14]
:PROPERTIES:
:ID: t-cast
:END:
* Sound
** TODO Foley for the fire
`
describe("PL2: the plan as values", () => {
const p = readPlan(PLAN)
test("tasks and the headings that group them; states from the keywords; stages, parents and progress", () => {
expect(p.title).toBe("Ides")
expect(p.entries.map((t) => [t.ref, t.keyword ?? "", t.state ?? "", t.stage])).toEqual([
["#0", "", "", ""],
["t-rome", "TODO", "todo", "Act one"],
["t-forum", "TODO", "todo", "Act one"],
["t-steps", "TODO", "todo", "Act one"],
["t-cast", "DONE", "done", "Act one"],
["#5", "", "", ""],
["#6", "TODO", "todo", "Sound"],
])
expect(find(p, "t-rome")!.children).toEqual(["t-forum", "t-steps"])
expect(find(p, "t-rome")!.progress).toEqual({ done: 0, total: 2 })
expect(find(p, "t-rome")!.text).toBe("Rome storyboard")
expect(find(p, "t-rome")!.line).toBe(4)
expect(find(p, "t-cast")!.closed?.date).toBe("2026-11-02")
})
test("a file's own keywords are read with their states, Org's way", () => {
const own = readPlan("#+TODO: OPEN NEXT | SHIPPED KILLED\n* NEXT a\n* KILLED b\n* REVIEW c\n")
expect(own.tasks.map((t) => [t.keyword, t.state])).toEqual([
["NEXT", "making"],
["KILLED", "dropped"],
["REVIEW", "review"],
])
})
})
describe("PL3: edits by id", () => {
test("closing a subtask stamps CLOSED, links what was made and counts the cookie; nothing else moves", () => {
const r = apply(PLAN, [{ op: "state", ref: "t-forum", state: "done", item: "i-forum-1", note: "Made the forum still." }])
expect(r.refs).toEqual(["t-forum"])
expect(r.text).toContain("** TODO Rome storyboard [1/2]\n")
expect(r.text).toContain("*** DONE The forum\nCLOSED: [2026-11-14 Sat 16:40]\n:PROPERTIES:\n:ID: t-forum\n:ITEM: i-forum-1\n:END:\nMade the forum still.\n")
// every line no edit touched is as it was
const kept = PLAN.split("\n").filter((l) => !/Rome storyboard|The forum/.test(l))
for (const l of kept) expect(r.text.split("\n")).toContain(l)
// and opened again: CLOSED comes off
const back = apply(r.text, [toggled(find(r.plan, "t-forum")!)])
expect(back.text).toContain("*** TODO The forum\n:PROPERTIES:")
expect(back.text).not.toContain("CLOSED: [2026-11-14")
})
test("add: under a heading by its words (made when missing), with priority, tags, deadline, agent and checkboxes", () => {
n = 0
const r = apply(PLAN, [
{ op: "add", title: "Senate theme, final mix", under: "Sound", priority: "a", tags: ["trailer", "final-mix"], deadline: "11-20", agents: ["a-score"], from: "m-1", checks: ["stems", "master"] },
{ op: "add", title: "Colour the titles", under: "Look" },
])
expect(r.refs).toEqual(["t-1", "t-2"])
const head = r.text.split("\n").find((l) => l.includes("Senate theme"))!
expect(head).toMatch(/^\*\* TODO \[#A\] Senate theme, final mix +:trailer:final_mix:$/)
expect(head.length).toBe(77)
expect(r.text).toContain(`${head}\nDEADLINE: <2026-11-20 Fri>\n:PROPERTIES:\n:ID: t-1\n:AGENT: a-score\n:FROM: m-1\n:END:\n- [ ] stems\n- [ ] master\n`)
expect(r.text.endsWith("* Look\n** TODO Colour the titles\n:PROPERTIES:\n:ID: t-2\n:END:\n")).toBe(true)
// the task with no id got one on this write (t-3), so every task can be named from now on
expect(find(r.plan, "t-3")?.text).toBe("Foley for the fire")
expect(find(r.plan, "t-1")).toMatchObject({ priority: "A", tags: ["trailer", "final_mix"], agents: ["a-score"], from: "m-1", stage: "Sound", progress: { done: 0, total: 2 } })
})
test("#N names a headline with no id as the plan was before the edits, even after an add moved it", () => {
const r = apply(PLAN, [
{ op: "add", title: "First", before: "t-rome" },
{ op: "set", ref: "#6", title: "Foley for the fire and the crowd" },
])
expect(r.text).toContain("** TODO Foley for the fire and the crowd\n")
})
test("move: a subtree goes before another task, taking its level; under a heading; never into itself", () => {
const r = apply(PLAN, [{ op: "move", ref: "t-rome", before: "#6" }])
expect(readPlan(r.text).entries.map((t) => `${t.level}${t.text}`)).toEqual(["1Act one", "2Cast the narrator", "1Sound", "2Rome storyboard", "3The forum", "3The steps", "2Foley for the fire"])
const up = apply(PLAN, [{ op: "move", ref: "t-forum", under: "Sound" }])
expect(find(up.plan, "t-forum")).toMatchObject({ level: 2, stage: "Sound" })
expect(find(up.plan, "t-rome")!.title).toBe("Rome storyboard [0/1]")
expect(() => apply(PLAN, [{ op: "move", ref: "t-rome", after: "t-steps" }])).toThrow(/into itself/)
})
test("set and remove; a checkbox ticked and one added; what's wrong is said and nothing is written", () => {
const r = apply(PLAN, [
{ op: "set", ref: "t-steps", deadline: "2026-11-21", tags: ["gate"], props: { SHOT: "12" } },
{ op: "remove", ref: "t-cast" },
])
expect(r.text).toContain("*** TODO The steps")
expect(find(r.plan, "t-steps")).toMatchObject({ deadline: { date: "2026-11-21" }, tags: ["gate"], props: { ID: "t-steps", SHOT: "12" } })
expect(find(r.plan, "t-cast")).toBeUndefined()
const c = apply("* TODO Grade [0%]\n:PROPERTIES:\n:ID: g\n:END:\n- [ ] warm\n- [ ] cool\n", [{ op: "check", ref: "g", index: 1 }, { op: "check", ref: "g", add: "contrast" }])
expect(c.text).toBe("* TODO Grade [33%]\n:PROPERTIES:\n:ID: g\n:END:\n- [ ] warm\n- [X] cool\n- [ ] contrast\n")
expect(() => apply(PLAN, [{ op: "state", ref: "t-nope", state: "done" }])).toThrow(/no task t-nope/)
expect(() => apply(PLAN, [{ op: "state", ref: "t-rome", state: "finished" }])).toThrow(/neither a keyword nor a state/)
expect(() => apply(PLAN, [{ op: "set", ref: "t-rome", deadline: "someday" }])).toThrow(/YYYY-MM-DD/)
})
test("closing one task in a file kept by hand changes that task's lines and nothing else", () => {
const mine = `#+TITLE: Kept in Emacs
#+STARTUP: content
#+OPTIONS: toc:nil
* Notes :notes:
#+BEGIN_SRC typescript :tangle yes
const x = { a: 1 }
* a headline-looking line is one in Org too, so it is one here
#+END_SRC
| col | other |
|-----+-------|
| 1 | 2 |
#+TBLFM: $2=$1*2
- plain list
- nested
* Work
** TODO [#B] Light the door :look:
SCHEDULED: <2026-11-20 Fri> DEADLINE: <2026-11-22 Sun>
:PROPERTIES:
:ID: t-door
:Effort: 1:00
:END:
:LOGBOOK:
CLOCK: [2026-11-14 Sat 10:00]--[2026-11-14 Sat 11:00] => 1:00
:END:
** TODO Score it
:PROPERTIES:
:ID: t-score
:END:
`
const r = apply(mine, [{ op: "state", ref: "t-door", state: "done" }])
const before = mine.split("\n")
const after = r.text.split("\n")
expect(after.filter((l) => !before.includes(l))).toEqual(["** DONE [#B] Light the door :look:", " CLOSED: [2026-11-14 Sat 16:40] SCHEDULED: <2026-11-20 Fri> DEADLINE: <2026-11-22 Sun>"])
expect(before.filter((l) => !after.includes(l))).toEqual(["** TODO [#B] Light the door :look:", " SCHEDULED: <2026-11-20 Fri> DEADLINE: <2026-11-22 Sun>"])
expect(after.length).toBe(before.length)
})
test("under a task's id that isn't there is a mistake, not a stage to make", () => {
expect(() => apply(PLAN, [{ op: "add", title: "x", under: "t-gone" }])).toThrow(/no task t-gone/)
expect(() => apply(PLAN, [{ op: "move", ref: "t-forum", under: "#99" }])).toThrow(/no task #99/)
})
test("a plugin's keyword written into a file that doesn't name it gets a #+TODO: line, so Emacs cycles it", () => {
const reg = createRegistry()
defineKeywords({ name: "shots", words: "SHOT LIT | APPROVED" }, reg)
const r = applyEdits(PLAN, [{ op: "add", title: "Shot 12", state: "SHOT" }], { now: NOW, registry: reg })
expect(r.text.startsWith("#+TITLE: Ides\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n#+TODO: SHOT LIT | APPROVED\n\n")).toBe(true)
// raea's own words in a file with no #+TODO: line: Org's TODO and DONE need none, MAKING does
expect(applyEdits("* TODO a\n:PROPERTIES:\n:ID: a\n:END:\n", [{ op: "state", ref: "a", state: "done" }], { now: NOW }).text.startsWith("* DONE a")).toBe(true)
expect(applyEdits("#+TITLE: x\n* TODO a\n:PROPERTIES:\n:ID: a\n:END:\n", [{ op: "state", ref: "a", state: "making" }], { now: NOW }).text.startsWith("#+TITLE: x\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n* MAKING a")).toBe(true)
})
test("a new plan is raea's keywords spelled out; the digest an agent reads lists open tasks by id", () => {
const r = apply(newPlan("Pong"), [{ op: "add", title: "Tune the paddle", under: "Feel" }, { op: "add", title: "Old idea", state: "dropped" }])
expect(r.text.startsWith("#+TITLE: Pong\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n\n* Feel\n** TODO Tune the paddle\n")).toBe(true)
expect(planDigest(r.plan)).toMatch(/^Feel:\n {2}- t-\d+ {2}TODO {2}Tune the paddle\n1 closed \(done or dropped\)\.$/)
})
})
+51
View File
@@ -0,0 +1,51 @@
// PL6: a plugin's keywords, properties, kinds and views (src/extend.ts, src/views.ts).
import { describe, expect, test } from "vitest"
import { applyEdits, checkPlan, createRegistry, defineKeywords, definePlanKind, defineProperty, defineView, readPlan, view, type Task } from "../src"
describe("PL6: extending plans", () => {
test("a keyword sequence a plugin defines is read in any plan, with the states it gives", () => {
const reg = createRegistry()
defineKeywords({ name: "film", words: "SHOOT CUT GRADE | DELIVERED", states: { GRADE: "review" } }, reg)
const p = readPlan("* SHOOT the steps\n* GRADE the steps\n* DELIVERED the trailer\n", reg)
expect(p.tasks.map((t) => [t.keyword, t.state])).toEqual([
["SHOOT", "todo"],
["GRADE", "review"],
["DELIVERED", "done"],
])
// the default registry doesn't know them: a plain heading
expect(readPlan("* SHOOT the steps\n").tasks).toEqual([])
expect(() => defineKeywords({ name: "bad", words: "to do | done" }, reg)).toThrow(/capitals/)
})
test("a kind names its sequence, the properties it needs and a check of its own; checkPlan says what's wrong", () => {
const reg = createRegistry()
defineKeywords({ name: "film", words: "SHOOT CUT | DELIVERED" }, reg)
defineProperty({ key: "shot", about: "the shot's number", check: (v) => (/^\d+$/.test(v) ? undefined : "a shot is a number") }, reg)
definePlanKind({ name: "shot", keywords: "film", props: ["SHOT"], check: (t: Task) => (t.deadline ? undefined : "a shot needs a deadline"), defaults: { tags: ["shot"] } }, reg)
const r = applyEdits("", [{ op: "add", id: "s1", title: "The steps, wide", kind: "shot", state: "SHOOT", props: { SHOT: "x" } }, { op: "add", id: "s2", title: "No kind", kind: "nope" }], { registry: reg })
expect(r.plan.tasks[0]).toMatchObject({ kind: "shot", keyword: "SHOOT", tags: ["shot"] })
// with no state, a task of a kind starts at its sequence's first word
const first = reg.sequences.get("film")!.words[0].word
expect(applyEdits("", [{ op: "add", title: "Another", kind: "shot" }], { registry: reg }).plan.tasks[0].keyword).toBe(first)
expect(checkPlan(r.plan, reg).map((d) => `${d.ref}: ${d.message}`)).toEqual(["s1: :SHOT: a shot is a number", "s1: a shot needs a deadline", "s2: no kind nope is defined (shot)"])
const dup = readPlan("* TODO a\n:PROPERTIES:\n:ID: x\n:END:\n* TODO b\n:PROPERTIES:\n:ID: x\n:END:\n", reg)
expect(checkPlan(dup, reg)).toMatchObject([{ ref: "x", severity: "error", line: 4 }])
expect(() => definePlanKind({ name: "take", keywords: "nope" }, reg)).toThrow(/defineKeywords it first/)
})
test("views: raea's board and agenda, and one a plugin adds", () => {
const reg = createRegistry()
const p = readPlan(
"* TODO a\nDEADLINE: <2026-11-13 Fri>\n* MAKING b\nSCHEDULED: <2026-11-15 Sun>\n* REVIEW c\n* DONE d\nDEADLINE: <2026-11-14 Sat>\n* DROPPED e\n* TODO f :x:\n:PROPERTIES:\n:AGENT: a-grade\n:END:\n",
reg,
)
const lanes = view<{ state: string; tasks: Task[] }[]>(p, "board", undefined, reg)
expect(lanes.map((l) => `${l.state}:${l.tasks.map((t) => t.text).join("")}`)).toEqual(["todo:af", "making:b", "review:c", "done:d"])
const a = view<{ overdue: { task: Task }[]; days: { date: string; entries: { task: Task; why: string }[] }[] }, { from: string; days: number }>(p, "agenda", { from: "2026-11-14", days: 3 }, reg)
expect(a.overdue.map((e) => e.task.text)).toEqual(["a"])
expect(a.days.map((d) => `${d.date}:${d.entries.map((e) => `${e.task.text}/${e.why}`).join(",")}`)).toEqual(["2026-11-14:", "2026-11-15:b/scheduled", "2026-11-16:"])
defineView({ name: "by-agent", build: (plan) => Object.groupBy(plan.tasks.filter((t) => t.agents.length), (t) => t.agents[0]) }, reg)
expect(Object.keys(view<Record<string, Task[]>>(p, "by-agent", undefined, reg))).toEqual(["a-grade"])
expect(() => view(p, "nope", undefined, reg)).toThrow(/no plan view nope: board, agenda, outline, by-agent/)
})
})
+151
View File
@@ -0,0 +1,151 @@
// PL2: the plan.org read and written without losing a byte (src/org.ts, src/time.ts).
import { describe, expect, test } from "vitest"
import { checksOf, dayOf, formatStamp, linksIn, linkText, parseOrg, parseStamp, printOrg, readHeadline } from "../src"
const KW = new Set(["TODO", "MAKING", "REVIEW", "DONE", "DROPPED"])
const GNARLY = `#+TITLE: The Ides of March
#+TODO: TODO MAKING REVIEW | DONE DROPPED
#+STARTUP: overview
Some words before any headline, kept as they are.
* Act one :act_one:
** DONE [#A] Cast the narrator :score:
CLOSED: [2026-11-02 Mon 10:14] DEADLINE: <2026-11-01 Sun>
:PROPERTIES:
:ID: t-cast
:AGENT: a-score
:CUSTOM_thing: kept as written
:END:
:LOGBOOK:
- State "DONE" from "TODO" [2026-11-02 Mon 10:14]
:END:
** TODO Rome storyboard [1/3]
SCHEDULED: <2026-11-20 Fri 10:00-11:00 +1w -2d>
- [X] the forum
- [ ] the steps
- [x] a nested one
- [-] the senate
| a | table |
|---+-------|
#+BEGIN_SRC tsx
* not a headline inside a block? Org says it is one, and so do we
#+END_SRC
*bold* at the start of a line is no headline
* WAITING an unknown keyword is part of the title
*** Deep, skipping a level
:PROPERTIES:
:ID: unterminated drawer, so this is body
* COMMENT a commented heading
* Last line without a newline`
describe("PL2a: a round trip changes nothing", () => {
test("a file with drawers, logbooks, tables, blocks, odd spacing and no final newline prints back byte for byte", () => {
expect(printOrg(parseOrg(GNARLY, KW))).toBe(GNARLY)
expect(printOrg(parseOrg(`${GNARLY}\n`, KW))).toBe(`${GNARLY}\n`)
})
test("CRLF files, empty files, a file of only a head, trailing blank lines", () => {
for (const t of ["", "\n", "\n\n", "#+TITLE: x\n", "* TODO a\r\n** DONE b\r\n :PROPERTIES:\r\n :ID: x\r\n :END:\r\n", "* a\n\n\n", "text\n* h\nbody\n\n"]) expect(printOrg(parseOrg(t, KW))).toBe(t)
})
})
describe("PL2b: what a headline says", () => {
test("stars, keyword, priority, title and tags", () => {
expect(readHeadline("** DONE [#A] Cast the narrator :score:x@y:", KW)).toEqual({ level: 2, keyword: "DONE", priority: "A", title: "Cast the narrator", tags: ["score", "x@y"] })
expect(readHeadline("* TODO", KW)).toEqual({ level: 1, keyword: "TODO", title: "", tags: [] })
expect(readHeadline("* WAITING on the cut", KW)).toEqual({ level: 1, title: "WAITING on the cut", tags: [] })
expect(readHeadline("*bold*", KW)).toBeNull()
expect(readHeadline("* Tags need a space before them:no:", KW)!.tags).toEqual([])
})
test("planning, drawer and body are told apart; an unterminated drawer is body", () => {
const d = parseOrg(GNARLY, KW)
const cast = d.sections[1]
expect(cast.planning.closed).toEqual({ active: false, date: "2026-11-02", time: "10:14" })
expect(cast.planning.deadline).toEqual({ active: true, date: "2026-11-01" })
expect(cast.props).toEqual([["ID", "t-cast"], ["AGENT", "a-score"], ["CUSTOM_thing", "kept as written"]])
expect(cast.body[0]).toBe(" :LOGBOOK:")
const rome = d.sections[2]
expect(rome.planning.scheduled).toEqual({ active: true, date: "2026-11-20", time: "10:00", end: "11:00", repeat: "+1w", warn: "-2d" })
expect(checksOf(rome.body).map((c) => [c.done, c.partial, c.indent, c.text])).toEqual([
[true, false, 0, "the forum"],
[false, false, 0, "the steps"],
[true, false, 2, "a nested one"],
[false, true, 0, "the senate"],
])
const deep = d.sections.find((s) => s.title.startsWith("Deep"))!
expect(deep.props).toBeUndefined()
expect(deep.body).toEqual([":PROPERTIES:", ":ID: unterminated drawer, so this is body"])
})
})
describe("PL2c: a changed entry is written again part by part", () => {
test("a new keyword rewrites the headline, keeps the planning line and drawer as they were", () => {
const d = parseOrg(GNARLY, KW)
d.sections[2].keyword = "MAKING"
const out = printOrg(d)
expect(out).toContain("** MAKING Rome storyboard [1/3]\nSCHEDULED: <2026-11-20 Fri 10:00-11:00 +1w -2d>\n- [X] the forum")
expect(out.replace("MAKING Rome", "TODO Rome")).toBe(GNARLY)
})
test("a property added keeps every other property's line, indentation and all", () => {
const d = parseOrg(GNARLY, KW)
d.sections[1].props = [...d.sections[1].props!, ["ITEM", "i-cast"]]
const out = printOrg(d)
expect(out).toContain(" :CUSTOM_thing: kept as written\n :ITEM: i-cast\n :END:")
expect(out.split("\n").length).toBe(GNARLY.split("\n").length + 1)
})
test("tags end at column 77; a new drawer and planning line are written Org's way", () => {
const d = parseOrg("* TODO Grade it\n", KW)
d.sections[0].tags = ["trailer"]
d.sections[0].planning = { deadline: { active: true, date: "2026-11-03" } }
d.sections[0].props = [["ID", "t-1"]]
const out = printOrg(d).split("\n")
expect(out[0].length).toBe(77)
expect(out[0]).toMatch(/^\* TODO Grade it +:trailer:$/)
expect(out.slice(1, 5)).toEqual(["DEADLINE: <2026-11-03 Tue>", ":PROPERTIES:", ":ID: t-1", ":END:"])
})
test("a headline whose keyword or words change keeps its own spacing, and its tags end where they ended", () => {
const d = parseOrg("* TODO [#B] Foo bar :a:b:\n** NEXT\tTabbed\n", new Set([...KW, "NEXT"]))
d.sections[0].keyword = "DONE"
d.sections[0].title = "Foo bar [1/2]"
d.sections[1].keyword = undefined
expect(printOrg(d)).toBe("* DONE [#B] Foo bar [1/2] :a:b:\n** Tabbed\n")
// tags aligned to a column stay at it
const aligned = parseOrg("** TODO Light the door :look:\n", KW)
aligned.sections[0].keyword = "MAKING"
expect(printOrg(aligned)).toBe("** MAKING Light the door :look:\n")
})
test("a planning line raea can't wholly read (a range of days, a habit) is still the planning line", () => {
const text = "* TODO Shoot the steps\n SCHEDULED: <2026-11-20 Fri>--<2026-11-22 Sun> DEADLINE: <2026-11-23 Mon .+2d/3d>\n :PROPERTIES:\n :ID: t-steps\n :END:\n"
const d = parseOrg(text, KW)
expect(d.sections[0].props).toEqual([["ID", "t-steps"]])
expect(d.sections[0].planning).toEqual({ deadline: { active: true, date: "2026-11-23", repeat: ".+2d/3d" }, rest: ["SCHEDULED: <2026-11-20 Fri>--<2026-11-22 Sun>"] })
expect(printOrg(d)).toBe(text)
// closed: CLOSED comes first, and the rest is written as it was, in its order
d.sections[0].keyword = "DONE"
d.sections[0].planning = { ...d.sections[0].planning, closed: { active: false, date: "2026-11-14", time: "16:40" } }
expect(printOrg(d).split("\n")[1]).toBe(" CLOSED: [2026-11-14 Sat 16:40] DEADLINE: <2026-11-23 Mon .+2d/3d> SCHEDULED: <2026-11-20 Fri>--<2026-11-22 Sun>")
})
test("a CRLF file's new lines end in CRLF", () => {
const d = parseOrg("* TODO a\r\n", KW)
d.sections[0].props = [["ID", "x"]]
expect(printOrg(d)).toBe("* TODO a\r\n:PROPERTIES:\r\n:ID: x\r\n:END:\r\n")
})
})
describe("timestamps and links", () => {
test("read and written back; a day as a person writes it", () => {
for (const s of ["<2026-11-14 Sat>", "[2026-11-14 Sat 16:40]", "<2026-11-14 Sat 10:00-11:30 .+1d --3d>"]) expect(formatStamp(parseStamp(s)!)).toBe(s)
expect(parseStamp("<2026-11-14 Sat]")).toBeUndefined()
expect(dayOf("11-03", new Date(2026, 0, 1))).toEqual({ active: true, date: "2026-11-03" })
expect(dayOf("2026-02-30")).toBeUndefined()
expect(dayOf("soon")).toBeUndefined()
})
test("links by type: a feed item, a task by id, a web page", () => {
expect(linksIn("Made [[item:i-hero][the trailer]], see [[id:t-cast]] and [[https://raea.io]]").map((l) => [l.type, l.path, l.desc])).toEqual([
["item", "i-hero", "the trailer"],
["id", "t-cast", undefined],
["https", "//raea.io", undefined],
])
expect(linkText("Grade [[item:i-hero][the trailer]] after [[id:t-1]]")).toBe("Grade the trailer after t-1")
})
})
+55
View File
@@ -0,0 +1,55 @@
// PL6: the React side (src/react.tsx): a plan read from a source that changes, and the components drawn as plain
// elements. Run by the app's vitest, which has react-dom (apps/app vite.config.ts test.include).
import { renderToStaticMarkup } from "react-dom/server"
import { describe, expect, test } from "vitest"
import { readPlan } from "../src"
import { Agenda, BoardLanes, memorySource, PlanOutline, TaskLine, toggled, usePlan } from "../src/react"
const TEXT = "* Act one\n** TODO [#A] Rome storyboard [0/1]\n:PROPERTIES:\n:ID: t-rome\n:END:\n*** TODO The forum\nDEADLINE: <2026-11-14 Sat>\n:PROPERTIES:\n:ID: t-forum\n:END:\n** DONE Cast\n"
describe("PL6: React", () => {
test("TaskLine: a checkbox, the words, priority, progress, deadline; a heading has no checkbox", () => {
const p = readPlan(TEXT)
const html = renderToStaticMarkup(<TaskLine task={p.entries[1]} onToggle={() => {}} />)
expect(html).toContain('data-task="t-rome"')
expect(html).toContain('role="checkbox" aria-checked="false"')
expect(html).toContain('<span data-part="priority">A</span>')
expect(html).toContain('<span data-part="text">Rome storyboard</span>')
expect(html).toContain('<span data-part="progress">0/1</span>')
expect(renderToStaticMarkup(<TaskLine task={p.entries[0]} />)).not.toContain("checkbox")
})
test("the outline nests, the board has its lanes, the agenda its days", () => {
const p = readPlan(TEXT)
const outline = renderToStaticMarkup(<PlanOutline plan={p} />)
expect(outline.indexOf("The forum")).toBeGreaterThan(outline.indexOf("Rome storyboard"))
expect(outline.match(/<ul/g)!.length).toBe(3)
const board = renderToStaticMarkup(<BoardLanes plan={p} labels={{ todo: "Next" }} />)
expect(board).toMatch(/data-state="todo"><h3>Next <span data-part="count">2<\/span>/)
expect(board).toMatch(/data-state="done"><h3>Done <span data-part="count">1<\/span>/)
const agenda = renderToStaticMarkup(<Agenda plan={p} from="2026-11-14" days={2} />)
expect(agenda).toMatch(/data-date="2026-11-14"><h3>2026-11-14<\/h3><ul><li data-why="deadline">.*The forum/)
})
test("usePlan reads a source and edits it by id; a source of text alone is read-only", () => {
const src = memorySource(TEXT)
let seen: ReturnType<typeof usePlan> | undefined
const Probe = () => {
seen = usePlan(src)
return null
}
renderToStaticMarkup(<Probe />)
expect(seen!.plan.tasks.length).toBe(3)
seen!.edit([toggled(seen!.plan.tasks[1])])
expect(readPlan(src.read()!).tasks[1].state).toBe("done")
expect(src.read()).toContain("** TODO [#A] Rome storyboard [1/1]")
renderToStaticMarkup(<Probe />)
expect(seen!.plan.tasks[1].state).toBe("done")
const Fixed = () => {
seen = usePlan(TEXT)
return null
}
renderToStaticMarkup(<Fixed />)
expect(() => seen!.edit([])).toThrow(/read-only/)
})
})
+91
View File
@@ -0,0 +1,91 @@
// PL5: a plan's tools for an agent (src/tools.ts), answered on a plan in memory the way the app and a headless run do.
import { describe, expect, test } from "vitest"
import { answerPlanTool, applyEdits, find, readPlan, planToolEdits, type PlanToolHost } from "../src"
const NOW = new Date(2026, 10, 14, 16, 40)
const START = `#+TITLE: Stay
#+TODO: TODO MAKING REVIEW | DONE DROPPED
* Look
** TODO Light the door
:PROPERTIES:
:ID: t-door
:END:
- [ ] warm key
- [ ] cool fill
`
/** A host on a plan in memory: the page's and the headless feed's, minus where the text is kept. */
function host(text = START): PlanToolHost & { now: () => string } {
let n = 0
let at = text
return {
who: "a-light",
text: () => at,
apply: (edits) => {
const r = applyEdits(at, edits, { now: NOW, newId: () => `t-new${++n}` })
at = r.text
return r
},
now: () => at,
}
}
describe("an agent's plan tools", () => {
test("plan_read gives the open tasks by id, and the whole file with full", async () => {
const h = host()
const r = (await answerPlanTool("plan_read", {}, h)) as { file: string; open: string; text?: string }
expect(r.file).toBe("plan.org")
expect(r.open).toContain("t-door TODO Light the door")
expect(r.text).toBeUndefined()
expect(((await answerPlanTool("plan_read", { full: true }, h)) as { text: string }).text).toBe(START)
})
test("plan_add writes tasks under their stage, held by the agent that asked unless it names others", async () => {
const h = host()
const r = (await answerPlanTool("plan_add", { tasks: [{ title: "Grade the hall", under: "Look", priority: "A", deadline: "2026-11-20", tags: ["look"] }, { title: "Score it", agents: ["a-score"] }] }, h)) as { ids: string[] }
expect(r.ids).toEqual(["t-new1", "t-new2"])
const plan = readPlan(h.now())
expect(find(plan, "t-new1")).toMatchObject({ stage: "Look", level: 2, priority: "A", agents: ["a-light"], tags: ["look"], deadline: { date: "2026-11-20" } })
expect(find(plan, "t-new2")).toMatchObject({ level: 1, agents: ["a-score"] })
expect(h.now()).toContain("** TODO [#A] Grade the hall")
})
test("plan_update marks, ticks, adds a checkbox, moves and sets fields by id", async () => {
const h = host()
await answerPlanTool("plan_update", { changes: [{ id: "t-door", state: "making", check: 0, add_check: "rim light", item: "i-door-2" }] }, h)
const t = find(readPlan(h.now()), "t-door")!
expect([t.keyword, t.item, t.checks.map((c) => `${c.done ? "x" : " "} ${c.text}`)]).toEqual(["MAKING", "i-door-2", ["x warm key", " cool fill", " rim light"]])
expect(t.progress).toEqual({ done: 1, total: 3 })
})
test("plan_close closes with CLOSED, the item it made and a note; dropped keeps the task", async () => {
const h = host()
await answerPlanTool("plan_close", { id: "t-door", item: "i-door-3", note: "Warm key at 3200K." }, h)
expect(h.now()).toContain("** DONE Light the door\nCLOSED: [2026-11-14 Sat 16:40]")
expect(h.now()).toContain(":ITEM: i-door-3")
expect(h.now()).toContain("Warm key at 3200K.")
const d = host()
await answerPlanTool("plan_close", { id: "t-door", state: "dropped" }, d)
expect(find(readPlan(d.now()), "t-door")!.state).toBe("dropped")
})
test("a wrong input or a task that isn't there is said, and nothing is written", async () => {
const h = host()
expect(() => planToolEdits("plan_add", { tasks: [] }, "a")).toThrow(/at least one/)
expect(() => planToolEdits("plan_update", { changes: [{ id: "t-door" }] }, "a")).toThrow(/nothing to change/)
expect(() => planToolEdits("plan_close", { id: "t-door", state: "making" }, "a")).toThrow(/done or dropped/)
await expect(answerPlanTool("plan_close", { id: "t-door", state: "MAKING" }, h)).rejects.toThrow(/MAKING doesn't close/)
await expect(answerPlanTool("plan_close", { id: "t-gone" }, h)).rejects.toThrow(/no task t-gone/)
await expect(answerPlanTool("plan_add", { tasks: [{ title: "x", under: "t-gone" }] }, h)).rejects.toThrow(/no task t-gone/)
expect(h.now()).toBe(START)
})
test("plan_read gives a task written by hand without an id one first, so the agent never names a task by its place", async () => {
const h = host(`${START}** TODO Written in Emacs\n`)
const r = (await answerPlanTool("plan_read", {}, h)) as { open: string }
expect(r.open).toContain("t-new1 TODO Written in Emacs")
expect(r.open).not.toMatch(/#\d/)
expect(h.now()).toContain("** TODO Written in Emacs\n:PROPERTIES:\n:ID: t-new1\n:END:\n")
})
})
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true,
"noUnusedLocals": true,
"lib": ["ES2023", "DOM"]
},
"include": ["src"]
}
+1 -1
Submodule skills updated: c293caacb2...e2490012a5.