@nxxxsooo/opencode-annotate 0.6.0 → 0.8.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/agy/hooks.mjs ADDED
@@ -0,0 +1,100 @@
1
+ import { spawn } from "node:child_process"
2
+ import { fileURLToPath } from "node:url"
3
+ import path from "node:path"
4
+ import { dequeueAnnotations, defaultInboxRoot } from "./inbox.mjs"
5
+ import { listTargets, registryRoot } from "../bridge/receiver.mjs"
6
+
7
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
8
+
9
+ export async function readStdin() {
10
+ const chunks = []
11
+ for await (const chunk of process.stdin) {
12
+ chunks.push(chunk)
13
+ }
14
+ const text = Buffer.concat(chunks).toString("utf8").trim()
15
+ if (!text) return {}
16
+ try {
17
+ return JSON.parse(text)
18
+ } catch {
19
+ return {}
20
+ }
21
+ }
22
+
23
+ export async function handleSessionStart(payload, { root = registryRoot(), inboxRoot = defaultInboxRoot() } = {}) {
24
+ const conversationId = payload.conversationId
25
+ if (!conversationId) return {}
26
+
27
+ // Check if a receiver target is already registered for this session
28
+ const targets = await listTargets(root)
29
+ const exists = targets.some(t => t.sessionID === conversationId)
30
+ if (!exists) {
31
+ const dir = payload.workspacePaths?.[0] || process.cwd()
32
+ const daemonScript = path.join(__dirname, "daemon.mjs")
33
+ const args = ["--session", conversationId, "--dir", dir]
34
+ if (process.ppid) args.push("--pid", String(process.ppid))
35
+
36
+ const child = spawn(process.execPath, [daemonScript, ...args], {
37
+ detached: true,
38
+ stdio: "ignore",
39
+ })
40
+ child.unref()
41
+ }
42
+
43
+ return {}
44
+ }
45
+
46
+ export async function handlePreInvocation(payload, { inboxRoot = defaultInboxRoot() } = {}) {
47
+ const conversationId = payload.conversationId
48
+ if (!conversationId) return {}
49
+
50
+ const dequeued = await dequeueAnnotations(conversationId, inboxRoot)
51
+ if (!dequeued || !dequeued.combinedMarkdown.trim()) {
52
+ return {}
53
+ }
54
+
55
+ return {
56
+ injectSteps: [
57
+ {
58
+ userMessage: `# Delivered Annotations\n\n${dequeued.combinedMarkdown}`,
59
+ },
60
+ ],
61
+ }
62
+ }
63
+
64
+ export async function handleStop(payload, { inboxRoot = defaultInboxRoot() } = {}) {
65
+ const conversationId = payload.conversationId
66
+ if (!conversationId) return {}
67
+
68
+ const dequeued = await dequeueAnnotations(conversationId, inboxRoot)
69
+ if (!dequeued || !dequeued.combinedMarkdown.trim()) {
70
+ return {}
71
+ }
72
+
73
+ return {
74
+ decision: "continue",
75
+ reason: `Delivered annotations:\n\n${dequeued.combinedMarkdown}`,
76
+ }
77
+ }
78
+
79
+ export async function runHook(event, payload, options = {}) {
80
+ switch (event) {
81
+ case "SessionStart":
82
+ case "session-start":
83
+ return handleSessionStart(payload, options)
84
+ case "PreInvocation":
85
+ case "pre-invocation":
86
+ return handlePreInvocation(payload, options)
87
+ case "Stop":
88
+ case "stop":
89
+ return handleStop(payload, options)
90
+ default:
91
+ return {}
92
+ }
93
+ }
94
+
95
+ if (process.argv[1] && process.argv[1].endsWith("hooks.mjs")) {
96
+ const event = process.argv[2]
97
+ const payload = await readStdin()
98
+ const result = await runHook(event, payload)
99
+ process.stdout.write(JSON.stringify(result) + "\n")
100
+ }
@@ -0,0 +1,60 @@
1
+ import { test } from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import { mkdtemp, mkdir, rm } from "node:fs/promises"
4
+ import path from "node:path"
5
+ import os from "node:os"
6
+ import { handlePreInvocation, handleStop, handleSessionStart } from "./hooks.mjs"
7
+ import { enqueueAnnotations } from "./inbox.mjs"
8
+
9
+ async function makeFixture(t) {
10
+ const base = path.join(os.homedir(), ".cache")
11
+ await mkdir(base, { recursive: true })
12
+ const root = await mkdtemp(path.join(base, "hooks-test-"))
13
+ t.after(() => rm(root, { recursive: true, force: true }))
14
+ const inboxRoot = path.join(root, "inbox")
15
+ const targetRoot = path.join(root, "targets")
16
+ await mkdir(inboxRoot, { recursive: true })
17
+ await mkdir(targetRoot, { recursive: true })
18
+ return { root, inboxRoot, targetRoot }
19
+ }
20
+
21
+ test("handlePreInvocation injects userMessage when inbox has pending annotations", async t => {
22
+ const { inboxRoot } = await makeFixture(t)
23
+ const conversationId = "conv-test-hook"
24
+
25
+ // Empty inbox returns empty object
26
+ const emptyRes = await handlePreInvocation({ conversationId }, { inboxRoot })
27
+ assert.deepEqual(emptyRes, {})
28
+
29
+ // Enqueue annotations
30
+ await enqueueAnnotations(conversationId, { batchID: "b-1", markdown: "Fix the navbar button" }, inboxRoot)
31
+
32
+ const res = await handlePreInvocation({ conversationId }, { inboxRoot })
33
+ assert.ok(res.injectSteps)
34
+ assert.equal(res.injectSteps.length, 1)
35
+ assert.ok(res.injectSteps[0].userMessage.includes("Fix the navbar button"))
36
+
37
+ // Subsequent call finds inbox empty
38
+ const drained = await handlePreInvocation({ conversationId }, { inboxRoot })
39
+ assert.deepEqual(drained, {})
40
+ })
41
+
42
+ test("handleStop forces continuation when inbox has pending annotations", async t => {
43
+ const { inboxRoot } = await makeFixture(t)
44
+ const conversationId = "conv-test-stop"
45
+
46
+ // Empty inbox returns empty object
47
+ const emptyRes = await handleStop({ conversationId }, { inboxRoot })
48
+ assert.deepEqual(emptyRes, {})
49
+
50
+ // Enqueue annotations
51
+ await enqueueAnnotations(conversationId, { batchID: "b-stop", markdown: "Check accessibility labels" }, inboxRoot)
52
+
53
+ const res = await handleStop({ conversationId }, { inboxRoot })
54
+ assert.equal(res.decision, "continue")
55
+ assert.ok(res.reason.includes("Check accessibility labels"))
56
+
57
+ // Second call is empty
58
+ const drained = await handleStop({ conversationId }, { inboxRoot })
59
+ assert.deepEqual(drained, {})
60
+ })
package/agy/inbox.mjs ADDED
@@ -0,0 +1,72 @@
1
+ import { mkdir, readdir, readFile, rm, writeFile, chmod } from "node:fs/promises"
2
+ import path from "node:path"
3
+ import os from "node:os"
4
+
5
+ export const defaultInboxRoot = () => path.join(os.homedir(), ".local/share/opencode-annotate/inbox")
6
+
7
+ export async function enqueueAnnotations(conversationId, payload, inboxRoot = defaultInboxRoot()) {
8
+ if (!conversationId) throw new Error("Conversation ID is required to enqueue annotations")
9
+ const sessionInbox = path.join(inboxRoot, conversationId)
10
+ await mkdir(sessionInbox, { recursive: true, mode: 0o700 })
11
+ await chmod(sessionInbox, 0o700)
12
+
13
+ const batchID = payload.batchID || `batch-${Date.now()}`
14
+ const file = path.join(sessionInbox, `${batchID}.json`)
15
+ const record = {
16
+ batchID,
17
+ createdAt: new Date().toISOString(),
18
+ promptID: payload.promptID,
19
+ markdown: payload.markdown,
20
+ review: payload.review,
21
+ }
22
+
23
+ await writeFile(file, JSON.stringify(record, null, 2), { mode: 0o600 })
24
+ return { file, batchID }
25
+ }
26
+
27
+ export async function listPendingBatches(conversationId, inboxRoot = defaultInboxRoot()) {
28
+ const sessionInbox = path.join(inboxRoot, conversationId)
29
+ let files
30
+ try {
31
+ files = await readdir(sessionInbox)
32
+ } catch (error) {
33
+ if (error.code === "ENOENT") return []
34
+ throw error
35
+ }
36
+
37
+ const batches = []
38
+ for (const name of files.filter(f => f.endsWith(".json")).sort()) {
39
+ const filePath = path.join(sessionInbox, name)
40
+ try {
41
+ const data = JSON.parse(await readFile(filePath, "utf8"))
42
+ batches.push({ ...data, filePath })
43
+ } catch {
44
+ // Ignore corrupt or in-flight writes
45
+ }
46
+ }
47
+ return batches
48
+ }
49
+
50
+ export async function dequeueAnnotations(conversationId, inboxRoot = defaultInboxRoot()) {
51
+ const batches = await listPendingBatches(conversationId, inboxRoot)
52
+ if (!batches.length) return null
53
+
54
+ const markdowns = []
55
+ const batchIDs = []
56
+
57
+ for (const batch of batches) {
58
+ if (batch.markdown) markdowns.push(batch.markdown)
59
+ batchIDs.push(batch.batchID)
60
+ try {
61
+ await rm(batch.filePath, { force: true })
62
+ } catch {
63
+ // Ignore cleanup error
64
+ }
65
+ }
66
+
67
+ return {
68
+ batchIDs,
69
+ combinedMarkdown: markdowns.join("\n\n---\n\n"),
70
+ count: batches.length,
71
+ }
72
+ }
@@ -0,0 +1,40 @@
1
+ import { test } from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import { mkdtemp, mkdir, rm } from "node:fs/promises"
4
+ import path from "node:path"
5
+ import os from "node:os"
6
+ import { enqueueAnnotations, listPendingBatches, dequeueAnnotations } from "./inbox.mjs"
7
+
8
+ async function makeFixture(t) {
9
+ const base = path.join(os.homedir(), ".cache")
10
+ await mkdir(base, { recursive: true })
11
+ const root = await mkdtemp(path.join(base, "inbox-test-"))
12
+ t.after(() => rm(root, { recursive: true, force: true }))
13
+ return root
14
+ }
15
+
16
+ test("inbox enqueues, lists, and dequeues batches atomically", async t => {
17
+ const root = await makeFixture(t)
18
+ const conversationId = "conv-123"
19
+
20
+ assert.equal(await dequeueAnnotations(conversationId, root), null)
21
+ assert.deepEqual(await listPendingBatches(conversationId, root), [])
22
+
23
+ await enqueueAnnotations(conversationId, { batchID: "b-1", markdown: "# Note 1", promptID: "p-1" }, root)
24
+ await enqueueAnnotations(conversationId, { batchID: "b-2", markdown: "# Note 2", promptID: "p-2" }, root)
25
+
26
+ const pending = await listPendingBatches(conversationId, root)
27
+ assert.equal(pending.length, 2)
28
+ assert.equal(pending[0].batchID, "b-1")
29
+ assert.equal(pending[1].batchID, "b-2")
30
+
31
+ const dequeued = await dequeueAnnotations(conversationId, root)
32
+ assert.ok(dequeued)
33
+ assert.equal(dequeued.count, 2)
34
+ assert.deepEqual(dequeued.batchIDs, ["b-1", "b-2"])
35
+ assert.ok(dequeued.combinedMarkdown.includes("# Note 1"))
36
+ assert.ok(dequeued.combinedMarkdown.includes("# Note 2"))
37
+
38
+ // Subsequent dequeue is empty
39
+ assert.equal(await dequeueAnnotations(conversationId, root), null)
40
+ })
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "agy-annotate",
3
+ "description": "Annotate replies, documents and live HTML pages, then send feedback to the originating AGY session.",
4
+ "author": "Mingjian Shao",
5
+ "repository": "https://github.com/nxxxsooo/opencode-annotate"
6
+ }
@@ -0,0 +1,44 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import path from "node:path"
3
+ import os from "node:os"
4
+ import { createReceiver, registryRoot } from "../bridge/receiver.mjs"
5
+ import { enqueueAnnotations, defaultInboxRoot } from "./inbox.mjs"
6
+
7
+ export async function getAgySessionTitle(conversationId, fallback = "Antigravity Session") {
8
+ if (!conversationId) return fallback
9
+ try {
10
+ const pbtxt = path.join(os.homedir(), ".gemini/antigravity-cli/annotations", `${conversationId}.pbtxt`)
11
+ const raw = await readFile(pbtxt, "utf8")
12
+ const match = raw.match(/title:\s*"([^"]+)"/)
13
+ if (match && match[1]) return match[1]
14
+ } catch {
15
+ // pbtxt might not exist for newly started sessions
16
+ }
17
+ return fallback
18
+ }
19
+
20
+ export async function createAgyReceiver({
21
+ conversationId,
22
+ title,
23
+ directory = process.cwd(),
24
+ root = registryRoot(),
25
+ inboxRoot = defaultInboxRoot(),
26
+ onError = () => {},
27
+ }) {
28
+ if (!conversationId) throw new Error("Conversation ID is required for AGY receiver")
29
+
30
+ const sessionTitle = title || (await getAgySessionTitle(conversationId, path.basename(directory)))
31
+
32
+ return createReceiver({
33
+ sessionID: conversationId,
34
+ title: sessionTitle,
35
+ directory,
36
+ provider: "agy",
37
+ root,
38
+ onError,
39
+ deliver: async ({ review, batchID, markdown, promptID }) => {
40
+ const result = await enqueueAnnotations(conversationId, { review, batchID, markdown, promptID }, inboxRoot)
41
+ return { id: result.batchID }
42
+ },
43
+ })
44
+ }
@@ -0,0 +1,73 @@
1
+ import { test } from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"
4
+ import path from "node:path"
5
+ import os from "node:os"
6
+ import { randomUUID } from "node:crypto"
7
+ import { createAgyReceiver, getAgySessionTitle } from "./receiver.mjs"
8
+ import { listPendingBatches } from "./inbox.mjs"
9
+ import { listTargets } from "../bridge/receiver.mjs"
10
+ import { request } from "../bridge/wire.mjs"
11
+
12
+ const sampleReview = () => ({
13
+ version: 1,
14
+ page: { url: "https://example.test/app", title: "App Preview" },
15
+ annotations: [
16
+ {
17
+ id: "note-1",
18
+ revision: 1,
19
+ kind: "comment",
20
+ comment: "Improve spacing on the header",
21
+ createdAt: new Date().toISOString(),
22
+ anchor: { type: "element", quote: "Header text", selector: "header > h1" },
23
+ },
24
+ ],
25
+ })
26
+
27
+ async function makeFixture(t) {
28
+ const base = path.join(os.homedir(), ".cache")
29
+ await mkdir(base, { recursive: true })
30
+ const root = await mkdtemp(path.join(base, "agy-recv-test-"))
31
+ t.after(() => rm(root, { recursive: true, force: true }))
32
+ const targetDir = path.join(root, "targets")
33
+ const inboxDir = path.join(root, "inbox")
34
+ await mkdir(targetDir, { recursive: true })
35
+ await mkdir(inboxDir, { recursive: true })
36
+ return { root, targetDir, inboxDir }
37
+ }
38
+
39
+ test("createAgyReceiver registers target as provider: agy and enqueues to inbox", async t => {
40
+ const { targetDir, inboxDir } = await makeFixture(t)
41
+ const conversationId = "conv-abc-123"
42
+
43
+ const receiver = await createAgyReceiver({
44
+ conversationId,
45
+ title: "Fixture AGY Conversation",
46
+ directory: "/workspace/my-app",
47
+ root: targetDir,
48
+ inboxRoot: inboxDir,
49
+ })
50
+ t.after(() => receiver.close())
51
+
52
+ const targets = await listTargets(targetDir)
53
+ assert.equal(targets.length, 1)
54
+ assert.equal(targets[0].provider, "agy")
55
+ assert.equal(targets[0].sessionID, conversationId)
56
+ assert.equal(targets[0].title, "Fixture AGY Conversation")
57
+
58
+ const batchID = randomUUID()
59
+ const res = await request(receiver.target.socket, {
60
+ action: "send",
61
+ targetID: receiver.target.id,
62
+ batchID,
63
+ review: sampleReview(),
64
+ })
65
+
66
+ assert.equal(res.ok, true)
67
+ assert.equal(res.state, "admitted")
68
+
69
+ const pending = await listPendingBatches(conversationId, inboxDir)
70
+ assert.equal(pending.length, 1)
71
+ assert.equal(pending[0].batchID, batchID)
72
+ assert.ok(pending[0].markdown.includes("Improve spacing on the header"))
73
+ })
@@ -0,0 +1,93 @@
1
+ import { spawnSync } from "node:child_process"
2
+ import { DatabaseSync } from "node:sqlite"
3
+ import { fileURLToPath } from "node:url"
4
+ import path from "node:path"
5
+ import os from "node:os"
6
+ import { getAgySessionTitle } from "./receiver.mjs"
7
+
8
+ export const agyConfigDir = () => path.join(os.homedir(), ".gemini/antigravity-cli")
9
+
10
+ export function getActiveAgySessions(baseDir = agyConfigDir()) {
11
+ const presenceDir = path.join(baseDir, "presence")
12
+ const dbPath = path.join(baseDir, "conversation_summaries.db")
13
+
14
+ const proc = spawnSync("lsof", ["+D", presenceDir], { encoding: "utf8" })
15
+ const stdout = proc.stdout || ""
16
+ const lockMap = new Map()
17
+
18
+ for (const line of stdout.split("\n")) {
19
+ const parts = line.trim().split(/\s+/)
20
+ if (parts.length >= 9 && parts[0] === "agy") {
21
+ const pid = parseInt(parts[1], 10)
22
+ const nodeName = parts[parts.length - 1]
23
+ if (nodeName.endsWith(".lock")) {
24
+ const conversationId = path.basename(nodeName, ".lock")
25
+ lockMap.set(conversationId, pid)
26
+ }
27
+ }
28
+ }
29
+
30
+ if (lockMap.size === 0) return []
31
+
32
+ let db
33
+ try {
34
+ db = new DatabaseSync(dbPath, { open: true, readOnly: true })
35
+ } catch {
36
+ // Database might be temporarily locked or not exist
37
+ }
38
+
39
+ const query = db?.prepare("SELECT title, workspace_uris FROM conversation_summaries WHERE conversation_id = ?")
40
+ const results = []
41
+
42
+ for (const [conversationId, pid] of lockMap.entries()) {
43
+ let title = ""
44
+ let directory = ""
45
+
46
+ if (query) {
47
+ try {
48
+ const row = query.get(conversationId)
49
+ if (row) {
50
+ title = row.title || ""
51
+ if (row.workspace_uris) {
52
+ try {
53
+ const uris = JSON.parse(row.workspace_uris)
54
+ if (Array.isArray(uris) && uris[0]) {
55
+ directory = fileURLToPath(uris[0])
56
+ }
57
+ } catch {}
58
+ }
59
+ }
60
+ } catch {}
61
+ }
62
+
63
+ results.push({
64
+ conversationId,
65
+ pid,
66
+ title: title || `Session ${conversationId.slice(0, 8)}`,
67
+ directory: directory || process.cwd(),
68
+ })
69
+ }
70
+
71
+ return results
72
+ }
73
+
74
+ export function findSessionForDirectory(dir = process.cwd(), baseDir = agyConfigDir()) {
75
+ const sessions = getActiveAgySessions(baseDir)
76
+ const normalized = path.resolve(dir)
77
+
78
+ // Exact match first
79
+ const exact = sessions.find(s => path.resolve(s.directory) === normalized)
80
+ if (exact) return exact
81
+
82
+ // Parent directory or child directory match
83
+ const matched = sessions.find(s => {
84
+ const sDir = path.resolve(s.directory)
85
+ return normalized.startsWith(sDir) || sDir.startsWith(normalized)
86
+ })
87
+ if (matched) return matched
88
+
89
+ // Fall back to first session if only one exists
90
+ if (sessions.length === 1) return sessions[0]
91
+
92
+ return null
93
+ }
@@ -0,0 +1,30 @@
1
+ ---
2
+ name: annotate
3
+ description: Review assistant replies or local documents in Plannotator TUI, or pair Google Chrome companion for live visual webpage annotation. Use when the user types /annotate, /annotate-web, asks to annotate a reply or document, or requests webpage review.
4
+ ---
5
+
6
+ # Annotate (`agy-annotate`)
7
+
8
+ Use this skill when the user runs `/annotate`, `/annotate-web`, or asks to annotate assistant responses, documents, or webpages.
9
+
10
+ ## Execution Guide for the Agent:
11
+
12
+ ### 1. When the user types `/annotate` (or asks to review the last reply):
13
+ Run the command:
14
+ ```bash
15
+ node /Users/mingjian/Documents/sync/GitHub/opencode-annotate/agy/cli.mjs tui
16
+ ```
17
+ This automatically opens an interactive Plannotator TUI window (via Ghostty or Terminal). When the user finishes adding annotations and presses `q` (or `Ctrl+S`), the window closes, the command outputs the feedback, and you immediately proceed to apply the requested changes.
18
+
19
+ ### 2. When the user specifies a document (e.g., `/annotate path/to/doc.md`):
20
+ Run the command:
21
+ ```bash
22
+ node /Users/mingjian/Documents/sync/GitHub/opencode-annotate/agy/cli.mjs tui "<path/to/doc.md>"
23
+ ```
24
+
25
+ ### 3. When the user types `/annotate-web` (or provides a URL/HTML file):
26
+ Run the command:
27
+ ```bash
28
+ node /Users/mingjian/Documents/sync/GitHub/opencode-annotate/agy/cli.mjs web [url-or-html-path]
29
+ ```
30
+ Inform the user that the session is paired with Chrome and ready in the Annotate side panel (`Alt+Shift+A`). When the user sends notes from Chrome, they are delivered directly to this session.
@@ -0,0 +1,81 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import path from "node:path"
3
+ import os from "node:os"
4
+
5
+ export const defaultBrainDir = (conversationId, baseDir = path.join(os.homedir(), ".gemini/antigravity-cli/brain")) =>
6
+ path.join(baseDir, conversationId)
7
+
8
+ export function parseTranscriptLine(raw) {
9
+ if (!raw || !raw.trim()) return null
10
+ try {
11
+ return JSON.parse(raw)
12
+ } catch {
13
+ return null
14
+ }
15
+ }
16
+
17
+ export function cleanModelContent(content) {
18
+ if (!content) return ""
19
+ // Strip transient system injections or tags that shouldn't be the subject of review
20
+ return content.replace(/<hindsight_[^>]*>[\s\S]*?<\/hindsight_[^>]*>/g, "").trim()
21
+ }
22
+
23
+ export async function readFullStep(brainDir, stepIndex) {
24
+ const fullLog = path.join(brainDir, ".system_generated/logs/transcript_full.jsonl")
25
+ try {
26
+ const text = await readFile(fullLog, "utf8")
27
+ const lines = text.split("\n")
28
+ for (const line of lines) {
29
+ const parsed = parseTranscriptLine(line)
30
+ if (parsed && parsed.step_index === stepIndex) return parsed
31
+ }
32
+ } catch {
33
+ // Fall back if full transcript is absent
34
+ }
35
+ return null
36
+ }
37
+
38
+ export async function extractAgyReplies(brainDir, { signal } = {}) {
39
+ const logPath = path.join(brainDir, ".system_generated/logs/transcript.jsonl")
40
+ let text
41
+ try {
42
+ text = await readFile(logPath, "utf8", { signal })
43
+ } catch (error) {
44
+ if (error.code === "ENOENT") return []
45
+ throw error
46
+ }
47
+
48
+ const lines = text.split("\n")
49
+ const replies = []
50
+
51
+ for (let i = lines.length - 1; i >= 0; i--) {
52
+ signal?.throwIfAborted()
53
+ const step = parseTranscriptLine(lines[i])
54
+ if (!step) continue
55
+ if (step.source !== "MODEL" || step.type !== "PLANNER_RESPONSE" || step.status !== "DONE") continue
56
+
57
+ let content = step.content || ""
58
+ if (step.truncated_fields && step.truncated_fields.includes("content")) {
59
+ const full = await readFullStep(brainDir, step.step_index)
60
+ if (full && full.content) content = full.content
61
+ }
62
+
63
+ const cleaned = cleanModelContent(content)
64
+ const hasToolCalls = Array.isArray(step.tool_calls) && step.tool_calls.length > 0
65
+ if (!cleaned && hasToolCalls) continue
66
+
67
+ replies.push({
68
+ id: String(step.step_index),
69
+ text: cleaned,
70
+ progress: hasToolCalls,
71
+ created: Date.parse(step.created_at) || Date.now(),
72
+ toolCalls: step.tool_calls?.map(t => t.name) || [],
73
+ })
74
+ }
75
+
76
+ return replies
77
+ }
78
+
79
+ export function latestCompletedReply(replies) {
80
+ return replies.find(r => !r.progress && r.text.trim()) || null
81
+ }
@@ -0,0 +1,76 @@
1
+ import { test } from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"
4
+ import path from "node:path"
5
+ import os from "node:os"
6
+ import { extractAgyReplies, latestCompletedReply, cleanModelContent } from "./transcript.mjs"
7
+
8
+ async function makeFixture(t) {
9
+ const base = path.join(os.homedir(), ".cache")
10
+ await mkdir(base, { recursive: true })
11
+ const root = await mkdtemp(path.join(base, "agy-test-"))
12
+ t.after(() => rm(root, { recursive: true, force: true }))
13
+ const logDir = path.join(root, ".system_generated/logs")
14
+ await mkdir(logDir, { recursive: true })
15
+ return { root, logDir }
16
+ }
17
+
18
+ test("extractAgyReplies extracts completed and in-progress replies, handling truncated fields", async t => {
19
+ const { root, logDir } = await makeFixture(t)
20
+ const logPath = path.join(logDir, "transcript.jsonl")
21
+ const fullLogPath = path.join(logDir, "transcript_full.jsonl")
22
+
23
+ const step0 = { step_index: 0, source: "USER_EXPLICIT", type: "USER_INPUT", content: "Build a feature" }
24
+ const step1 = {
25
+ step_index: 1,
26
+ source: "MODEL",
27
+ type: "PLANNER_RESPONSE",
28
+ status: "DONE",
29
+ created_at: "2026-10-28T10:00:00Z",
30
+ content: "Checking the codebase...",
31
+ tool_calls: [{ name: "run_command" }],
32
+ }
33
+ const step2 = {
34
+ step_index: 2,
35
+ source: "MODEL",
36
+ type: "PLANNER_RESPONSE",
37
+ status: "DONE",
38
+ created_at: "2026-10-28T10:01:00Z",
39
+ content: "Truncated preview...",
40
+ truncated_fields: ["content"],
41
+ tool_calls: [],
42
+ }
43
+ const step2Full = {
44
+ step_index: 2,
45
+ source: "MODEL",
46
+ type: "PLANNER_RESPONSE",
47
+ status: "DONE",
48
+ created_at: "2026-10-28T10:01:00Z",
49
+ content: "Full complete response with <hindsight_knowledge_refresh>tags to strip</hindsight_knowledge_refresh> and actual advice.",
50
+ tool_calls: [],
51
+ }
52
+
53
+ await writeFile(logPath, [JSON.stringify(step0), JSON.stringify(step1), JSON.stringify(step2)].join("\n"))
54
+ await writeFile(fullLogPath, JSON.stringify(step2Full))
55
+
56
+ const replies = await extractAgyReplies(root)
57
+ assert.equal(replies.length, 2)
58
+
59
+ // Newest first
60
+ assert.equal(replies[0].id, "2")
61
+ assert.equal(replies[0].progress, false)
62
+ assert.equal(replies[0].text, "Full complete response with and actual advice.")
63
+
64
+ assert.equal(replies[1].id, "1")
65
+ assert.equal(replies[1].progress, true)
66
+ assert.equal(replies[1].text, "Checking the codebase...")
67
+
68
+ const latest = latestCompletedReply(replies)
69
+ assert.ok(latest)
70
+ assert.equal(latest.id, "2")
71
+ })
72
+
73
+ test("extractAgyReplies returns empty array when transcript does not exist", async () => {
74
+ const replies = await extractAgyReplies("/non/existent/path")
75
+ assert.deepEqual(replies, [])
76
+ })