@dibs.ai/dibs 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/package.json +79 -4
- package/schema.json +33 -0
- package/src/cli/index.ts +98 -0
- package/src/cli/mcp.ts +79 -0
- package/src/core/adapters/dex/README.md +40 -0
- package/src/core/adapters/dex/dex.schema.json +17 -0
- package/src/core/adapters/dex/index.ts +82 -0
- package/src/core/adapters/sync-all.ts +15 -0
- package/src/core/adapters/sync.ts +81 -0
- package/src/core/adapters/things/README.md +49 -0
- package/src/core/adapters/things/index.ts +73 -0
- package/src/core/adapters/things/things.schema.json +17 -0
- package/src/core/ctx.ts +6 -0
- package/src/core/identity.ts +19 -0
- package/src/core/panel.ts +39 -0
- package/src/core/store.ts +184 -0
- package/src/core/tasks.ts +161 -0
- package/src/core/todo.ts +80 -0
- package/src/core/util.ts +59 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { mkdirSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { type Task, toTask } from "../todo.ts";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { readJsonl, withLock } from "../util.ts";
|
|
6
|
+
import { ParentError, runFile } from "../tasks.ts";
|
|
7
|
+
|
|
8
|
+
// An external todo app. Tasks use dibs's shape; ids are the app's own.
|
|
9
|
+
export interface Adapter {
|
|
10
|
+
name: string;
|
|
11
|
+
// Fields the app can hold; others are neither pushed nor pulled. Default: all.
|
|
12
|
+
fields?: readonly (typeof fields)[number][];
|
|
13
|
+
list(): Promise<Task[]>;
|
|
14
|
+
create(task: Task): Promise<string>;
|
|
15
|
+
update(id: string, patch: Partial<Task>): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Each link remembers both ids and the task as of the last sync, so a 3-way compare tells which side changed.
|
|
19
|
+
interface Link { local: string; remote: string; base: Task }
|
|
20
|
+
const toLink = (r: Record<string, unknown>): Link => {
|
|
21
|
+
if (typeof r.local !== "string" || typeof r.remote !== "string") throw new Error("bad link ids");
|
|
22
|
+
return { local: r.local, remote: r.remote, base: toTask(r.base) };
|
|
23
|
+
};
|
|
24
|
+
const fields = ["name", "description", "completed", "started_at", "result", "parent"] as const;
|
|
25
|
+
|
|
26
|
+
// Two-way sync of the dibs todos file with one adapter. Per field: only one side changed -> copy it; both -> dibs wins.
|
|
27
|
+
// With `human`, only tasks whose human matches take part; the rest are left untouched.
|
|
28
|
+
// Deletions are never propagated: a task missing on one side just stays unlinked.
|
|
29
|
+
export async function sync(file: string, base: string, adapter: Adapter, human?: string): Promise<void> {
|
|
30
|
+
const linksFile = join(base, "sync", `${adapter.name}.jsonl`);
|
|
31
|
+
mkdirSync(join(base, "sync"), { recursive: true });
|
|
32
|
+
return withLock(linksFile, async () => {
|
|
33
|
+
const links = readJsonl(linksFile, toLink);
|
|
34
|
+
// Links are saved even if a later step throws, so created tasks are never duplicated next sync.
|
|
35
|
+
try {
|
|
36
|
+
const local: Task[] = JSON.parse(await runFile(file, ["list"])).filter((t: Task) => human === undefined || t.human === human);
|
|
37
|
+
const remote = await adapter.list();
|
|
38
|
+
const byLocal = new Map(local.map((t) => [t.id, t])), byRemote = new Map(remote.map((t) => [t.id, t]));
|
|
39
|
+
const toRemote = new Map(links.map((l) => [l.local, l.remote])), toLocal = new Map(links.map((l) => [l.remote, l.local]));
|
|
40
|
+
const norm = (t: Task): Task => ({ id: t.id, name: t.name, completed: t.completed, started_at: t.started_at ?? null, description: t.description || undefined, parent: t.parent || undefined, result: t.result || undefined });
|
|
41
|
+
// A rejected parent is cleared ("" overrides the stored value) so one bad link doesn't abort the sync. Returns the saved record.
|
|
42
|
+
const put = async (t: Task): Promise<Task> => {
|
|
43
|
+
try { await runFile(file, ["put", JSON.stringify(t)]); } catch (e) { if (!(e instanceof ParentError)) throw e; await runFile(file, ["put", JSON.stringify({ ...t, parent: "" })]); }
|
|
44
|
+
return norm(JSON.parse(await runFile(file, ["list"]) as string).find((x: Task) => x.id === t.id));
|
|
45
|
+
};
|
|
46
|
+
// Parents first, so a child's parent is already linked when it is created.
|
|
47
|
+
const depth = (t: Task, m: Map<string, Task>, n = 0): number => t.parent && m.has(t.parent) && n < 50 ? depth(m.get(t.parent)!, m, n + 1) + 1 : 0;
|
|
48
|
+
for (const t of [...local].sort((a, b) => depth(a, byLocal) - depth(b, byLocal))) {
|
|
49
|
+
if (toRemote.has(t.id)) continue;
|
|
50
|
+
// Only synced fields go out, so local-only ones (claimed_by) never reach the adapter.
|
|
51
|
+
const id = await adapter.create({ id: t.id, ...Object.fromEntries((adapter.fields ?? fields).map((f) => [f, t[f]])), parent: t.parent && toRemote.get(t.parent) } as Task);
|
|
52
|
+
toRemote.set(t.id, id); toLocal.set(id, t.id);
|
|
53
|
+
links.push({ local: t.id, remote: id, base: norm(t) });
|
|
54
|
+
}
|
|
55
|
+
for (const r of [...remote].sort((a, b) => depth(a, byRemote) - depth(b, byRemote))) {
|
|
56
|
+
if (toLocal.has(r.id)) continue;
|
|
57
|
+
const t = norm({ ...r, id: crypto.randomUUID(), parent: r.parent && toLocal.get(r.parent) });
|
|
58
|
+
const saved = await put(human === undefined ? t : { ...t, human }); // pulled tasks join the filtered set
|
|
59
|
+
toRemote.set(t.id, r.id); toLocal.set(r.id, t.id);
|
|
60
|
+
links.push({ local: t.id, remote: r.id, base: saved });
|
|
61
|
+
}
|
|
62
|
+
for (const link of links) {
|
|
63
|
+
const l = byLocal.get(link.local), r = byRemote.get(link.remote);
|
|
64
|
+
if (!l || !r) continue;
|
|
65
|
+
const lv = norm(l), rv = norm({ ...r, id: l.id, parent: r.parent && toLocal.get(r.parent) }), b = link.base;
|
|
66
|
+
const push: Partial<Task> = {}, pull: Partial<Task> = {};
|
|
67
|
+
for (const f of adapter.fields ?? fields) {
|
|
68
|
+
// Skip values the remote already has, so adapters needn't re-read to avoid no-op writes.
|
|
69
|
+
if (lv[f] !== b[f]) { if (lv[f] !== rv[f]) (push as Record<string, unknown>)[f] = lv[f]; }
|
|
70
|
+
else if (rv[f] !== b[f]) (pull as Record<string, unknown>)[f] = rv[f];
|
|
71
|
+
}
|
|
72
|
+
if (Object.keys(push).length) await adapter.update(r.id, { ...push, parent: push.parent && toRemote.get(push.parent), result: lv.result });
|
|
73
|
+
link.base = Object.keys(pull).length ? await put({ id: lv.id, ...Object.fromEntries(Object.entries(pull).map(([k, v]) => [k, v ?? ""])) } as Task) : { ...lv };
|
|
74
|
+
}
|
|
75
|
+
} finally {
|
|
76
|
+
const temp = `${linksFile}.${randomUUID()}.tmp`;
|
|
77
|
+
writeFileSync(temp, links.map((l) => JSON.stringify(l)).join("\n") + "\n");
|
|
78
|
+
renameSync(temp, linksFile);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Things 3 adapter
|
|
2
|
+
|
|
3
|
+
Syncs dibs's todo store with [Things 3](https://culturedcode.com/things/) on macOS. Writes use the [Things URL scheme](https://culturedcode.com/things/support/articles/2803573/); reads use Things' AppleScript dictionary through `osascript`, because the URL scheme cannot read tasks.
|
|
4
|
+
|
|
5
|
+
## Connect
|
|
6
|
+
|
|
7
|
+
1. Install Things 3 on the Mac that runs Pi.
|
|
8
|
+
2. Enable the URL scheme and copy the auth token: Things → Settings → General → Enable Things URLs → Manage.
|
|
9
|
+
3. Save the token in Pi:
|
|
10
|
+
```
|
|
11
|
+
/todos connect things <token>
|
|
12
|
+
```
|
|
13
|
+
It is written to `~/.dibs/adapters/things.json` with `0600` permissions, never to a `config.json` (which may be committed). `DIBS_THINGS_TOKEN` overrides the file.
|
|
14
|
+
4. Turn sync on in an dibs `config.json` (global `~/.dibs/config.json` or the project's):
|
|
15
|
+
```json
|
|
16
|
+
{"adapters": {"things": {"sync": true}}}
|
|
17
|
+
```
|
|
18
|
+
5. Run `/reload` in Pi. On the first read, macOS asks to let Pi's terminal control Things 3 (System Settings → Privacy & Security → Automation); allow it.
|
|
19
|
+
|
|
20
|
+
To disconnect, set `"sync": false` or remove the entry, and delete `~/.dibs/adapters/things.json`. Tasks already synced stay on both sides.
|
|
21
|
+
|
|
22
|
+
## Projects
|
|
23
|
+
|
|
24
|
+
Each dibs project syncs with the Things project of the same name (the project folder's name, or its name in `~/.dibs/projects/projects.jsonl`). dibs creates the Things project with the first new task. Only to-dos in that project sync; to-dos you move out of it stop syncing.
|
|
25
|
+
|
|
26
|
+
## Capabilities
|
|
27
|
+
|
|
28
|
+
| Field | dibs → Things | Things → dibs |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| Create to-do | yes | yes |
|
|
31
|
+
| Name → title (todo.txt priority, `+project`, `@context` stay as text) | yes | yes |
|
|
32
|
+
| Description → notes | yes | yes |
|
|
33
|
+
| Completed (and un-completed) | yes | yes |
|
|
34
|
+
|
|
35
|
+
- Two-way, with the same rules as every adapter: each list or change in dibs syncs both ways. Per field, dibs copies across a change made on one side since the last sync, and dibs wins when both sides changed the field.
|
|
36
|
+
- dibs pulls changes made in Things on its next action and before each prompt.
|
|
37
|
+
- State: links and last-synced copies live in `sync/things.jsonl` next to the store's `config.json`.
|
|
38
|
+
|
|
39
|
+
## Limitations
|
|
40
|
+
|
|
41
|
+
- macOS only.
|
|
42
|
+
- Canceled to-dos are skipped.
|
|
43
|
+
- Renaming either project breaks the match; dibs then creates a new Things project.
|
|
44
|
+
- Not synced: started time, result, parent/subtasks (Things has projects, headings and checklists rather than subtasks), and Things' when/deadline, tags, areas, projects, headings and checklists.
|
|
45
|
+
- Deletions are never propagated in either direction.
|
|
46
|
+
- The URL scheme does not return the new to-do's id to a command-line caller. dibs tags the notes with a temporary `[dibs:<id>]` marker, waits up to about 5 seconds to find the to-do, then removes the marker. If Things takes longer, the sync fails and retries, and the retry can create a duplicate.
|
|
47
|
+
- Adding uses `open -g` so Things stays in the background, but macOS may still launch it.
|
|
48
|
+
- No live updates: Things has no folder to watch.
|
|
49
|
+
- A sync failure shows as a notice and does not block the local change.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { Ctx } from "../../ctx.ts";
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import type { Task } from "../../todo.ts";
|
|
6
|
+
import type { Adapter } from "../sync.ts";
|
|
7
|
+
import { dibsHome } from "../../store.ts";
|
|
8
|
+
|
|
9
|
+
// The auth token is a secret: kept in ~/.dibs/adapters/things.json (0600), never in a config.json that may be committed.
|
|
10
|
+
const tokenFile = () => join(dibsHome(), "adapters", "things.json");
|
|
11
|
+
export function saveThingsToken(token: string): string {
|
|
12
|
+
if (!/^[\w-]+$/.test(token)) throw new Error("Invalid Things auth token");
|
|
13
|
+
mkdirSync(join(dibsHome(), "adapters"), { recursive: true });
|
|
14
|
+
writeFileSync(tokenFile(), JSON.stringify({ token }) + "\n", { mode: 0o600 });
|
|
15
|
+
chmodSync(tokenFile(), 0o600);
|
|
16
|
+
return `Saved Things auth token to ${tokenFile()}`;
|
|
17
|
+
}
|
|
18
|
+
function token(): string {
|
|
19
|
+
if (process.env.DIBS_THINGS_TOKEN) return process.env.DIBS_THINGS_TOKEN;
|
|
20
|
+
try { return JSON.parse(readFileSync(tokenFile(), "utf8")).token; }
|
|
21
|
+
catch { throw new Error("Things auth token missing: run /todos connect things <token>"); }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Marks a new to-do's notes so the next read can find its Things id (the URL scheme cannot return it to a CLI).
|
|
25
|
+
const marker = /\n*\[dibs:([\w-]+)\]\s*$/;
|
|
26
|
+
// The URL scheme writes but cannot read, so reads go through Things' AppleScript dictionary (JXA).
|
|
27
|
+
// Each dibs project syncs with the Things project of the same name; the name is passed as argv, never spliced into code.
|
|
28
|
+
const LIST = `function run([name]) { const p = Application("Things3").projects.whose({ name })(); return p.length ? JSON.stringify(p[0].toDos().map(t => ({ id: t.id(), name: t.name(), notes: t.notes(), status: t.status() }))) : "null"; }`;
|
|
29
|
+
|
|
30
|
+
export function thingsAdapter(ctx: Ctx, project: string): Adapter {
|
|
31
|
+
if (process.platform !== "darwin") throw new Error("Things adapter needs macOS");
|
|
32
|
+
const open = async (command: string, params: Record<string, string | undefined>) => {
|
|
33
|
+
const query = Object.entries(params).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}=${encodeURIComponent(v!)}`).join("&");
|
|
34
|
+
const r = await ctx.exec("open", ["-g", `things:///${command}?${query}`]);
|
|
35
|
+
if (r.code !== 0) throw new Error(r.stderr || `open exited ${r.code}`);
|
|
36
|
+
};
|
|
37
|
+
const read = async () => {
|
|
38
|
+
const r = await ctx.exec("osascript", ["-l", "JavaScript", "-e", LIST, project]);
|
|
39
|
+
if (r.code !== 0) throw new Error(r.stderr || `osascript exited ${r.code}`);
|
|
40
|
+
const data = JSON.parse(r.stdout);
|
|
41
|
+
if (data === null) return null; // project not created yet
|
|
42
|
+
if (!Array.isArray(data)) throw new Error("Invalid Things to-do list");
|
|
43
|
+
return data as { id: string; name: string; notes: string; status: string }[];
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
name: "things",
|
|
47
|
+
fields: ["name", "description", "completed"],
|
|
48
|
+
async list() {
|
|
49
|
+
return ((await read()) ?? []).filter((t) => t.status !== "canceled" && t.name.trim()).map((t) => ({ id: t.id, name: t.name.replace(/[\r\n]+/g, " ").trim(), description: t.notes.replace(marker, "") || undefined, completed: t.status === "completed", started_at: null }));
|
|
50
|
+
},
|
|
51
|
+
async create(task) {
|
|
52
|
+
const auth = token(); // fail before adding, so a missing token can't leave an unlinked to-do
|
|
53
|
+
const key = randomUUID();
|
|
54
|
+
const todo = { title: task.name, notes: `${task.description ?? ""}\n\n[dibs:${key}]`, completed: task.completed || undefined };
|
|
55
|
+
// A missing project is created together with its first to-do in one json call, so the to-do can't land in the Inbox.
|
|
56
|
+
if (await read()) await open("add", { list: project, title: todo.title, notes: todo.notes, completed: task.completed ? "true" : undefined });
|
|
57
|
+
else await open("json", { data: JSON.stringify([{ type: "project", attributes: { title: project, items: [{ type: "to-do", attributes: todo }] } }]) });
|
|
58
|
+
// shortcut: polls up to ~5s for Things to save the new to-do; a slower Things fails this sync and retries later (possible duplicate).
|
|
59
|
+
for (let i = 0; i < 20; i++) {
|
|
60
|
+
const found = ((await read()) ?? []).find((t) => t.notes.match(marker)?.[1] === key);
|
|
61
|
+
if (found) { await open("update", { id: found.id, "auth-token": auth, notes: task.description ?? "" }); return found.id; }
|
|
62
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
63
|
+
}
|
|
64
|
+
throw new Error(`Things did not save "${task.name}"`);
|
|
65
|
+
},
|
|
66
|
+
async update(id, patch) {
|
|
67
|
+
// sync() only sends fields that differ from Things' state, so no re-read here.
|
|
68
|
+
const params = { title: patch.name, notes: "description" in patch ? patch.description ?? "" : undefined, completed: patch.completed === undefined ? undefined : String(patch.completed) };
|
|
69
|
+
if (Object.values(params).every((v) => v === undefined)) return;
|
|
70
|
+
await open("update", { id, "auth-token": token(), ...params });
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"title": "dibs Things adapter",
|
|
4
|
+
"type": "object",
|
|
5
|
+
"additionalProperties": false,
|
|
6
|
+
"properties": {
|
|
7
|
+
"sync": {
|
|
8
|
+
"type": "boolean",
|
|
9
|
+
"description": "Two-way sync with the same-named Things 3 project (macOS). The auth token is set with /todos connect things, never here."
|
|
10
|
+
},
|
|
11
|
+
"human": {
|
|
12
|
+
"type": "string",
|
|
13
|
+
"minLength": 1,
|
|
14
|
+
"description": "Only sync tasks whose human matches this GitHub username; \"me\" is you. Tasks with no human are skipped."
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
package/src/core/ctx.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { Ctx } from "./ctx.ts";
|
|
4
|
+
import { dibsHome } from "./store.ts";
|
|
5
|
+
|
|
6
|
+
export const agentName = () => process.env.DIBS_AGENT || "cli";
|
|
7
|
+
|
|
8
|
+
// GitHub username of the person at the keyboard: DIBS_USER, else git config, else gh; cached in <dibsHome>/user so the lookup runs at most once. Never throws.
|
|
9
|
+
export async function ghUser(ctx: Ctx): Promise<string | undefined> {
|
|
10
|
+
if (process.env.DIBS_USER) return process.env.DIBS_USER;
|
|
11
|
+
const cache = join(dibsHome(), "user");
|
|
12
|
+
try { const cached = readFileSync(cache, "utf8").trim(); if (cached) return cached; } catch {}
|
|
13
|
+
for (const [cmd, args] of [["git", ["config", "github.user"]], ["gh", ["api", "user", "--jq", ".login"]]] as const) {
|
|
14
|
+
try {
|
|
15
|
+
const r = await ctx.exec(cmd, [...args]), user = r.stdout.trim();
|
|
16
|
+
if (r.code === 0 && user) { try { mkdirSync(dibsHome(), { recursive: true }); writeFileSync(cache, user + "\n"); } catch {} return user; }
|
|
17
|
+
} catch {}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Task } from "./todo.ts";
|
|
2
|
+
|
|
3
|
+
// The task panel's content, shared by every agent UI (Pi widget, Claude Code mod, opencode plugin).
|
|
4
|
+
export const views = ["current", "project", "completed"] as const;
|
|
5
|
+
export type View = (typeof views)[number];
|
|
6
|
+
export type Row = { id: string; name: string; state: "done" | "started" | "open" };
|
|
7
|
+
export type Panel = { title: string; rows: Row[]; more: number; empty: string | null };
|
|
8
|
+
|
|
9
|
+
// Current = tasks this session touched plus their subtasks from anywhere; unrelated new tasks stay in Project.
|
|
10
|
+
export function shown(tasks: Task[], view: View, mine: Set<string>): Task[] {
|
|
11
|
+
if (view === "completed") return tasks.filter((t) => t.completed);
|
|
12
|
+
if (view === "project") return tasks.filter((t) => !t.completed);
|
|
13
|
+
const byId = new Map(tasks.map((t) => [t.id, t]));
|
|
14
|
+
const memo = new Map<string, boolean>();
|
|
15
|
+
const current = (t: Task | undefined, depth = 0): boolean => {
|
|
16
|
+
if (!t || depth >= 50) return false;
|
|
17
|
+
if (!memo.has(t.id)) memo.set(t.id, mine.has(t.id) || current(t.parent ? byId.get(t.parent) : undefined, depth + 1));
|
|
18
|
+
return memo.get(t.id)!;
|
|
19
|
+
};
|
|
20
|
+
return tasks.filter((t) => current(t));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function panel(tasks: Task[], view: View, mine: Set<string>, max = 11): Panel {
|
|
24
|
+
const list = shown(tasks, view, mine);
|
|
25
|
+
const done = list.filter((t) => t.completed).length;
|
|
26
|
+
const label = { current: "Current", project: "Project", completed: "Completed" }[view];
|
|
27
|
+
const count = view === "project" ? `${list.length} open` : view === "completed" ? `${list.length}` : `${done}/${list.length}`;
|
|
28
|
+
return {
|
|
29
|
+
title: `${label} tasks (${count})`,
|
|
30
|
+
rows: list.slice(0, max).map((t) => ({ id: t.id, name: t.name.replace(/\s+/g, " ").trim(), state: t.completed ? "done" : t.started_at ? "started" : "open" })),
|
|
31
|
+
more: Math.max(0, list.length - max),
|
|
32
|
+
empty: list.length ? null : view === "current" ? "No tasks worked on in this session yet" : "None",
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const glyph = { done: "✓", started: "◐", open: "○" } as const;
|
|
37
|
+
|
|
38
|
+
// Plain-text form, for status lines and terminals without a widget API.
|
|
39
|
+
export const panelText = (p: Panel) => [p.title, ...(p.empty ? [` ${p.empty}`] : p.rows.map((r) => ` ${glyph[r.state]} #${r.id} ${r.name}`)), ...(p.more ? [` +${p.more} more`] : [])].join("\n");
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import type { Ctx } from "./ctx.ts";
|
|
2
|
+
import { appendFileSync, cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir, tmpdir } from "node:os";
|
|
4
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { home, readJsonl } from "./util.ts";
|
|
7
|
+
import { findId, runFile } from "./tasks.ts";
|
|
8
|
+
|
|
9
|
+
const { version } = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
|
|
10
|
+
// Pinned to this install's version so editors validate against the options it supports. Tag v<version> on release.
|
|
11
|
+
export const schemaUrl = `https://raw.githubusercontent.com/arobida/dibs/v${version}/schema.json`;
|
|
12
|
+
|
|
13
|
+
// JSONC: drops comments, then trailing commas (second pass catches a comma that sat before a comment); strings are kept as-is.
|
|
14
|
+
const stripJsonc = (t: string) => t.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\/|,(\s*[}\]])/g, (_m, str, close) => str ?? close ?? "");
|
|
15
|
+
export function parseJsonc(text: string, path: string): any {
|
|
16
|
+
if (!text.trim()) return {};
|
|
17
|
+
let config: any;
|
|
18
|
+
try { config = JSON.parse(stripJsonc(stripJsonc(text))); } catch (error: any) { throw new Error(`Invalid JSON in ${path}: ${error.message}`); }
|
|
19
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error(`${path} must hold a JSON object`);
|
|
20
|
+
return config;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const writeConfig = (dir: string, config: object) => writeFileSync(join(dir, "config.json"), JSON.stringify({ $schema: schemaUrl, ...config }, null, 2) + "\n");
|
|
24
|
+
const ensureConfig = (dir: string) => { readConfig(dir); if (!existsSync(join(dir, "config.json"))) writeConfig(dir, {}); };
|
|
25
|
+
|
|
26
|
+
// <dir>/config.json (JSONC). Keeps "$schema" pointed at this version.
|
|
27
|
+
export function readConfig(dir: string): { adapters?: Record<string, { sync?: boolean; human?: string }>; file?: string; scope?: string; id?: string } {
|
|
28
|
+
const path = join(dir, "config.json");
|
|
29
|
+
let text: string;
|
|
30
|
+
try { text = readFileSync(path, "utf8"); }
|
|
31
|
+
catch (error: any) { if (error.code === "ENOENT") return {}; throw new Error(`Cannot read ${path}: ${error.message}`); }
|
|
32
|
+
const config = parseJsonc(text, path);
|
|
33
|
+
// Text replace, not a rewrite, so the user's comments survive.
|
|
34
|
+
if (typeof config.$schema === "string" && config.$schema !== schemaUrl) writeFileSync(path, text.replace(JSON.stringify(config.$schema), JSON.stringify(schemaUrl)));
|
|
35
|
+
if (config.backend !== undefined) throw new Error(`"backend" was replaced by "adapters" in ${path}`);
|
|
36
|
+
if (config.adapters !== undefined && (typeof config.adapters !== "object" || Array.isArray(config.adapters) || Object.entries(config.adapters).some(([k, v]: [string, any]) => !["dex", "things"].includes(k) || !v || typeof v !== "object" || (v.sync !== undefined && typeof v.sync !== "boolean") || (v.human !== undefined && (typeof v.human !== "string" || !v.human.trim()))))) throw new Error(`Invalid adapters in ${path}`);
|
|
37
|
+
if (config.file !== undefined && (typeof config.file !== "string" || !config.file.trim())) throw new Error(`Invalid file in ${path}`);
|
|
38
|
+
if (config.scope !== undefined && !["project", "global", "temp"].includes(config.scope)) throw new Error(`Invalid scope in ${path}`);
|
|
39
|
+
if (config.id !== undefined && (typeof config.id !== "string" || !/^[\w-]+$/.test(config.id))) throw new Error(`Invalid id in ${path}`);
|
|
40
|
+
return config;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Adds the project id to an existing config by text insert after the opening brace, keeping comments.
|
|
44
|
+
function addId(dir: string, id: string) {
|
|
45
|
+
const path = join(dir, "config.json"), config = readConfig(dir);
|
|
46
|
+
if (!existsSync(path)) return writeConfig(dir, { id });
|
|
47
|
+
const text = readFileSync(path, "utf8");
|
|
48
|
+
if (!text.trim()) return writeConfig(dir, { id });
|
|
49
|
+
const comma = Object.keys(config).length ? "," : "";
|
|
50
|
+
writeFileSync(path, text.replace(/^(\s*(?:\/\/[^\n]*\n\s*|\/\*[\s\S]*?\*\/\s*)*)\{/, `$1{\n "id": ${JSON.stringify(id)}${comma}`));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// One line of ~/.dibs/projects/projects.jsonl.
|
|
54
|
+
export interface Project { id: string; name: string; path: string; scope: string; created: string }
|
|
55
|
+
const toProject = (r: Record<string, unknown>): Project => {
|
|
56
|
+
for (const k of ["id", "name", "path", "scope", "created"]) if (typeof r[k] !== "string") throw new Error(`bad ${k}`);
|
|
57
|
+
return r as unknown as Project;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// Falls back to the old .pi-do folder when only that exists, so existing stores keep working.
|
|
61
|
+
const withLegacy = (dir: string) => existsSync(dir) || !existsSync(dir.replace(/\.dibs$/, ".pi-do")) ? dir : dir.replace(/\.dibs$/, ".pi-do");
|
|
62
|
+
export const dibsHome = () => process.env.DIBS_HOME || withLegacy(join(homedir(), ".dibs"));
|
|
63
|
+
|
|
64
|
+
const registryFile = () => join(dibsHome(), "projects", "projects.jsonl");
|
|
65
|
+
function saveRegistry(projects: Project[]) {
|
|
66
|
+
const temp = `${registryFile()}.${randomUUID()}.tmp`;
|
|
67
|
+
writeFileSync(temp, projects.map((p) => JSON.stringify(p) + "\n").join("")); renameSync(temp, registryFile());
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface Settings { adapters: Record<string, { sync?: boolean; human?: string }>; file?: string; scope: string; base: string; local: string; name: string; id: string; registered: boolean }
|
|
71
|
+
|
|
72
|
+
export const localDir = (cwd: string) => existsSync(join(cwd, ".agents", "dibs")) ? join(cwd, ".agents/dibs") : withLegacy(join(cwd, ".dibs"));
|
|
73
|
+
export const globalDir = (s: { name: string; id: string }) => join(dibsHome(), "projects", `${s.name}.${s.id}`);
|
|
74
|
+
|
|
75
|
+
// The project's id lives in its local config.json (kept in place across scopes) and keys its projects.jsonl record.
|
|
76
|
+
// Scope: forceGlobal > env DIBS_SCOPE > the project's record scope > global config.json > "project".
|
|
77
|
+
export function settings(ctx: Ctx, forceGlobal = false): Settings {
|
|
78
|
+
const root = dibsHome(), cwd = resolve(ctx.cwd), trusted = ctx.trusted();
|
|
79
|
+
if (forceGlobal && !trusted) throw new Error("--global requires a trusted project");
|
|
80
|
+
const local = localDir(cwd);
|
|
81
|
+
const id: string = (trusted ? readConfig(local).id : undefined) ?? randomUUID();
|
|
82
|
+
const record = readJsonl(join(root, "projects", "projects.jsonl"), toProject).find((p) => p.id === id);
|
|
83
|
+
const globalConfig = readConfig(root);
|
|
84
|
+
const scope = forceGlobal ? "global" : process.env.DIBS_SCOPE || record?.scope || globalConfig.scope || "project";
|
|
85
|
+
if (!["project", "global", "temp"].includes(scope)) throw new Error(`Invalid dibs scope: ${scope}`);
|
|
86
|
+
const name = record?.name ?? basename(cwd);
|
|
87
|
+
// Untrusted projects use a temp store so dibs never writes into them.
|
|
88
|
+
const temp = !trusted && !forceGlobal || scope === "temp";
|
|
89
|
+
// Temp stores use the same layout as project stores, in a per-session folder.
|
|
90
|
+
const base = temp ? join(tmpdir(), "dibs", createHash("sha256").update(ctx.sessionId()).digest("hex"), ".dibs") : scope === "global" ? globalDir({ name, id }) : local;
|
|
91
|
+
const config = { ...globalConfig, ...(base ? readConfig(base) : {}) };
|
|
92
|
+
return { adapters: config.adapters ?? {}, file: process.env.DIBS_FILE || config.file, scope: temp ? "temp" : scope, base, local, name, id, registered: !!record };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export const helloWorld = () => JSON.stringify({ id: randomUUID(), name: "Hello World", completed: false, created: new Date().toISOString().slice(0, 10), started_at: null }) + "\n";
|
|
96
|
+
|
|
97
|
+
// Resolves the todos file, creating the dibs folder, config, list index, project registration and Hello World todo on first use.
|
|
98
|
+
export function storeFile(ctx: Ctx, s: Settings): string {
|
|
99
|
+
// ~/.dibs always exists: global config plus the projects registry. Its absence means this run is the installation.
|
|
100
|
+
const installing = !existsSync(join(dibsHome(), "config.json"));
|
|
101
|
+
mkdirSync(join(dibsHome(), "projects"), { recursive: true });
|
|
102
|
+
ensureConfig(dibsHome());
|
|
103
|
+
if (!existsSync(join(dibsHome(), "projects", "projects.jsonl"))) writeFileSync(join(dibsHome(), "projects", "projects.jsonl"), "");
|
|
104
|
+
if (s.file) return resolve(ctx.cwd, home(s.file));
|
|
105
|
+
const todos = join(s.base, "todos"), file = join(todos, `${s.name}.todos.jsonl`);
|
|
106
|
+
// Temp stores never write into the project or the registry.
|
|
107
|
+
if (s.scope !== "temp" && !readConfig(s.local).id) { mkdirSync(s.local, { recursive: true }); addId(s.local, s.id); }
|
|
108
|
+
if (!s.registered && s.scope !== "temp") {
|
|
109
|
+
appendFileSync(join(dibsHome(), "projects", "projects.jsonl"), JSON.stringify({ id: s.id, name: s.name, path: resolve(ctx.cwd), scope: s.scope, created: new Date().toISOString() }) + "\n");
|
|
110
|
+
s.registered = true;
|
|
111
|
+
} else if (s.scope !== "temp") {
|
|
112
|
+
// Last opened wins: a moved project re-registers its new path.
|
|
113
|
+
const projects = readJsonl(registryFile(), toProject), record = projects.find((p) => p.id === s.id);
|
|
114
|
+
if (record && record.path !== resolve(ctx.cwd)) { record.path = resolve(ctx.cwd); saveRegistry(projects); }
|
|
115
|
+
}
|
|
116
|
+
if (existsSync(file)) return file;
|
|
117
|
+
mkdirSync(todos, { recursive: true });
|
|
118
|
+
ensureConfig(s.base);
|
|
119
|
+
// Hello World onboards installation and new permanent stores; other temp stores start empty.
|
|
120
|
+
try { writeFileSync(file, s.scope === "temp" && !installing ? "" : helloWorld(), { flag: "wx", mode: 0o600 }); }
|
|
121
|
+
catch (error: any) { if (error.code === "EEXIST") return file; throw error; }
|
|
122
|
+
const created = new Date().toISOString();
|
|
123
|
+
appendFileSync(join(todos, "lists.jsonl"), JSON.stringify({ id: randomUUID(), name: s.name, file: basename(file), created }) + "\n");
|
|
124
|
+
return file;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Moves the project store between .dibs and .agents/dibs (todos, config, list index); never overwrites.
|
|
128
|
+
export function migrate(ctx: Ctx, target: string): string {
|
|
129
|
+
if (!ctx.trusted()) throw new Error("migrate requires a trusted project");
|
|
130
|
+
const s = settings(ctx);
|
|
131
|
+
if (s.scope !== "project" || s.file) throw new Error("migrate only moves a project-scope dibs folder; use /todos scope to change scope");
|
|
132
|
+
const to = join(resolve(ctx.cwd), target);
|
|
133
|
+
if (to === s.base) throw new Error(`Already stored in ${to}`);
|
|
134
|
+
if (existsSync(to)) throw new Error(`${to} already exists`);
|
|
135
|
+
mkdirSync(dirname(to), { recursive: true });
|
|
136
|
+
renameSync(s.base, to);
|
|
137
|
+
return `Moved ${s.base} to ${to}`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Switches scope and moves the todos folder with it; the local config.json (holding the project id) stays put.
|
|
141
|
+
export function setScope(ctx: Ctx, scope: string): string {
|
|
142
|
+
if (!ctx.trusted()) throw new Error("scope requires a trusted project");
|
|
143
|
+
const s = settings(ctx), registry = join(dibsHome(), "projects", "projects.jsonl");
|
|
144
|
+
if (s.file) throw new Error("scope does not apply to an explicit file");
|
|
145
|
+
storeFile(ctx, s); // registers the project and writes its id if needed
|
|
146
|
+
const projects = readJsonl(registry, toProject);
|
|
147
|
+
const record = projects.find((p) => p.id === s.id)!;
|
|
148
|
+
if (record.scope === scope) return `Already ${scope} scope`;
|
|
149
|
+
const [from, to] = scope === "global" ? [s.local, globalDir(s)] : [globalDir(s), s.local];
|
|
150
|
+
if (existsSync(join(to, "todos"))) throw new Error(`${join(to, "todos")} already exists`);
|
|
151
|
+
mkdirSync(to, { recursive: true });
|
|
152
|
+
ensureConfig(to);
|
|
153
|
+
// Copy then delete: project and home may be on different disks.
|
|
154
|
+
if (existsSync(join(from, "todos"))) { cpSync(join(from, "todos"), join(to, "todos"), { recursive: true, errorOnExist: true, force: false }); rmSync(join(from, "todos"), { recursive: true }); }
|
|
155
|
+
if (scope === "project") rmSync(from, { recursive: true, force: true });
|
|
156
|
+
record.scope = scope;
|
|
157
|
+
saveRegistry(projects);
|
|
158
|
+
return `Scope set to ${scope}: ${storeFile(ctx, settings(ctx))}`;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const findTask = (file: string, id: string): any => {
|
|
162
|
+
const items = JSON.parse(runFile(file, ["list"]) as string);
|
|
163
|
+
return items.find((t: any) => t.id === findId(items, id, file));
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
// `[name](dibs://<project-id>/<task-id>)`; only registered stores can be resolved later.
|
|
167
|
+
export function link(ctx: Ctx, id: string): string {
|
|
168
|
+
const s = settings(ctx);
|
|
169
|
+
if (s.scope === "temp" || s.file) throw new Error(`Cannot link: ${s.file ? "explicit-file" : "temp-scope"} stores are not registered, so the link could never be resolved`);
|
|
170
|
+
const t = findTask(storeFile(ctx, s), id);
|
|
171
|
+
return `[${t.name}](dibs://${s.id}/${t.id})`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Looks the project up in the registry and reads its store; never a stale copy at an old path.
|
|
175
|
+
export function resolveLink(url: string): string {
|
|
176
|
+
const m = url.match(/^dibs:\/\/([\w-]+)\/([\w-]+)$/);
|
|
177
|
+
if (!m) throw new Error(`Invalid dibs URL: ${url}`);
|
|
178
|
+
const p = readJsonl(registryFile(), toProject).find((r) => r.id === m[1]);
|
|
179
|
+
if (!p) throw new Error(`Unknown project: ${m[1]}`);
|
|
180
|
+
const local = localDir(p.path);
|
|
181
|
+
if (!existsSync(p.path) || readConfig(local).id !== p.id) throw new Error(`Project ${p.id} is no longer at ${p.path}; open pi in its new location to update the registry`);
|
|
182
|
+
const t = findTask(join(p.scope === "global" ? globalDir(p) : local, "todos", `${p.name}.todos.jsonl`), m[2]);
|
|
183
|
+
return `${t.name}\nState: ${t.completed ? "completed" : t.started_at ? "started" : "open"}\nResult: ${t.result ?? ""}`;
|
|
184
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core task store for dibs: run task actions against a JSONL todos file.
|
|
3
|
+
* @example
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { runFile } from "jsr:@dibs/dibs";
|
|
6
|
+
* console.log(await runFile(".dibs/todos/dibs.todos.jsonl", ["list"]));
|
|
7
|
+
* ```
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { basename, dirname } from "node:path";
|
|
12
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
13
|
+
import { checkName, clean, parseTodo, todoLine, toTask, type Task } from "./todo.ts";
|
|
14
|
+
import { isAlive, withLock } from "./util.ts";
|
|
15
|
+
|
|
16
|
+
/** Thrown when a task's parent is missing, is the task itself, or is one of its descendants. */
|
|
17
|
+
export class ParentError extends Error {}
|
|
18
|
+
// A parent must exist and must not be the task itself or one of its descendants.
|
|
19
|
+
function checkParent(items: Task[], id: string, parent?: string) {
|
|
20
|
+
const seen = new Set<string>();
|
|
21
|
+
for (let p = parent; p; p = items.find((item) => item.id === p)?.parent) {
|
|
22
|
+
if (p === id || seen.has(p)) throw new ParentError(`Parent cycle: ${parent} is or descends from ${id}`);
|
|
23
|
+
seen.add(p);
|
|
24
|
+
if (!items.some((item) => item.id === p)) throw new ParentError(`Parent task not found: ${p} (parent must be an existing task id; put details in description)`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Thrown when a blocker is missing, is the task itself, or forms a cycle. */
|
|
29
|
+
export class BlockerError extends Error {}
|
|
30
|
+
// Blockers must exist, not include the task itself, and not lead back to it through their own blockers.
|
|
31
|
+
function checkBlockers(items: Task[], id: string, blockers: string[] = []) {
|
|
32
|
+
for (const b of blockers) {
|
|
33
|
+
if (!items.some((item) => item.id === b)) throw new BlockerError(`Blocker task not found: ${b}`);
|
|
34
|
+
const seen = new Set<string>(), todo = [b];
|
|
35
|
+
for (let x = todo.pop(); x; x = todo.pop()) {
|
|
36
|
+
if (x === id) throw new BlockerError(`Blocker cycle: ${b} is or depends on ${id}`);
|
|
37
|
+
if (!seen.has(x)) { seen.add(x); todo.push(...(items.find((item) => item.id === x)?.blocked_by ?? [])); }
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const live = (task: Task) => !!task.claimed_by && isAlive(Number(task.claimed_by.split(":").pop()));
|
|
42
|
+
const ids = (s?: string) => (s ? s.split(",").map((x) => x.trim()).filter(Boolean) : undefined);
|
|
43
|
+
// Short project-prefixed ids (like Dex/Beads) so agents copy a few characters, not a UUID.
|
|
44
|
+
const prefix = (file: string) => (basename(file).replace(/\.todos\.jsonl$/, "").toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 4) || "task");
|
|
45
|
+
const newId = (file: string, items: Task[]): string => { for (;;) { const id = `${prefix(file)}-${randomBytes(4).toString("hex").slice(0, 6)}`; if (!items.some((t) => t.id === id)) return id; } };
|
|
46
|
+
/** Resolves an exact task id, or a unique id prefix (with or without the project prefix). Throws if none or several match. */
|
|
47
|
+
export function findId(items: Task[], ref: string, file: string): string {
|
|
48
|
+
if (items.some((t) => t.id === ref)) return ref;
|
|
49
|
+
const hits = items.filter((t) => t.id.startsWith(ref) || t.id.startsWith(`${prefix(file)}-${ref}`));
|
|
50
|
+
if (hits.length === 1) return hits[0].id;
|
|
51
|
+
throw new Error(hits.length ? `Ambiguous task id ${ref}: matches ${hits.map((t) => `${t.id} "${t.name}"`).join(", ")}` : `Task not found: ${ref}`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Runs an action (list, ready, export, import, put, create, start, complete, edit, release) against a dibs JSONL todos file and returns its output. */
|
|
55
|
+
export function runFile(file: string, args: string[]): string | Promise<string> {
|
|
56
|
+
const [action, value] = args;
|
|
57
|
+
if (action !== "list" && action !== "export") mkdirSync(dirname(file), { recursive: true });
|
|
58
|
+
return action === "list" || action === "ready" || action === "export" ? mutate() : withLock(file, mutate);
|
|
59
|
+
function mutate(): string {
|
|
60
|
+
let items: Task[] = [];
|
|
61
|
+
try {
|
|
62
|
+
const data = readFileSync(file, "utf8");
|
|
63
|
+
items = data.split("\n").flatMap((line, index) => {
|
|
64
|
+
if (!line.trim()) return []; // blank lines (hand edits) are harmless
|
|
65
|
+
let record: any;
|
|
66
|
+
try { record = JSON.parse(line); } catch { throw new Error(`Invalid dibs JSONL record on line ${index + 1}`); }
|
|
67
|
+
try { return [toTask(record)]; } catch (error: any) { throw new Error(`Invalid dibs JSONL record on line ${index + 1}: ${error.message}`); }
|
|
68
|
+
});
|
|
69
|
+
} catch (error: any) { if (error.code !== "ENOENT") throw error; }
|
|
70
|
+
if (action === "export") {
|
|
71
|
+
// Tasks todo.txt can't hold unchanged are left out and named, so the rest still export.
|
|
72
|
+
const skipped: string[] = [];
|
|
73
|
+
const text = items.flatMap((task) => { try { return [todoLine(task) + "\n"]; } catch { skipped.push(`#${task.id} ${task.name}`); return []; } }).join("");
|
|
74
|
+
return JSON.stringify({ text, skipped });
|
|
75
|
+
}
|
|
76
|
+
if (action === "list") {
|
|
77
|
+
const q = args.includes("--query") ? args[args.indexOf("--query") + 1]?.toLowerCase() : undefined;
|
|
78
|
+
const h = args.includes("--human") ? args[args.indexOf("--human") + 1] : undefined;
|
|
79
|
+
return JSON.stringify(items.filter((t) => (!q || `${t.name}\n${t.description ?? ""}`.toLowerCase().includes(q)) && (h === undefined || t.human === h)));
|
|
80
|
+
}
|
|
81
|
+
if (action === "ready") return JSON.stringify(items.filter((t) => (!args.includes("--human") || t.human === args[args.indexOf("--human") + 1]) && !t.completed && !live(t) && (t.blocked_by ?? []).every((b) => items.find((i) => i.id === b)?.completed ?? true)));
|
|
82
|
+
const save = () => { const temp = `${file}.${randomUUID()}.tmp`; writeFileSync(temp, items.map((task) => JSON.stringify(clean(task)) + "\n").join(""), { mode: 0o600 }); renameSync(temp, file); };
|
|
83
|
+
const today = () => new Date().toISOString().slice(0, 10);
|
|
84
|
+
if (action === "import") {
|
|
85
|
+
// Each todo.txt line becomes one record; lines whose dibsid already exists are skipped.
|
|
86
|
+
const ids = new Set(items.map((item) => item.id));
|
|
87
|
+
let added = 0, n = 0;
|
|
88
|
+
for (const line of value.split(/\r?\n/)) {
|
|
89
|
+
n++;
|
|
90
|
+
if (!line.trim()) continue;
|
|
91
|
+
let task: Task;
|
|
92
|
+
// Validate every line before saving anything, so a bad file imports nothing.
|
|
93
|
+
try { task = parseTodo(line); } catch (error: any) { throw new Error(`Invalid todo.txt line ${n}: ${error.message}`); }
|
|
94
|
+
if (ids.has(task.id)) continue;
|
|
95
|
+
ids.add(task.id); items.push(task); added++;
|
|
96
|
+
}
|
|
97
|
+
// Only new tasks: an old dangling parent must not block every future import.
|
|
98
|
+
for (const task of items.slice(items.length - added)) checkParent(items, task.id, task.parent);
|
|
99
|
+
if (added) save();
|
|
100
|
+
return `Imported ${added} tasks`;
|
|
101
|
+
}
|
|
102
|
+
if (action === "put") {
|
|
103
|
+
// Sync writes a whole task (JSON in value): replace by id, or append.
|
|
104
|
+
const task: Task = JSON.parse(value);
|
|
105
|
+
const at = items.findIndex((item) => item.id === task.id);
|
|
106
|
+
const old = items[at];
|
|
107
|
+
// Partial merge: a stale snapshot only overwrites the fields it carries ("" clears one); todo.txt-only fields stay.
|
|
108
|
+
const merged: any = { ...old, ...task };
|
|
109
|
+
merged.started_at ??= null;
|
|
110
|
+
merged.completed_date = merged.completed ? merged.completed_date || today() : undefined;
|
|
111
|
+
checkParent(items, merged.id, merged.parent);
|
|
112
|
+
items[at < 0 ? items.length : at] = toTask(clean(merged));
|
|
113
|
+
save();
|
|
114
|
+
return `put: ${task.id}`;
|
|
115
|
+
}
|
|
116
|
+
// Walk option/value pairs by position so values that look like flags stay values.
|
|
117
|
+
const options: Record<string, string> = {};
|
|
118
|
+
for (let i = action === "release" ? 1 : 2; i < args.length; i++) { if (args[i] === "--no-commit" || args[i] === "--force") { options[args[i]] = "1"; continue; } options[args[i]] = args[++i]; }
|
|
119
|
+
const option = (key: string): string | undefined => options[key];
|
|
120
|
+
if (action === "release") {
|
|
121
|
+
// Clears every claim equal to --claim (session end).
|
|
122
|
+
for (const item of items) if (item.claimed_by === option("--claim")) delete item.claimed_by;
|
|
123
|
+
save();
|
|
124
|
+
return "release";
|
|
125
|
+
}
|
|
126
|
+
let task: Task;
|
|
127
|
+
let index = items.length;
|
|
128
|
+
if (action === "create") {
|
|
129
|
+
const parent = option("--parent") && findId(items, option("--parent")!, file);
|
|
130
|
+
checkParent(items, "", parent);
|
|
131
|
+
task = { id: newId(file, items), name: value, completed: false, created: today(), started_at: null, description: option("--description"), parent, created_by: option("--created-by"), human: option("--human"), blocked_by: ids(option("--blocked-by"))?.map((b) => findId(items, b, file)) };
|
|
132
|
+
checkBlockers(items, task.id, task.blocked_by);
|
|
133
|
+
} else {
|
|
134
|
+
const ref = findId(items, value, file);
|
|
135
|
+
index = items.findIndex((item) => item?.id === ref);
|
|
136
|
+
const found = items[index];
|
|
137
|
+
if (!found) throw new Error(`Task not found: ${value}`);
|
|
138
|
+
task = found;
|
|
139
|
+
var before = JSON.stringify([found.name, found.description ?? "", found.blocked_by ?? [], found.human ?? ""]);
|
|
140
|
+
const claim = option("--claim"), owner = found.claimed_by;
|
|
141
|
+
// shortcut: a reused pid keeps a claim looking live until --force or release; upgrade by storing a process start time.
|
|
142
|
+
if ((action === "start" || action === "complete") && claim && owner && owner !== claim && live(found) && !option("--force")) throw new Error(`Task ${value} is claimed by ${owner}; pass force to override`);
|
|
143
|
+
if (action === "start") { task.started_at = new Date().toISOString(); if (claim) task.claimed_by = claim; }
|
|
144
|
+
else if (action === "complete") { task.claimed_by = undefined; task.completed = true; task.completed_date ||= today(); task.result = option("--result"); }
|
|
145
|
+
else if (action === "edit") { if (option("--name") !== undefined) task.name = option("--name")!; if (option("--description") !== undefined) task.description = option("--description"); if (option("--human") !== undefined) task.human = option("--human"); if (option("--blocked-by") !== undefined) { task.blocked_by = ids(option("--blocked-by"))?.map((b) => findId(items, b, file)); checkBlockers(items, task.id, task.blocked_by); } }
|
|
146
|
+
else throw new Error(`Unknown action: ${action}`);
|
|
147
|
+
}
|
|
148
|
+
if (action === "create" || (action === "edit" && option("--name") !== undefined)) checkName(task.name);
|
|
149
|
+
items[index] = clean(task);
|
|
150
|
+
save();
|
|
151
|
+
// Echo the fields a model may have meant to set, so an omission shows up in the reply.
|
|
152
|
+
const what = `task ${task.id} "${task.name}"`, blockers = task.blocked_by?.length ? `; blocked by ${task.blocked_by.join(", ")}` : "";
|
|
153
|
+
const desc = task.description ? `; description: "${task.description}"` : "; no description";
|
|
154
|
+
if (action === "create") return `Created ${what}${desc}${task.parent ? `; parent ${task.parent}` : ""}${blockers}`;
|
|
155
|
+
if (action === "start") return `Started ${what}${option("--claim") ? "; claimed by this session" : ""}${option("--force") ? " (forced)" : ""}`;
|
|
156
|
+
if (action === "complete") return `Completed ${what}; ${task.result ? `result: ${task.result}` : "no result"}`;
|
|
157
|
+
const after = [task.name, task.description ?? "", task.blocked_by ?? [], task.human ?? ""], was = JSON.parse(before!);
|
|
158
|
+
const changed = ["name", "description", "blocked_by", "human"].filter((_, i) => JSON.stringify(after[i]) !== JSON.stringify(was[i]));
|
|
159
|
+
return `${changed.length ? `Updated ${what}; changed ${changed.join(", ")}` : `No change to ${what}; values already set`}${desc}${blockers}`;
|
|
160
|
+
}
|
|
161
|
+
}
|