Skip to content

An open-source, faster Devin alternative

TypeScript

Work index: the item parser (work tracking 3.2)

Igor Zalutski via Computer6e96ced291ba
diff --git a/services/managed-agents/src/computer/work/item.ts b/services/managed-agents/src/computer/work/item.ts
new file mode 100644
index 00000000..dde3418f
--- /dev/null
+++ b/services/managed-agents/src/computer/work/item.ts
@@ -0,0 +1,190 @@
+// An item file of the knowledge repository (work tracking, tech design 3.2), read by hand: no YAML
+// or Markdown library. Pure and dependency-free, so the Work index can re-parse stored bodies when
+// the rules change (PARSER_VERSION) without a GitHub call.
+//
+// The parser never rejects a file. What it could not read it reports in `warnings`, which the
+// card shows as a small mark. The number (leading digits of the file name) is the item's identity:
+// it survives a retitle, a new slug and the move to `done/`.
+
+/** Bump when a rule below changes: the index re-parses every stored body. */
+export const PARSER_VERSION = 1;
+
+/** Characters kept of the state line. */
+export const STATE_LINE_MAX = 200;
+
+export type Stage = "open" | "closed";
+
+/** An item's place in the repository: only `NN-slug.md` directly under `work/` or `done/`. */
+export interface ItemPath {
+ number: number;
+ stage: Stage;
+ /** The file name without the number, its dash and `.md`. */
+ slug: string;
+}
+
+/** What the parser reads from one file. */
+export interface ParsedItem {
+ title: string;
+ stateLine: string | null;
+ tags: string[];
+ /** The frontmatter `owner:`, one email, lowercased; null when absent or unreadable. */
+ owner: string | null;
+ /** Unchecked `- [ ]` entries under `## Left`; null when there is no such heading. */
+ left: number | null;
+ /** Checkboxes under `## Left`, checked or not. */
+ boxes: number;
+ /** URLs on lines that start with `PR:`, in order, without duplicates. */
+ pullRequests: string[];
+ warnings: string[];
+}
+
+const ITEM_FILE = /^(work|done)\/(\d{1,9})-([^/]+)\.md$/;
+
+/** The item a path names, or null when the file is not an item. */
+export function itemPath(path: string): ItemPath | null {
+ const m = ITEM_FILE.exec(path);
+ if (!m) return null;
+ return { number: Number(m[2]), stage: m[1] === "work" ? "open" : "closed", slug: m[3]! };
+}
+
+/** The title an item has before its body is read: the slug. */
+export function slugTitle(slug: string): string {
+ return slug;
+}
+
+const EMAIL = /^[^\s@,;<>]+@[^\s@,;<>]+\.[^\s@,;<>]+$/;
+const CHECKBOX = /^\s*[-*+]\s+\[([ xX])\]/;
+const KEY_VALUE = /^[A-Za-z][A-Za-z0-9 _-]{0,40}:(\s|$)/;
+const URL_IN_TEXT = /https?:\/\/[^\s<>()[\]"'`]+/g;
+
+/** One file's fields. `path` gives the stage and the slug (the title when there is no heading). */
+export function parseItem(path: ItemPath, body: string): ParsedItem {
+ const warnings: string[] = [];
+ const lines = body.replace(/^/, "").split(/\r?\n/);
+
+ // Frontmatter: `---` on the first line, closed by the next `---`.
+ let start = 0;
+ let owner: string | null = null;
+ let tags: string[] = [];
+ if (lines[0]?.trim() === "---") {
+ const end = lines.findIndex((line, i) => i > 0 && line.trim() === "---");
+ if (end === -1) {
+ warnings.push("The frontmatter is not closed with ---.");
+ } else {
+ start = end + 1;
+ for (const line of lines.slice(1, end)) {
+ const kv = /^\s*([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(line);
+ if (!kv) continue;
+ const key = kv[1]!.toLowerCase();
+ const value = unquote(kv[2]!.trim());
+ if (key === "owner") {
+ if (!value) continue;
+ if (EMAIL.test(value)) owner = value.toLowerCase();
+ else warnings.push(`owner is not one email: ${value.slice(0, 80)}`);
+ } else if (key === "tags") {
+ tags = [...new Set(value.replace(/^\[|\]$/g, "").split(",").map((t) => unquote(t.trim()).toLowerCase()).filter(Boolean))];
+ }
+ }
+ }
+ }
+
+ let title: string | null = null;
+ let titleAt = -1;
+ let stateLine: string | null = null;
+ let left: number | null = null;
+ let boxes = 0;
+ let leftHeadings = 0;
+ let inLeft = false;
+ let leftContent = false;
+ const pullRequests: string[] = [];
+ let fence: string | null = null;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i]!;
+ const trimmed = line.trim();
+ const fenceMark = /^(`{3,}|~{3,})/.exec(trimmed)?.[1];
+ if (fence) {
+ if (fenceMark && fenceMark[0] === fence[0] && fenceMark.length >= fence.length) fence = null;
+ if (inLeft) leftContent = true;
+ continue;
+ }
+ if (fenceMark) {
+ fence = fenceMark;
+ if (inLeft) leftContent = true;
+ continue;
+ }
+ const heading = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(trimmed);
+ if (heading && /^\s{0,3}#/.test(line)) {
+ const level = heading[1]!.length;
+ const text = heading[2]!;
+ if (inLeft && level <= 2) inLeft = false;
+ if (level === 1 && title === null) {
+ title = text.replace(/^\d+\s*[.:)\-–—]?\s*/, "").trim() || text;
+ titleAt = i;
+ } else if (level === 2 && /^left\s*:?$/i.test(text)) {
+ leftHeadings += 1;
+ if (leftHeadings === 1) {
+ inLeft = true;
+ left = 0;
+ }
+ }
+ continue;
+ }
+ if (inLeft && trimmed) {
+ leftContent = true;
+ const box = CHECKBOX.exec(line);
+ if (box) {
+ boxes += 1;
+ if (box[1] === " ") left = (left ?? 0) + 1;
+ }
+ }
+ if (/^PR:/i.test(trimmed)) {
+ for (const url of trimmed.slice(3).match(URL_IN_TEXT) ?? []) {
+ const clean = url.replace(/[.,;:!?]+$/, "");
+ if (!pullRequests.includes(clean)) pullRequests.push(clean);
+ }
+ }
+ if (titleAt >= 0 && i > titleAt && stateLine === null && trimmed && !KEY_VALUE.test(trimmed)) {
+ stateLine = cut(trimmed);
+ }
+ }
+
+ if (title === null) warnings.push("There is no # title.");
+ if (leftHeadings > 0 && !leftContent) warnings.push("## Left is empty.");
+ if (leftHeadings > 1) warnings.push("There is more than one ## Left; only the first is read.");
+ if (fence) warnings.push("A code block is not closed.");
+
+ return {
+ title: title ?? slugTitle(path.slug),
+ stateLine,
+ tags,
+ owner,
+ left,
+ boxes,
+ pullRequests,
+ warnings,
+ };
+}
+
+/** Ready to close: open, and `## Left` holds at least one checkbox and none unchecked. */
+export function readyToClose(stage: Stage, parsed: Pick<ParsedItem, "left" | "boxes">): boolean {
+ return stage === "open" && parsed.boxes > 0 && parsed.left === 0;
+}
+
+function cut(text: string): string {
+ return text.length > STATE_LINE_MAX ? text.slice(0, STATE_LINE_MAX) : text;
+}
+
+function unquote(value: string): string {
+ return /^(["']).*\1$/.test(value) && value.length >= 2 ? value.slice(1, -1) : value;
+}
+
+/** The `Session:` trailers of a commit message (the knowledge clone's hook writes one; 3.4). */
+export function sessionTrailers(message: string): string[] {
+ const out: string[] = [];
+ for (const line of message.split(/\r?\n/)) {
+ const m = /^Session:\s*([A-Za-z0-9_.:-]{1,128})\s*$/.exec(line.trim());
+ if (m && !out.includes(m[1]!)) out.push(m[1]!);
+ }
+ return out;
+}
diff --git a/services/managed-agents/test/work-item.test.ts b/services/managed-agents/test/work-item.test.ts
new file mode 100644
index 00000000..42415882
--- /dev/null
+++ b/services/managed-agents/test/work-item.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it } from "vitest";
+
+import { itemPath, parseItem, readyToClose, sessionTrailers, STATE_LINE_MAX, type ItemPath } from "../src/computer/work/item.js";
+
+/** Work tracking 3.2: an item file read by hand, never rejected. */
+
+const open: ItemPath = { number: 7, stage: "open", slug: "board-api" };
+const parse = (body: string, path: ItemPath = open) => parseItem(path, body);
+
+describe("itemPath", () => {
+ it("names only NN-slug.md directly under work/ or done/", () => {
+ expect(itemPath("work/7-board-api.md")).toEqual({ number: 7, stage: "open", slug: "board-api" });
+ expect(itemPath("done/012-old.md")).toEqual({ number: 12, stage: "closed", slug: "old" });
+ for (const p of ["work/README.md", "work/x/7-a.md", "work/7-a.txt", "notes/7-a.md", "work/7.md", "work/-a.md", "done/1234567890-a.md"]) {
+ expect(itemPath(p)).toBeNull();
+ }
+ });
+});
+
+describe("parseItem", () => {
+ it("reads a full item", () => {
+ const body = [
+ "---",
+ "owner: [email protected]",
+ "tags: [Board, api, board]",
+ "---",
+ "# 7. The board API",
+ "",
+ "Status: in progress",
+ "Routes are in; composition next.",
+ "",
+ "PR: https://github.com/o/r/pull/3, https://github.com/o/r/pull/4.",
+ "pr: https://github.com/o/r/pull/3",
+ "",
+ "## Left",
+ "- [x] routes",
+ "- [ ] composition",
+ "* [X] scopes",
+ "",
+ "## Notes",
+ "- [ ] not counted",
+ ].join("\n");
+ expect(parse(body)).toEqual({
+ title: "The board API",
+ stateLine: "Routes are in; composition next.",
+ tags: ["board", "api"],
+ owner: "[email protected]",
+ left: 1,
+ boxes: 3,
+ pullRequests: ["https://github.com/o/r/pull/3", "https://github.com/o/r/pull/4"],
+ warnings: [],
+ });
+ });
+
+ it("falls back to the slug and nulls with a warning, never throwing", () => {
+ const p = parse("just text\n");
+ expect(p.title).toBe("board-api");
+ expect(p.stateLine).toBeNull();
+ expect(p.left).toBeNull();
+ expect(p.owner).toBeNull();
+ expect(p.warnings).toEqual(["There is no # title."]);
+ expect(parse("").title).toBe("board-api");
+ });
+
+ it("warns about an unreadable owner and an unclosed frontmatter", () => {
+ expect(parse("---\nowner: Ana, Bob\n---\n# T\n").warnings).toEqual(["owner is not one email: Ana, Bob"]);
+ const unclosed = parse("---\nowner: [email protected]\n# T\n");
+ expect(unclosed.owner).toBeNull();
+ expect(unclosed.warnings).toContain("The frontmatter is not closed with ---.");
+ });
+
+ it("strips quotes from frontmatter values", () => {
+ const p = parse('---\nowner: "[email protected]"\ntags: "x", \'Y\'\n---\n# T\n');
+ expect(p.owner).toBe("[email protected]");
+ expect(p.tags).toEqual(["x", "y"]);
+ });
+
+ it("cuts the state line, skips headings and Key: value lines", () => {
+ const long = "x".repeat(STATE_LINE_MAX + 50);
+ expect(parse(`# T\n## Sub\nOwner: me\n${long}\n`).stateLine).toBe("x".repeat(STATE_LINE_MAX));
+ expect(parse("# T\n\nhttps://example.com is the link\n").stateLine).toBe("https://example.com is the link");
+ });
+
+ it("removes a leading number from the title only", () => {
+ expect(parse("# 12 - Ship it\n").title).toBe("Ship it");
+ expect(parse("# 2026 plans\n").title).toBe("plans");
+ expect(parse("# 42\n").title).toBe("42");
+ expect(parse("# Release v2\n").title).toBe("Release v2");
+ });
+
+ it("ignores headings, boxes and PR lines inside code blocks", () => {
+ const p = parse("# T\n```\n# not a title\n## Left\n- [ ] x\nPR: https://github.com/o/r/pull/1\n```\nstate\n## Left\n- [ ] real\n");
+ expect(p.title).toBe("T");
+ expect(p.stateLine).toBe("state");
+ expect(p.left).toBe(1);
+ expect(p.pullRequests).toEqual([]);
+ });
+
+ it("warns about an unclosed code block", () => {
+ expect(parse("# T\n```\ncode\n").warnings).toEqual(["A code block is not closed."]);
+ });
+
+ it("counts only the first ## Left, warns about more and about an empty one", () => {
+ const two = parse("# T\n## Left\n- [ ] a\n## left:\n- [ ] b\n- [ ] c\n");
+ expect(two.left).toBe(1);
+ expect(two.warnings).toEqual(["There is more than one ## Left; only the first is read."]);
+ const empty = parse("# T\n## Left\n\n## Next\n");
+ expect(empty.left).toBe(0);
+ expect(empty.warnings).toEqual(["## Left is empty."]);
+ });
+
+ it("ends ## Left at a heading of level 2 or above, not at a level 3", () => {
+ const p = parse("# T\n## Left\n### API\n- [ ] a\n### Web\n- [x] b\n# Other\n- [ ] c\n");
+ expect(p.left).toBe(1);
+ expect(p.boxes).toBe(2);
+ });
+
+ it("reads a body with CRLF and a byte order mark", () => {
+ const p = parse("---\r\nowner: [email protected]\r\n---\r\n# T\r\nline\r\n");
+ expect(p.owner).toBe("[email protected]");
+ expect(p.title).toBe("T");
+ expect(p.stateLine).toBe("line");
+ });
+});
+
+describe("readyToClose", () => {
+ it("is open, with boxes under ## Left and none unchecked", () => {
+ expect(readyToClose("open", { left: 0, boxes: 2 })).toBe(true);
+ expect(readyToClose("open", { left: 1, boxes: 2 })).toBe(false);
+ expect(readyToClose("open", { left: 0, boxes: 0 })).toBe(false);
+ expect(readyToClose("open", { left: null, boxes: 0 })).toBe(false);
+ expect(readyToClose("closed", { left: 0, boxes: 2 })).toBe(false);
+ });
+});
+
+describe("sessionTrailers", () => {
+ it("reads Session: lines, once each", () => {
+ expect(sessionTrailers("Update 7\n\nSession: cs_abc123\nSession: cs_abc123\nSession: run:42\n")).toEqual(["cs_abc123", "run:42"]);
+ expect(sessionTrailers("Session: has spaces in it\nSession:\n")).toEqual([]);
+ });
+});
diff --git a/services/managed-agents/vitest.config.ts b/services/managed-agents/vitest.config.ts
index 7c407047..58f6c7ee 100644
--- a/services/managed-agents/vitest.config.ts
+++ b/services/managed-agents/vitest.config.ts
@@ -494,6 +494,7 @@ export default defineConfig({
"test/computer-pool-probe.test.ts",
"test/computer-token-check.test.ts",
"test/computer-secrets.test.ts", "test/computer-secrets-scopes.test.ts",
+ "test/work-item.test.ts",
"test/computer-connections.test.ts",
"test/computer-model-subscriptions.test.ts",
"test/computer-codex-subscriptions.test.ts",