cueloop 0.1.0-alpha.2 → 0.1.0-alpha.21

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cueloop",
3
- "version": "0.1.0-alpha.2",
3
+ "version": "0.1.0-alpha.21",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "bin": {
@@ -10,9 +10,9 @@
10
10
  ".": "./src/main.ts"
11
11
  },
12
12
  "dependencies": {
13
- "@cueloop/schema": "0.1.0-alpha.2",
14
- "@cueloop/daemon": "0.1.0-alpha.2",
15
- "@cueloop/client": "0.1.0-alpha.2"
13
+ "@cueloop/schema": "0.1.0-alpha.21",
14
+ "@cueloop/daemon": "0.1.0-alpha.21",
15
+ "@cueloop/client": "0.1.0-alpha.21"
16
16
  },
17
17
  "publishConfig": {
18
18
  "access": "public"
@@ -28,5 +28,10 @@
28
28
  "type": "git",
29
29
  "url": "git+https://github.com/mmurakaru/cueloop.git",
30
30
  "directory": "packages/cli"
31
- }
32
- }
31
+ },
32
+ "homepage": "https://github.com/mmurakaru/cueloop#readme",
33
+ "bugs": {
34
+ "url": "https://github.com/mmurakaru/cueloop/issues"
35
+ },
36
+ "description": "Terminal review surface for coding agents: annotate plans and diffs, return a verdict, send structured feedback back"
37
+ }
package/src/args.ts CHANGED
@@ -9,16 +9,16 @@ export function parseArgs(argv: string[]): ParsedArgs {
9
9
  const positional: string[] = [];
10
10
  const flags: Record<string, string | boolean> = {};
11
11
  for (let i = 0; i < argv.length; i++) {
12
- const a = argv[i]!;
13
- if (!a.startsWith("--")) {
14
- positional.push(a);
12
+ const argument = argv[i]!;
13
+ if (!argument.startsWith("--")) {
14
+ positional.push(argument);
15
15
  continue;
16
16
  }
17
- const eq = a.indexOf("=");
18
- if (eq !== -1) {
19
- flags[a.slice(2, eq)] = a.slice(eq + 1);
17
+ const equalsIndex = argument.indexOf("=");
18
+ if (equalsIndex !== -1) {
19
+ flags[argument.slice(2, equalsIndex)] = argument.slice(equalsIndex + 1);
20
20
  } else {
21
- const key = a.slice(2);
21
+ const key = argument.slice(2);
22
22
  const next = argv[i + 1];
23
23
  if (next !== undefined && !next.startsWith("--")) {
24
24
  flags[key] = next;
@@ -31,7 +31,7 @@ export function parseArgs(argv: string[]): ParsedArgs {
31
31
  return { positional, flags };
32
32
  }
33
33
 
34
- export function flagStr(flags: Record<string, string | boolean>, key: string): string | undefined {
35
- const v = flags[key];
36
- return typeof v === "string" ? v : undefined;
34
+ export function stringFlag(flags: Record<string, string | boolean>, key: string): string | undefined {
35
+ const value = flags[key];
36
+ return typeof value === "string" ? value : undefined;
37
37
  }
package/src/main.ts CHANGED
@@ -1,16 +1,27 @@
1
1
  #!/usr/bin/env bun
2
2
  /**
3
- * cueloop entry points (#18): `cueloop` opens the TUI on the inbox,
4
- * `cueloop diff` reviews the working tree, `cueloop review <pr>` a PR,
5
- * `cueloop session *` mirrors the daemon API for agents and scripts,
6
- * `cueloop serve` shares a session over ssh (read-only observers),
7
- * `cueloop daemon` runs the daemon in the foreground.
3
+ * cueloop entry points: `cueloop` opens the TUI on the inbox, the verb-first
4
+ * openers `cueloop plan|diff|review` open the latest pending review of that
5
+ * type (or address one by id/title), `cueloop diff`/`cueloop review <pr>` also
6
+ * keep their create paths, `cueloop session *` mirrors the daemon API for
7
+ * agents and scripts, `cueloop serve` shares a session over ssh (read-only
8
+ * observers), `cueloop daemon` runs the daemon in the foreground.
8
9
  */
9
10
 
10
- import { parseArgs, flagStr } from "./args";
11
- import { sessionCommand } from "./session-cmds";
12
- import { resolveWorkspace, workingTreeDiff } from "./workspace";
11
+ import { parseArgs, stringFlag, type ParsedArgs } from "./args";
12
+ import {
13
+ isDiffReview,
14
+ isPlanReview,
15
+ isPrReview,
16
+ isSessionId,
17
+ openTargetMessage,
18
+ resolveOpenTarget,
19
+ } from "./open-target";
20
+ import { sessionCommand } from "./session-commands";
21
+ import { workingTreeDiff } from "./working-tree";
13
22
  import { DaemonClient } from "@cueloop/daemon/client";
23
+ import type { ReviewSession } from "@cueloop/schema";
24
+ import { openReview, resolveWorkspace } from "@cueloop/daemon/review";
14
25
 
15
26
  const argv = process.argv.slice(2);
16
27
  const cmd = argv[0];
@@ -31,29 +42,17 @@ async function main(): Promise<number> {
31
42
  await new Promise(() => {}); // run until signalled
32
43
  return 0;
33
44
  }
34
- case "diff": {
35
- const workspace = await resolveWorkspace();
36
- const diff = await workingTreeDiff();
37
- if (!diff.trim()) {
38
- console.error("working tree is clean - nothing to review");
39
- return 1;
40
- }
41
- const client = await DaemonClient.connect({ autostart: true });
42
- const session = await client.sessionCreate(workspace, {
43
- type: "diff",
44
- content: diff,
45
- meta: { title: `working tree @ ${workspace.branch}`, cwd: process.cwd() },
46
- });
47
- client.close();
48
- return runTui(session.id);
49
- }
45
+ case "plan":
46
+ return planCommand(argv.slice(1));
47
+ case "diff":
48
+ return diffCommand(argv.slice(1));
50
49
  case "serve": {
51
50
  const { positional, flags } = parseArgs(argv.slice(1));
52
- const port = flagStr(flags, "port");
51
+ const port = stringFlag(flags, "port");
53
52
  const { serveClient } = await import("@cueloop/client");
54
53
  const handle = await serveClient({
55
54
  port: port !== undefined ? Number(port) : undefined,
56
- host: flagStr(flags, "host"),
55
+ host: stringFlag(flags, "host"),
57
56
  sessionId: positional[0],
58
57
  });
59
58
  console.log(
@@ -73,10 +72,8 @@ async function main(): Promise<number> {
73
72
  await new Promise(() => {}); // serve until signalled
74
73
  return 0;
75
74
  }
76
- case "review": {
77
- const { reviewCommand } = await import("./pr");
78
- return reviewCommand(argv.slice(1));
79
- }
75
+ case "review":
76
+ return reviewEntry(argv.slice(1));
80
77
  case "review-post": {
81
78
  const { reviewPostCommand } = await import("./pr");
82
79
  return reviewPostCommand(argv.slice(1));
@@ -96,6 +93,103 @@ async function main(): Promise<number> {
96
93
  }
97
94
  }
98
95
 
96
+ /**
97
+ * The id-or-title selector for a verb-first opener: the bare positional, or a
98
+ * value handed to `--open`/`--latest`. A bare `--latest`/`--open` flag carries
99
+ * no value, so the selector stays undefined and the opener defaults to the
100
+ * latest pending review.
101
+ */
102
+ function openSelector(parsed: ParsedArgs): string | undefined {
103
+ return parsed.positional[0] ?? stringFlag(parsed.flags, "open") ?? stringFlag(parsed.flags, "latest");
104
+ }
105
+
106
+ /**
107
+ * Resolve one review of the verb's scope and open it in the TUI, or print the
108
+ * miss and fail. `emptyMessage` overrides the default no-pending line for the
109
+ * one caller that needs a scope-specific hint (a clean working tree).
110
+ */
111
+ async function openReviewOfKind(
112
+ match: (session: ReviewSession) => boolean,
113
+ label: string,
114
+ selector: string | undefined,
115
+ emptyMessage?: string,
116
+ ): Promise<number> {
117
+ const client = await DaemonClient.connect({ autostart: true });
118
+ let sessions: ReviewSession[];
119
+ try {
120
+ sessions = await client.sessionList();
121
+ } finally {
122
+ client.close();
123
+ }
124
+ const target = resolveOpenTarget(sessions, { match, selector });
125
+ if (target.kind === "session") return runTui(target.sessionId);
126
+ if (target.kind === "no-pending" && emptyMessage !== undefined) {
127
+ console.error(emptyMessage);
128
+ return 1;
129
+ }
130
+ console.error(openTargetMessage(label, target));
131
+ return 1;
132
+ }
133
+
134
+ /** `cueloop plan [id|title]` - open the latest pending plan, or address one. */
135
+ async function planCommand(argv: string[]): Promise<number> {
136
+ return openReviewOfKind(isPlanReview, "plan", openSelector(parseArgs(argv)));
137
+ }
138
+
139
+ /**
140
+ * `cueloop diff` disambiguates create from open by intent:
141
+ * - a selector (`cueloop diff <id|title>`) or an explicit `--open`/`--latest`
142
+ * opens a pending diff review;
143
+ * - otherwise a dirty working tree still creates a review as before;
144
+ * - a clean working tree carries no create input, so it opens the latest
145
+ * pending diff review instead of erroring.
146
+ */
147
+ async function diffCommand(argv: string[]): Promise<number> {
148
+ const parsed = parseArgs(argv);
149
+ const selector = openSelector(parsed);
150
+ const wantsOpen = selector !== undefined || "open" in parsed.flags || "latest" in parsed.flags;
151
+ if (wantsOpen) return openReviewOfKind(isDiffReview, "diff", selector);
152
+
153
+ const workspace = await resolveWorkspace();
154
+ const diff = await workingTreeDiff();
155
+ if (!diff.trim()) {
156
+ return openReviewOfKind(
157
+ isDiffReview,
158
+ "diff",
159
+ undefined,
160
+ "working tree is clean and no pending diff review - nothing to open",
161
+ );
162
+ }
163
+ const client = await DaemonClient.connect({ autostart: true });
164
+ const review = await openReview(client, {
165
+ type: "diff",
166
+ content: diff,
167
+ workspace,
168
+ title: `working tree @ ${workspace.branch}`,
169
+ });
170
+ client.close();
171
+ return runTui(review.id);
172
+ }
173
+
174
+ /**
175
+ * `cueloop review` disambiguates create from open by intent:
176
+ * - bare `cueloop review`, `--open`/`--latest`, or a `ses_*` selector opens a
177
+ * pending PR review (a diff carrying a `pr` reference);
178
+ * - any other positional is a PR reference and takes the create path in pr.ts.
179
+ */
180
+ async function reviewEntry(argv: string[]): Promise<number> {
181
+ const parsed = parseArgs(argv);
182
+ const explicitOpen = "open" in parsed.flags || "latest" in parsed.flags;
183
+ const selector = openSelector(parsed);
184
+ const looksLikeSessionId = selector !== undefined && isSessionId(selector);
185
+ const wantsCreate = !explicitOpen && !looksLikeSessionId && selector !== undefined;
186
+ if (wantsCreate) {
187
+ const { reviewCommand } = await import("./pr");
188
+ return reviewCommand(argv);
189
+ }
190
+ return openReviewOfKind(isPrReview, "PR", explicitOpen || looksLikeSessionId ? selector : undefined);
191
+ }
192
+
99
193
  async function runTui(sessionId?: string): Promise<number> {
100
194
  const { runClient } = await import("@cueloop/client");
101
195
  return runClient({ sessionId });
@@ -109,8 +203,12 @@ function printHelp(): void {
109
203
  "usage:",
110
204
  " cueloop open the inbox",
111
205
  " cueloop <session-id> open one session",
112
- " cueloop diff review the working tree",
206
+ " cueloop plan [id|title] open the latest pending plan review (or one by id/title)",
207
+ " cueloop diff [id|title] open the latest pending diff review (or one by id/title);",
208
+ " with a dirty working tree and no argument, create one instead",
209
+ " cueloop review [id|title] open the latest pending PR review (or one by id/title)",
113
210
  " cueloop review <pr> review a pull request (--no-tui prints the session)",
211
+ " cueloop <plan|diff|review> --latest open the latest pending review of that type",
114
212
  " cueloop review-post <id> <pr> post a resolved session's verdict back to the PR",
115
213
  " cueloop serve [session-id] share over ssh: observers are read-only,",
116
214
  " you stay the controller (--port 2222, --host 127.0.0.1;",
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Verb-first open resolution over a plain session list: latest-pending default,
3
+ * by-id, and fuzzy-by-title (exact wins, unique substring wins, else
4
+ * ambiguous). No daemon and no TUI - the resolver is pure over the array.
5
+ */
6
+
7
+ import { describe, expect, test } from "bun:test";
8
+ import type { ArtifactType, ReviewSession } from "@cueloop/schema";
9
+ import {
10
+ isDiffReview,
11
+ isPlanReview,
12
+ isPrReview,
13
+ isSessionId,
14
+ openTargetMessage,
15
+ resolveOpenTarget,
16
+ } from "./open-target";
17
+
18
+ function session(overrides: {
19
+ id: string;
20
+ type?: ArtifactType;
21
+ title?: string;
22
+ status?: "pending" | "resolved";
23
+ createdAt?: string;
24
+ pr?: string;
25
+ }): ReviewSession {
26
+ return {
27
+ schemaVersion: "1",
28
+ id: overrides.id,
29
+ workspace: { repoRoot: "/repo", branch: "main" },
30
+ artifact: {
31
+ type: overrides.type ?? "plan",
32
+ content: "",
33
+ meta: { title: overrides.title, pr: overrides.pr },
34
+ },
35
+ revisions: [],
36
+ annotations: [],
37
+ verdict: overrides.status === "resolved" ? { kind: "approve", summary: "", feedback: "", resolvedAt: "" } : null,
38
+ status: overrides.status ?? "pending",
39
+ createdAt: overrides.createdAt ?? "2026-01-01T00:00:00.000Z",
40
+ };
41
+ }
42
+
43
+ const isPlan = isPlanReview;
44
+
45
+ describe("verb scope predicates are disjoint", () => {
46
+ test("isPlanReview matches only plan artifacts", () => {
47
+ expect(isPlanReview(session({ id: "ses_p", type: "plan" }))).toBe(true);
48
+ expect(isPlanReview(session({ id: "ses_d", type: "diff" }))).toBe(false);
49
+ });
50
+
51
+ test("isDiffReview matches a plain diff but NOT a diff carrying meta.pr", () => {
52
+ expect(isDiffReview(session({ id: "ses_d", type: "diff" }))).toBe(true);
53
+ expect(isDiffReview(session({ id: "ses_pr", type: "diff", pr: "42" }))).toBe(false);
54
+ expect(isDiffReview(session({ id: "ses_p", type: "plan" }))).toBe(false);
55
+ });
56
+
57
+ test("isPrReview matches a diff carrying meta.pr, and only that", () => {
58
+ expect(isPrReview(session({ id: "ses_pr", type: "diff", pr: "42" }))).toBe(true);
59
+ expect(isPrReview(session({ id: "ses_d", type: "diff" }))).toBe(false);
60
+ expect(isPrReview(session({ id: "ses_p", type: "plan" }))).toBe(false);
61
+ });
62
+
63
+ test("a PR review resolves under exactly one scope - never both diff and review", () => {
64
+ const prReview = session({ id: "ses_pr", type: "diff", pr: "42" });
65
+ expect(isDiffReview(prReview)).toBe(false);
66
+ expect(isPrReview(prReview)).toBe(true);
67
+ });
68
+ });
69
+
70
+ describe("isSessionId", () => {
71
+ test("only the ses_ prefix reads as an id", () => {
72
+ expect(isSessionId("ses_abc")).toBe(true);
73
+ expect(isSessionId("some title")).toBe(false);
74
+ expect(isSessionId("42")).toBe(false);
75
+ });
76
+ });
77
+
78
+ describe("resolveOpenTarget: latest pending default", () => {
79
+ test("picks the most recent pending session in scope", () => {
80
+ const sessions = [
81
+ session({ id: "ses_old", createdAt: "2026-01-01T00:00:00.000Z" }),
82
+ session({ id: "ses_new", createdAt: "2026-03-01T00:00:00.000Z" }),
83
+ session({ id: "ses_mid", createdAt: "2026-02-01T00:00:00.000Z" }),
84
+ ];
85
+ expect(resolveOpenTarget(sessions, { match: isPlan })).toEqual({ kind: "session", sessionId: "ses_new" });
86
+ });
87
+
88
+ test("ignores resolved sessions and other artifact types", () => {
89
+ const sessions = [
90
+ session({ id: "ses_resolved", createdAt: "2026-05-01T00:00:00.000Z", status: "resolved" }),
91
+ session({ id: "ses_diff", type: "diff", createdAt: "2026-04-01T00:00:00.000Z" }),
92
+ session({ id: "ses_plan", createdAt: "2026-02-01T00:00:00.000Z" }),
93
+ ];
94
+ expect(resolveOpenTarget(sessions, { match: isPlan })).toEqual({ kind: "session", sessionId: "ses_plan" });
95
+ });
96
+
97
+ test("no pending session in scope reports no-pending", () => {
98
+ const sessions = [session({ id: "ses_done", status: "resolved" })];
99
+ expect(resolveOpenTarget(sessions, { match: isPlan })).toEqual({ kind: "no-pending" });
100
+ });
101
+ });
102
+
103
+ describe("resolveOpenTarget: by id", () => {
104
+ test("an exact session id in scope opens that session, pending or not", () => {
105
+ const sessions = [
106
+ session({ id: "ses_a" }),
107
+ session({ id: "ses_b", status: "resolved" }),
108
+ ];
109
+ expect(resolveOpenTarget(sessions, { match: isPlan, selector: "ses_b" })).toEqual({
110
+ kind: "session",
111
+ sessionId: "ses_b",
112
+ });
113
+ });
114
+
115
+ test("an id outside the scope does not match", () => {
116
+ const sessions = [session({ id: "ses_diff", type: "diff" })];
117
+ expect(resolveOpenTarget(sessions, { match: isPlan, selector: "ses_diff" })).toEqual({
118
+ kind: "no-match",
119
+ selector: "ses_diff",
120
+ });
121
+ });
122
+ });
123
+
124
+ describe("resolveOpenTarget: fuzzy by title", () => {
125
+ test("case-insensitive exact title wins over substring rivals", () => {
126
+ const sessions = [
127
+ session({ id: "ses_exact", title: "Rollout" }),
128
+ session({ id: "ses_sub", title: "Rollout plan v2" }),
129
+ ];
130
+ expect(resolveOpenTarget(sessions, { match: isPlan, selector: "rollout" })).toEqual({
131
+ kind: "session",
132
+ sessionId: "ses_exact",
133
+ });
134
+ });
135
+
136
+ test("a unique case-insensitive substring match wins", () => {
137
+ const sessions = [
138
+ session({ id: "ses_auth", title: "Auth rewrite" }),
139
+ session({ id: "ses_cache", title: "Cache warmup" }),
140
+ ];
141
+ expect(resolveOpenTarget(sessions, { match: isPlan, selector: "AUTH" })).toEqual({
142
+ kind: "session",
143
+ sessionId: "ses_auth",
144
+ });
145
+ });
146
+
147
+ test("several substring matches are ambiguous and list the candidate titles", () => {
148
+ const sessions = [
149
+ session({ id: "ses_1", title: "Payments rollout" }),
150
+ session({ id: "ses_2", title: "Rollout of search" }),
151
+ ];
152
+ expect(resolveOpenTarget(sessions, { match: isPlan, selector: "rollout" })).toEqual({
153
+ kind: "ambiguous",
154
+ selector: "rollout",
155
+ titles: ["Payments rollout", "Rollout of search"],
156
+ });
157
+ });
158
+
159
+ test("no title match reports no-match", () => {
160
+ const sessions = [session({ id: "ses_1", title: "Auth rewrite" })];
161
+ expect(resolveOpenTarget(sessions, { match: isPlan, selector: "billing" })).toEqual({
162
+ kind: "no-match",
163
+ selector: "billing",
164
+ });
165
+ });
166
+ });
167
+
168
+ describe("openTargetMessage", () => {
169
+ test("no-pending mirrors the clean-tree tone", () => {
170
+ expect(openTargetMessage("plan", { kind: "no-pending" })).toBe("no pending plan review - nothing to open");
171
+ });
172
+
173
+ test("no-match names the selector", () => {
174
+ expect(openTargetMessage("diff", { kind: "no-match", selector: "billing" })).toBe(
175
+ 'no diff review matches "billing" - nothing to open',
176
+ );
177
+ });
178
+
179
+ test("ambiguous lists the candidate titles", () => {
180
+ const message = openTargetMessage("plan", { kind: "ambiguous", selector: "rollout", titles: ["A", "B"] });
181
+ expect(message).toContain('"rollout" matches several plan reviews');
182
+ expect(message).toContain(" - A");
183
+ expect(message).toContain(" - B");
184
+ });
185
+ });
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Verb-first review-open resolution: turn a verb (plan/diff/review) plus an
3
+ * optional id-or-title selector into a single session to open, or a clear
4
+ * miss. Pure over a session list so it unit-tests without a daemon or a TUI -
5
+ * main.ts fetches the sessions and prints the miss messages.
6
+ *
7
+ * Rules, in order:
8
+ * - no selector opens the latest pending session in scope (most recent
9
+ * createdAt, verdict still open) - the `--latest` default;
10
+ * - a selector that exactly equals a session id opens that session, pending
11
+ * or resolved;
12
+ * - otherwise the selector matches session titles, case-insensitive: an
13
+ * exact title wins, else a unique substring match wins, else the substring
14
+ * candidates are reported as ambiguous.
15
+ * Every lookup is scoped by the caller's `match` predicate, so a verb only
16
+ * ever resolves to its own artifact kind.
17
+ */
18
+
19
+ import type { ReviewSession } from "@cueloop/schema";
20
+
21
+ /**
22
+ * The verb scopes, kept disjoint on purpose so a single session never resolves
23
+ * under two verbs. A PR review is a diff artifact that carries a `pr`
24
+ * reference (openReview maps a top-level `pr` into `meta.pr`), so the plain
25
+ * diff scope must exclude those - otherwise `cueloop diff` and `cueloop
26
+ * review` would both open the same pending PR review.
27
+ */
28
+ export function isPlanReview(session: ReviewSession): boolean {
29
+ return session.artifact.type === "plan";
30
+ }
31
+ export function isDiffReview(session: ReviewSession): boolean {
32
+ return session.artifact.type === "diff" && session.artifact.meta.pr === undefined;
33
+ }
34
+ export function isPrReview(session: ReviewSession): boolean {
35
+ return session.artifact.type === "diff" && session.artifact.meta.pr !== undefined;
36
+ }
37
+
38
+ /** Session ids are minted with this prefix; the id-vs-title split lives here. */
39
+ export function isSessionId(value: string): boolean {
40
+ return value.startsWith("ses_");
41
+ }
42
+
43
+ export interface OpenTargetQuery {
44
+ /** Only sessions this predicate accepts are eligible - the verb's artifact scope. */
45
+ match: (session: ReviewSession) => boolean;
46
+ /** Positional id-or-title selector; absent means "latest pending". */
47
+ selector?: string;
48
+ }
49
+
50
+ export type OpenTarget =
51
+ | { kind: "session"; sessionId: string }
52
+ | { kind: "no-pending" }
53
+ | { kind: "no-match"; selector: string }
54
+ | { kind: "ambiguous"; selector: string; titles: string[] };
55
+
56
+ /** Most-recent-first, so the head of a sorted list is always the latest. */
57
+ function newestFirst(left: ReviewSession, right: ReviewSession): number {
58
+ return right.createdAt.localeCompare(left.createdAt);
59
+ }
60
+
61
+ export function resolveOpenTarget(sessions: ReviewSession[], query: OpenTargetQuery): OpenTarget {
62
+ const scoped = sessions.filter(query.match);
63
+
64
+ if (query.selector === undefined) {
65
+ const latestPending = scoped.filter((candidate) => candidate.status === "pending").sort(newestFirst)[0];
66
+ return latestPending ? { kind: "session", sessionId: latestPending.id } : { kind: "no-pending" };
67
+ }
68
+
69
+ const selector = query.selector;
70
+ const byId = scoped.find((candidate) => candidate.id === selector);
71
+ if (byId) return { kind: "session", sessionId: byId.id };
72
+
73
+ const loweredSelector = selector.toLowerCase();
74
+ const titled = scoped.filter((candidate) => (candidate.artifact.meta.title ?? "").length > 0);
75
+
76
+ const exactTitle = titled
77
+ .filter((candidate) => candidate.artifact.meta.title!.toLowerCase() === loweredSelector)
78
+ .sort(newestFirst)[0];
79
+ if (exactTitle) return { kind: "session", sessionId: exactTitle.id };
80
+
81
+ const substringMatches = titled
82
+ .filter((candidate) => candidate.artifact.meta.title!.toLowerCase().includes(loweredSelector))
83
+ .sort(newestFirst);
84
+ if (substringMatches.length === 1) return { kind: "session", sessionId: substringMatches[0]!.id };
85
+ if (substringMatches.length === 0) return { kind: "no-match", selector };
86
+ return { kind: "ambiguous", selector, titles: substringMatches.map((candidate) => candidate.artifact.meta.title!) };
87
+ }
88
+
89
+ /**
90
+ * The reviewer-facing line for a miss, in the "working tree is clean - nothing
91
+ * to review" tone. `label` is the human word for the verb's scope ("plan",
92
+ * "diff", "PR"). The "session" outcome has no message - the caller opens it.
93
+ */
94
+ export function openTargetMessage(label: string, target: Exclude<OpenTarget, { kind: "session" }>): string {
95
+ switch (target.kind) {
96
+ case "no-pending":
97
+ return `no pending ${label} review - nothing to open`;
98
+ case "no-match":
99
+ return `no ${label} review matches "${target.selector}" - nothing to open`;
100
+ case "ambiguous":
101
+ return [
102
+ `"${target.selector}" matches several ${label} reviews - name one:`,
103
+ ...target.titles.map((title) => ` - ${title}`),
104
+ ].join("\n");
105
+ }
106
+ }
package/src/pr.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * PR review entry (#18): `cueloop review <pr>` fetches the PR diff through the
2
+ * PR review entry: `cueloop review <pr>` fetches the PR diff through the
3
3
  * user's `gh` CLI (auth fully delegated), opens a diff session, and posts the
4
4
  * verdict back to the PR as a real review when the session resolves.
5
5
  * `cueloop review-post <session-id> <pr>` is the non-interactive post-back
@@ -8,8 +8,8 @@
8
8
 
9
9
  import type { ReviewSession, VerdictKind } from "@cueloop/schema";
10
10
  import { DaemonClient } from "@cueloop/daemon/client";
11
+ import { openReview } from "@cueloop/daemon/review";
11
12
  import { parseArgs } from "./args";
12
- import { resolveWorkspace } from "./workspace";
13
13
 
14
14
  /** The gh binary is injectable so tests can stub it. */
15
15
  function ghBin(): string {
@@ -55,13 +55,14 @@ export async function reviewCommand(argv: string[]): Promise<number> {
55
55
  console.error(`PR ${pr} has an empty diff - nothing to review`);
56
56
  return 1;
57
57
  }
58
- const workspace = await resolveWorkspace();
59
58
  const client = await DaemonClient.connect({ autostart: true });
60
- const session = await client.sessionCreate(workspace, {
59
+ const review = await openReview(client, {
61
60
  type: "diff",
62
61
  content: diff.stdout,
63
- meta: { title: `PR ${pr}`, pr, cwd: process.cwd() },
62
+ title: `PR ${pr}`,
63
+ pr,
64
64
  });
65
+ const session = review.session;
65
66
  client.close();
66
67
 
67
68
  if (flags["no-tui"]) {
@@ -0,0 +1,116 @@
1
+ /**
2
+ * `cueloop session *` - mirrors the daemon socket API 1:1. One surface,
3
+ * three consumers: agent adapters, the dev loop, and integrations. Output is
4
+ * JSON on stdout; exit code 0 unless the daemon returned an error.
5
+ */
6
+
7
+ import { newAnnotationId, type ArtifactType, type VerdictKind } from "@cueloop/schema";
8
+ import { DaemonClient } from "@cueloop/daemon/client";
9
+ import { openHerdrPaneForReview } from "@cueloop/daemon/herdr-pane";
10
+ import { openReview, verdictResponse, type ReviewNote } from "@cueloop/daemon/review";
11
+ import { parseArgs, stringFlag } from "./args";
12
+
13
+ async function readStdin(): Promise<string> {
14
+ return await new Response(Bun.stdin.stream()).text();
15
+ }
16
+
17
+ function out(value: unknown): void {
18
+ console.log(JSON.stringify(value, null, 2));
19
+ }
20
+
21
+ export async function sessionCommand(argv: string[]): Promise<number> {
22
+ const { positional, flags } = parseArgs(argv);
23
+ const verb = positional[0];
24
+ const client = await DaemonClient.connect({ autostart: true });
25
+ try {
26
+ switch (verb) {
27
+ case "create": {
28
+ const contentFile = stringFlag(flags, "content-file");
29
+ const content = contentFile ? await Bun.file(contentFile).text() : await readStdin();
30
+ // per-file agent notes for diff sessions: a JSON array of { path, body }
31
+ const notesFile = stringFlag(flags, "notes-file");
32
+ const notes = notesFile ? (JSON.parse(await Bun.file(notesFile).text()) as ReviewNote[]) : undefined;
33
+ const review = await openReview(client, {
34
+ type: (stringFlag(flags, "type") ?? "plan") as ArtifactType,
35
+ content,
36
+ cwd: stringFlag(flags, "cwd"),
37
+ agent: stringFlag(flags, "agent"),
38
+ agentSessionId: stringFlag(flags, "agent-session-id"),
39
+ planPath: stringFlag(flags, "plan-path"),
40
+ title: stringFlag(flags, "title"),
41
+ notes,
42
+ });
43
+ // herdr auto-open: a review created from inside herdr spawns a new tab
44
+ // that renders it. Guarded to genuinely new sessions and no-op outside
45
+ // herdr; a broken binary never blocks the create.
46
+ openHerdrPaneForReview(review.session);
47
+ out(review.session);
48
+ return 0;
49
+ }
50
+ case "get": {
51
+ out(await client.sessionGet(required(positional[1], "session id")));
52
+ return 0;
53
+ }
54
+ case "list": {
55
+ const status = stringFlag(flags, "status") as "pending" | "resolved" | undefined;
56
+ out(await client.sessionList(status ? { status } : undefined));
57
+ return 0;
58
+ }
59
+ case "wait": {
60
+ const id = required(positional[1], "session id");
61
+ const timeoutMs = Number(stringFlag(flags, "timeout-ms") ?? "60000");
62
+ const session = await client.sessionWait(id, timeoutMs);
63
+ if (session === null) {
64
+ out({ status: "pending" });
65
+ return 0;
66
+ }
67
+ const { allow, feedback } = verdictResponse(session);
68
+ out({ status: "resolved", allow, verdict: session.verdict!.kind, feedback });
69
+ return 0;
70
+ }
71
+ case "annotate": {
72
+ const id = required(positional[1], "session id");
73
+ const body = stringFlag(flags, "body") ?? "";
74
+ const quote = required(stringFlag(flags, "quote"), "--quote");
75
+ out(
76
+ await client.sessionAnnotate(id, {
77
+ id: stringFlag(flags, "annotation-id") ?? newAnnotationId(),
78
+ kind: stringFlag(flags, "kind") ?? "comment",
79
+ anchor: {
80
+ quote,
81
+ prefix: stringFlag(flags, "prefix") ?? "",
82
+ suffix: stringFlag(flags, "suffix") ?? "",
83
+ },
84
+ body,
85
+ }),
86
+ );
87
+ return 0;
88
+ }
89
+ case "resolve": {
90
+ const id = required(positional[1], "session id");
91
+ const kind = required(stringFlag(flags, "verdict"), "--verdict") as VerdictKind;
92
+ out(await client.sessionResolve(id, kind, stringFlag(flags, "summary") ?? ""));
93
+ return 0;
94
+ }
95
+ case "submit-revision": {
96
+ const id = required(positional[1], "session id");
97
+ const contentFile = stringFlag(flags, "content-file");
98
+ const content = contentFile ? await Bun.file(contentFile).text() : await readStdin();
99
+ out(await client.sessionSubmitRevision(id, content));
100
+ return 0;
101
+ }
102
+ default:
103
+ console.error(
104
+ "usage: cueloop session <create|get|list|wait|annotate|resolve|submit-revision> [flags]",
105
+ );
106
+ return 2;
107
+ }
108
+ } finally {
109
+ client.close();
110
+ }
111
+ }
112
+
113
+ function required<T>(value: T | undefined, description: string): T {
114
+ if (value === undefined) throw new Error(`missing ${description}`);
115
+ return value;
116
+ }
@@ -1,6 +1,4 @@
1
- /** Workspace key resolution (#9): repo root + branch from the cwd. */
2
-
3
- import type { WorkspaceKey } from "@cueloop/schema";
1
+ /** Working-tree diff capture for `cueloop diff`, untracked files included. */
4
2
 
5
3
  async function git(args: string[], cwd: string): Promise<string | null> {
6
4
  const proc = Bun.spawn(["git", ...args], { cwd, stdout: "pipe", stderr: "ignore" });
@@ -9,15 +7,9 @@ async function git(args: string[], cwd: string): Promise<string | null> {
9
7
  return out.trim();
10
8
  }
11
9
 
12
- export async function resolveWorkspace(cwd = process.cwd()): Promise<WorkspaceKey> {
13
- const repoRoot = (await git(["rev-parse", "--show-toplevel"], cwd)) ?? cwd;
14
- const branch = (await git(["rev-parse", "--abbrev-ref", "HEAD"], cwd)) ?? "detached";
15
- return { repoRoot, branch };
16
- }
17
-
18
10
  export async function workingTreeDiff(cwd = process.cwd()): Promise<string> {
19
11
  const tracked = (await git(["diff", "HEAD"], cwd)) ?? "";
20
- // untracked files included by default (map note: changed-first)
12
+ // untracked files included by default
21
13
  const untrackedList = (await git(["ls-files", "--others", "--exclude-standard"], cwd)) ?? "";
22
14
  let untracked = "";
23
15
  for (const file of untrackedList.split("\n").filter(Boolean)) {
@@ -1,114 +0,0 @@
1
- /**
2
- * `cueloop session *` - mirrors the daemon socket API 1:1 (#14). One surface,
3
- * three consumers: agent adapters, the dev loop, and integrations. Output is
4
- * JSON on stdout; exit code 0 unless the daemon returned an error.
5
- */
6
-
7
- import type { ArtifactType, VerdictKind } from "@cueloop/schema";
8
- import { DaemonClient } from "@cueloop/daemon/client";
9
- import { parseArgs, flagStr } from "./args";
10
- import { resolveWorkspace } from "./workspace";
11
-
12
- async function readStdin(): Promise<string> {
13
- return await new Response(Bun.stdin.stream()).text();
14
- }
15
-
16
- function out(value: unknown): void {
17
- console.log(JSON.stringify(value, null, 2));
18
- }
19
-
20
- export async function sessionCommand(argv: string[]): Promise<number> {
21
- const { positional, flags } = parseArgs(argv);
22
- const verb = positional[0];
23
- const client = await DaemonClient.connect({ autostart: true });
24
- try {
25
- switch (verb) {
26
- case "create": {
27
- const workspace = await resolveWorkspace(flagStr(flags, "cwd"));
28
- const contentFile = flagStr(flags, "content-file");
29
- const content = contentFile ? await Bun.file(contentFile).text() : await readStdin();
30
- const session = await client.sessionCreate(workspace, {
31
- type: (flagStr(flags, "type") ?? "plan") as ArtifactType,
32
- content,
33
- meta: {
34
- agent: flagStr(flags, "agent"),
35
- agentSessionId: flagStr(flags, "agent-session-id"),
36
- planPath: flagStr(flags, "plan-path"),
37
- title: flagStr(flags, "title"),
38
- cwd: flagStr(flags, "cwd") ?? process.cwd(),
39
- },
40
- });
41
- out(session);
42
- return 0;
43
- }
44
- case "get": {
45
- out(await client.sessionGet(required(positional[1], "session id")));
46
- return 0;
47
- }
48
- case "list": {
49
- const status = flagStr(flags, "status") as "pending" | "resolved" | undefined;
50
- out(await client.sessionList(status ? { status } : undefined));
51
- return 0;
52
- }
53
- case "wait": {
54
- const id = required(positional[1], "session id");
55
- const timeoutMs = Number(flagStr(flags, "timeout-ms") ?? "60000");
56
- const session = await client.sessionWait(id, timeoutMs);
57
- if (session === null) {
58
- out({ status: "pending" });
59
- return 0;
60
- }
61
- out({
62
- status: "resolved",
63
- allow: session.verdict!.kind === "approve",
64
- verdict: session.verdict!.kind,
65
- feedback: session.verdict!.feedback,
66
- });
67
- return 0;
68
- }
69
- case "annotate": {
70
- const id = required(positional[1], "session id");
71
- const body = flagStr(flags, "body") ?? "";
72
- const quote = required(flagStr(flags, "quote"), "--quote");
73
- out(
74
- await client.sessionAnnotate(id, {
75
- id: flagStr(flags, "annotation-id") ?? `a_${Date.now().toString(36)}`,
76
- kind: flagStr(flags, "kind") ?? "comment",
77
- anchor: {
78
- quote,
79
- prefix: flagStr(flags, "prefix") ?? "",
80
- suffix: flagStr(flags, "suffix") ?? "",
81
- },
82
- body,
83
- }),
84
- );
85
- return 0;
86
- }
87
- case "resolve": {
88
- const id = required(positional[1], "session id");
89
- const kind = required(flagStr(flags, "verdict"), "--verdict") as VerdictKind;
90
- out(await client.sessionResolve(id, kind, flagStr(flags, "summary") ?? ""));
91
- return 0;
92
- }
93
- case "submit-revision": {
94
- const id = required(positional[1], "session id");
95
- const contentFile = flagStr(flags, "content-file");
96
- const content = contentFile ? await Bun.file(contentFile).text() : await readStdin();
97
- out(await client.sessionSubmitRevision(id, content));
98
- return 0;
99
- }
100
- default:
101
- console.error(
102
- "usage: cueloop session <create|get|list|wait|annotate|resolve|submit-revision> [flags]",
103
- );
104
- return 2;
105
- }
106
- } finally {
107
- client.close();
108
- }
109
- }
110
-
111
- function required<T>(v: T | undefined, what: string): T {
112
- if (v === undefined) throw new Error(`missing ${what}`);
113
- return v;
114
- }