scribeclock 0.2.0 → 0.3.0

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/README.md CHANGED
@@ -49,7 +49,8 @@ Run `scribeclock --help` for the full list and `scribeclock <command> --help` fo
49
49
  | Vault & env | `vault ls\|get\|set\|credential\|rm` · `env pull\|push` · `run -- <command>` |
50
50
  | Cloudflare | `cf accounts\|zones\|dns\|dns set\|dns rm\|dns diff\|pages\|deployments\|deploy-status\|workers\|purge\|request` |
51
51
  | Team | `team` · `overlap [files…]` (exit 4 on overlap) · `team report` · `handoff [record]` |
52
- | Git | `branch KEY [--create]` · `commit -m "…"` · `pr KEY` · `changelog --since <tag>` |
52
+ | Git | `branch KEY [--create]` · `commit -m "…"` · `pr KEY [--reviewer …]` · `changelog --since <tag>` |
53
+ | Pull requests | `prs [--mine]` · `pr gate [--all]` (exit 4 while a PR needs you) · `pr wait [N] [--deploy]` · `pr report [N\|URL] [--reviewer …]` |
53
54
  | Bug reports | `connect [--env] [--vault] [--create]` · `issues [show\|resolve --release X\|ignore\|reopen\|task\|urgency]` · `analytics [--days N] [--report X] [--csv]` · `ingest settings [--immediate critical --per-hour 2 --every 120]` · `bug "title" [-d …] [--log file] [--stack file]` · `ingest keys\|revoke\|test\|snippets\|forward [provider]` · `health [--days N]` |
54
55
  | Ops & agents | `doctor` · `watch tasks [--on-change cmd]` · `serve --stdio` · `mcp-config <client> [--install]` · `ask "…"` |
55
56
  | Raw tools | `tools` · `call <tool> [--arg v \| --args '{json}']` · `<tool_name> …` · `refresh` |
@@ -154,8 +155,23 @@ scribeclock hooks status
154
155
  With the hooks installed, the agent's session starts with one server call (`scribeclock session`, which
155
156
  runs `start_repo_session`: clock, your tasks, who is active, the handoff to resume from, overlaps, inbox),
156
157
  every file edit keeps your presence fresh (`scribeclock heartbeat`, debounced, no tokens), every `git push`
157
- tells teammates' agents to pull, every `git pull` clears the notice, and the session end leaves a handoff.
158
- Only warnings (a teammate pushed, someone is on the same file, a message) are put in front of the agent.
158
+ tells teammates' agents to pull, every `git pull` clears the notice, every `gh pr create` records the PR and
159
+ notifies its reviewers, and the session end leaves a handoff. Only warnings (a teammate pushed, a pull request
160
+ needs you, someone is on the same file, a message) are put in front of the agent.
161
+
162
+ ### Pull request gate
163
+
164
+ Like the pull notice, a pull request that needs you stays at the top of your agent's replies
165
+ (`pr_action_required`) until it is handled: a review someone asked of you, changes requested on yours, red CI,
166
+ an approved PR waiting to be merged, or a failed deploy after merge. Reviewers are notified as soon as the PR
167
+ is opened (through the GitHub webhook, or the hook above when `gh pr create` runs).
168
+
169
+ ```bash
170
+ scribeclock pr '#731' --reviewer octocat # open, notify, attach to the task
171
+ scribeclock prs # this repository's PRs and what each needs from you
172
+ scribeclock pr gate || echo "handle your PRs first" # exit 4 while something blocks
173
+ scribeclock pr wait --deploy # block until this branch's PR is merged and deployed
174
+ ```
159
175
  Commit `.claude/settings.json` / `.cursor/hooks.json` so the whole team gets it.
160
176
 
161
177
  `scribeclock session` and `scribeclock heartbeat` also work by hand, and `scribeclock serve --stdio` runs
@@ -17,6 +17,7 @@ import { changedFiles, currentBranch, detectTaskKey, git, gitState, lastCommit,
17
17
  import { EXIT } from "../types.js";
18
18
  import { fmtDate } from "../util/format.js";
19
19
  import { cmd, emit, list, num, str, taskKey } from "./_shared.js";
20
+ import { isGhPrCreate, prUrlFrom, reportNotice, reportPullRequest, reviewersFromCommand } from "./pulls.js";
20
21
  export const HOOK_CLIENTS = ["claude-code", "cursor"];
21
22
  /** Seconds between two presence reports for the same file set (new files always report). */
22
23
  export const HEARTBEAT_MIN_INTERVAL_S = 300;
@@ -44,8 +45,11 @@ export function parseHookEvent(input, client) {
44
45
  const path = str(ti.file_path) ?? str(ti.notebook_path);
45
46
  return { ...base, kind: "edit", files: path ? [path] : [] };
46
47
  }
47
- if (name === "PostToolUse" && tool === "Bash")
48
- return { ...base, kind: "shell", files: [], command: str(ti.command) ?? "" };
48
+ if (name === "PostToolUse" && tool === "Bash") {
49
+ const resp = input.tool_response;
50
+ const output = typeof resp === "string" ? resp : resp && typeof resp === "object" ? str(resp.stdout) : undefined;
51
+ return { ...base, kind: "shell", files: [], command: str(ti.command) ?? "", output };
52
+ }
49
53
  return { ...base, kind: "other", files: [] };
50
54
  }
51
55
  // Cursor
@@ -58,7 +62,7 @@ export function parseHookEvent(input, client) {
58
62
  return { ...base, kind: "edit", files: path ? [path] : [] };
59
63
  }
60
64
  if (name === "afterShellExecution")
61
- return { ...base, kind: "shell", files: [], command: str(input.command) ?? "" };
65
+ return { ...base, kind: "shell", files: [], command: str(input.command) ?? "", output: str(input.output) };
62
66
  return { ...base, kind: "other", files: [] };
63
67
  }
64
68
  export function isGitPush(command) {
@@ -181,6 +185,8 @@ export function presenceNotices(data) {
181
185
  const lines = [];
182
186
  if (typeof data.git_pull_required === "string")
183
187
  lines.push(data.git_pull_required.split(". In your local")[0] + ". Run `git pull --rebase --autostash` before touching files.");
188
+ if (typeof data.pr_action_required === "string")
189
+ lines.push(data.pr_action_required);
184
190
  const overlaps = Array.isArray(data.overlaps) ? data.overlaps : [];
185
191
  for (const o of overlaps.slice(0, 3)) {
186
192
  const who = o.is_my_other_session ? "Your other agent session" : String(o.person?.name ?? o.person?.email ?? "A teammate");
@@ -258,7 +264,7 @@ export const sessionCommand = cmd({
258
264
  const lines = [
259
265
  `ScribeClock session started (${repo}). Hooks are installed: presence heartbeats, push notices and pull checks are automatic — do not call report_repo_activity, announce_push or check_repo_overlap yourself; still use report_task_progress on the person's task and record_handoff when stopping.`,
260
266
  String(data.brief ?? ""),
261
- ...presenceNotices({ git_pull_required: data.git_pull_required, inbox: data.inbox }),
267
+ ...presenceNotices({ git_pull_required: data.git_pull_required, pr_action_required: data.pr_action_required, inbox: data.inbox }),
262
268
  ].filter(Boolean);
263
269
  ctx.out.stdout.write(JSON.stringify(hookContext(client, event?.eventName || "SessionStart", lines.join("\n"))) + "\n");
264
270
  return EXIT.OK;
@@ -281,6 +287,8 @@ function renderSession(ctx, data, repo) {
281
287
  ctx.out.warn(String(w));
282
288
  if (typeof data.git_pull_required === "string")
283
289
  ctx.out.warn(String(data.git_pull_required).split(". In your local")[0] + ".");
290
+ if (typeof data.pr_action_required === "string")
291
+ ctx.out.warn(String(data.pr_action_required));
284
292
  }
285
293
  // ---------------------------------------------------------------------------
286
294
  // scribeclock heartbeat
@@ -289,8 +297,8 @@ export const heartbeatCommand = cmd({
289
297
  path: "heartbeat",
290
298
  group: "Automation & agents",
291
299
  summary: "Report presence from the local git state, debounced; as a hook it also announces pushes and records pulls.",
292
- description: "Sends report_repo_activity with the branch, the files touched recently and the git state, but only when new files appear or --min-interval seconds passed (so an editor hook can call it on every edit for free). With --hook claude-code|cursor it reads the hook event from stdin: file edits become presence, a `git push` becomes announce_push, a `git pull` clears the pull notice, and the session end leaves a handoff. Only warnings (a teammate's push, an overlap, a message) are printed back into the agent's context; nothing else costs tokens.",
293
- tool: ["report_repo_activity", "announce_push", "record_handoff"],
300
+ description: "Sends report_repo_activity with the branch, the files touched recently and the git state, but only when new files appear or --min-interval seconds passed (so an editor hook can call it on every edit for free). With --hook claude-code|cursor it reads the hook event from stdin: file edits become presence, a `git push` becomes announce_push, a `git pull` clears the pull notice, `gh pr create` / `gh pr ready` becomes report_pull_request (reviewers notified), and the session end leaves a handoff. Only warnings (a teammate's push, a pull request that needs you, an overlap, a message) are printed back into the agent's context; nothing else costs tokens.",
301
+ tool: ["report_repo_activity", "announce_push", "record_handoff", "report_pull_request"],
294
302
  positionals: [{ name: "files", variadic: true, description: "Files touched (default: from the hook event, else uncommitted changes)." }],
295
303
  flags: [
296
304
  REPO_FLAG,
@@ -307,7 +315,7 @@ export const heartbeatCommand = cmd({
307
315
  const event = client ? parseHookEvent(await readStdinJson(ctx), client) : null;
308
316
  if (event && event.kind === "other")
309
317
  return EXIT.OK;
310
- if (event && event.kind === "shell" && !isGitPush(event.command) && !isGitPull(event.command))
318
+ if (event && event.kind === "shell" && !isGitPush(event.command) && !isGitPull(event.command) && !isGhPrCreate(event.command))
311
319
  return EXIT.OK;
312
320
  const cwd = event?.cwd ?? ctx.cwd;
313
321
  const repo = str(inv.flags.repo) ?? repoRef(cwd);
@@ -363,6 +371,16 @@ export const heartbeatCommand = cmd({
363
371
  return EXIT.OK;
364
372
  });
365
373
  }
374
+ if (event?.kind === "shell" && isGhPrCreate(event.command)) {
375
+ return guard(async () => {
376
+ const data = await reportPullRequest(ctx, { cwd, repo, url: prUrlFrom(event.output), reviewers: reviewersFromCommand(event.command) });
377
+ state.last_error = null;
378
+ writeState(path, state);
379
+ if (client && data)
380
+ ctx.out.stdout.write(JSON.stringify(hookContext(client, event.eventName, `ScribeClock: ${reportNotice(data)}`)) + "\n");
381
+ return EXIT.OK;
382
+ });
383
+ }
366
384
  if (event?.kind === "shell" && isGitPull(event.command)) {
367
385
  return guard(async () => {
368
386
  await ctx.call("report_repo_activity", { repo, branch, pulled: true, git: gitState(cwd), session_key: sessionKey, client_name: clientLabel(client) });
@@ -4,6 +4,7 @@ import { changedFiles, currentBranch, detectTaskKey, git, gitState, githubSlug,
4
4
  import { EXIT } from "../types.js";
5
5
  import { fmtDate, parseWhen, slugify } from "../util/format.js";
6
6
  import { PROJECT_FLAG, bool, cmd, emit, list, personName, projectIdArg, str, taskKey } from "./_shared.js";
7
+ import { reportNotice, reportPullRequest } from "./pulls.js";
7
8
  /** feat/123-short-title — the prefix comes from .scribeclock.json → branch_prefix (default feat). */
8
9
  export function branchNameFor(ctx, task, prefix) {
9
10
  const p = prefix ?? ctx.repo.config.branch_prefix ?? "feat";
@@ -105,12 +106,13 @@ export const commitCommand = cmd({
105
106
  export const prCommand = cmd({
106
107
  path: "pr",
107
108
  group: "Git",
108
- summary: "Open a GitHub pull request for a task (title + task link + summary) and attach it to the task as evidence.",
109
+ summary: "Open a GitHub pull request for a task, notify its reviewers through ScribeClock, and attach it to the task as evidence.",
109
110
  description: "Needs the GitHub CLI (`gh`) and a pushed branch. The PR title is \"#123 Task title\", the body links the ScribeClock task; the PR url is then reported on the task (outcome=progress, pull_request evidence).",
110
- tool: ["get_task", "report_task_progress"],
111
+ tool: ["get_task", "report_task_progress", "report_pull_request"],
111
112
  positionals: [{ name: "task", description: "Task key (default: detected from git)." }],
112
113
  flags: [
113
114
  { name: "base", alias: "B", type: "string", description: "Base branch (default: the repository default)." },
115
+ { name: "reviewer", type: "array", description: "Reviewers (GitHub logins; emails or member names are notified on ScribeClock only). Each is told to review before new work." },
114
116
  { name: "draft", type: "boolean", description: "Open as a draft." },
115
117
  { name: "body", type: "string", description: "Extra body text (@file reads a file)." },
116
118
  { name: "no-report", type: "boolean", description: "Do not post the PR on the task." },
@@ -134,6 +136,10 @@ export const prCommand = cmd({
134
136
  args.push("--base", String(inv.flags.base));
135
137
  if (inv.flags.draft)
136
138
  args.push("--draft");
139
+ const reviewers = list(inv.flags.reviewer) ?? [];
140
+ const ghReviewers = reviewers.filter((r) => /^@?[A-Za-z0-9][A-Za-z0-9-]{0,38}$/.test(r)).map((r) => r.replace(/^@/, ""));
141
+ if (ghReviewers.length)
142
+ args.push("--reviewer", ghReviewers.join(","));
137
143
  if (ctx.flags.dryRun) {
138
144
  ctx.out.log(`${ctx.out.dim("dry run →")} gh ${args.map((a) => (a.includes(" ") || a.includes("\n") ? JSON.stringify(a.slice(0, 60)) : a)).join(" ")}`);
139
145
  return EXIT.OK;
@@ -143,10 +149,16 @@ export const prCommand = cmd({
143
149
  throw new CliError(`gh pr create failed: ${(r.stderr || r.stdout).trim()}`, { id: "gh_failed", hint: "Push the branch first (git push -u origin HEAD) and make sure gh is logged in." });
144
150
  const url = (r.stdout.trim().split("\n").pop() ?? "").trim();
145
151
  ctx.out.info(`${ctx.out.green("✓")} ${url}`);
152
+ const repo = repoRef(ctx.cwd);
153
+ const gate = repo ? await reportPullRequest(ctx, { cwd: ctx.cwd, repo, url, reviewers }).catch((err) => ({ ok: false, message: err instanceof Error ? err.message : String(err) })) : null;
154
+ if (gate && gate.ok !== false)
155
+ ctx.out.info(reportNotice(gate));
156
+ else if (gate)
157
+ ctx.out.warn(`Reviewers not notified on ScribeClock: ${String(gate.message ?? "error")} (scribeclock pr report)`);
146
158
  if (inv.flags["no-report"])
147
- return emit(ctx, { ok: true, url, reported: false }, () => undefined);
159
+ return emit(ctx, { ok: true, url, reported: false, pull_request: gate }, () => undefined);
148
160
  const report = await ctx.call("report_task_progress", { task_id: key, outcome: "progress", summary: `Opened pull request ${url}`, evidence: [{ kind: "pull_request", title, url }], repo: repoRef(ctx.cwd) ?? undefined, branch, git: gitState(ctx.cwd) });
149
- return emit(ctx, { ok: true, url, reported: true, report }, () => ctx.out.log(`${ctx.out.green("✓")} Pull request attached to ${String(t.key ?? key)}.`));
161
+ return emit(ctx, { ok: true, url, reported: true, report, pull_request: gate }, () => ctx.out.log(`${ctx.out.green("✓")} Pull request attached to ${String(t.key ?? key)}.`));
150
162
  },
151
163
  });
152
164
  export const changelogCommand = cmd({
@@ -12,6 +12,7 @@ import { CF_COMMANDS } from "./cf.js";
12
12
  import { TEAM_COMMANDS } from "./team.js";
13
13
  import { WORKFLOW_COMMANDS } from "./workflow.js";
14
14
  import { GITFLOW_COMMANDS } from "./gitflow.js";
15
+ import { PULL_COMMANDS } from "./pulls.js";
15
16
  import { OPS_COMMANDS } from "./ops.js";
16
17
  import { AUTOMATION_COMMANDS } from "./automation.js";
17
18
  import { INGEST_COMMANDS } from "./ingest.js";
@@ -24,6 +25,7 @@ export function buildRegistry() {
24
25
  registry.add(...CLOCK_COMMANDS);
25
26
  registry.add(...TASK_COMMANDS);
26
27
  registry.add(...GITFLOW_COMMANDS);
28
+ registry.add(...PULL_COMMANDS);
27
29
  registry.add(...INGEST_COMMANDS);
28
30
  registry.add(...PROJECT_COMMANDS);
29
31
  registry.add(...MEETING_COMMANDS);
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Pull request gate: `prs`, `pr gate`, `pr wait`, `pr report`.
3
+ *
4
+ * Like the push notice (git_pull_required), the server keeps every pull request that needs a person — a review
5
+ * asked of them, changes requested on theirs, red CI, approved and ready to merge, a failed deploy — and puts it
6
+ * at the top of their agent's replies (pr_action_required) until it is resolved. These commands read and feed
7
+ * that gate from a terminal or a script: `pr gate` exits 4 while something blocks, `pr wait` blocks until a PR
8
+ * is merged (and deployed with --deploy), the way `git pull` blocks until the tree is current.
9
+ */
10
+ import { spawnSync } from "node:child_process";
11
+ import { CliError, usageError } from "../cli/errors.js";
12
+ import { currentBranch, lastCommit, repoRef } from "../git.js";
13
+ import { EXIT } from "../types.js";
14
+ import { cmd, emit, list, num, str } from "./_shared.js";
15
+ /** A PR number from a flag, positional ("42", "#42") or gh JSON. */
16
+ export function prNumber(v) {
17
+ const n = typeof v === "number" ? v : typeof v === "string" && /^#?\d+$/.test(v.trim()) ? Number(v.trim().replace(/^#/, "")) : undefined;
18
+ return n && n > 0 ? n : undefined;
19
+ }
20
+ const PR_URL = /https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/(\d+)/;
21
+ /** `gh pr create` / `gh pr ready` in a shell command (also after `&&`, `;` or a pipe). */
22
+ export function isGhPrCreate(command) {
23
+ return Boolean(command && /(^|[;&|\s])gh\s+pr\s+(create|ready)\b/.test(command));
24
+ }
25
+ /** The PR link `gh pr create` printed, if any. */
26
+ export function prUrlFrom(text) {
27
+ const m = text ? PR_URL.exec(text) : null;
28
+ return m ? m[0] : null;
29
+ }
30
+ /** Reviewers named on a `gh pr create` command line (`--reviewer a,b`, `-r a`). */
31
+ export function reviewersFromCommand(command) {
32
+ if (!command)
33
+ return [];
34
+ const out = [];
35
+ const re = /(?:--reviewer|-r)(?:=|\s+)("[^"]*"|'[^']*'|[^\s;&|]+)/g;
36
+ for (let m = re.exec(command); m; m = re.exec(command))
37
+ out.push(...m[1].replace(/^["']|["']$/g, "").split(",").map((s) => s.trim()).filter(Boolean));
38
+ return [...new Set(out)];
39
+ }
40
+ /** `gh pr view` for the current branch (or a number): what report_pull_request needs. Null without gh or a PR. */
41
+ export function ghPrView(cwd, ref, env = process.env) {
42
+ if (env.SCRIBECLOCK_GH === "0")
43
+ return null;
44
+ const args = ["pr", "view", ...(ref ? [ref] : []), "--json", "number,url,title,headRefName,baseRefName,isDraft,headRefOid,reviewRequests"];
45
+ const r = spawnSync("gh", args, { cwd, encoding: "utf8", timeout: 15_000 });
46
+ if (r.status !== 0 || !r.stdout)
47
+ return null;
48
+ try {
49
+ return JSON.parse(r.stdout);
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ /** report_pull_request arguments from `gh pr view` output plus any reviewers named elsewhere. */
56
+ export function reportArgsFromGh(repo, view, extraReviewers = []) {
57
+ const requested = Array.isArray(view.reviewRequests) ? view.reviewRequests.map((r) => str(r.login)).filter((x) => Boolean(x)) : [];
58
+ return {
59
+ repo,
60
+ url: str(view.url),
61
+ number: prNumber(view.number),
62
+ title: str(view.title),
63
+ head_branch: str(view.headRefName),
64
+ base_branch: str(view.baseRefName),
65
+ draft: view.isDraft === true,
66
+ reviewers: [...new Set([...requested, ...extraReviewers])],
67
+ };
68
+ }
69
+ /** Reports the PR a hook or `scribeclock pr` just created; returns the server reply (or null when nothing is known). */
70
+ export async function reportPullRequest(ctx, opts) {
71
+ const view = ghPrView(opts.cwd, opts.url ?? undefined, ctx.env);
72
+ const args = view
73
+ ? reportArgsFromGh(opts.repo, view, opts.reviewers)
74
+ : { repo: opts.repo, url: opts.url ?? undefined, head_branch: currentBranch(opts.cwd) ?? undefined, reviewers: opts.reviewers ?? [] };
75
+ if (!args.url && !args.number)
76
+ return null;
77
+ return ctx.call("report_pull_request", args);
78
+ }
79
+ /** One line for a reviewer's / author's agent after report_pull_request. */
80
+ export function reportNotice(data) {
81
+ const pr = (data.pull_request ?? {});
82
+ const notified = Array.isArray(data.notified) ? data.notified.map((p) => String(p.name ?? p.email ?? "a teammate")) : [];
83
+ const unresolved = Array.isArray(data.unresolved_reviewers) ? data.unresolved_reviewers : [];
84
+ return `PR #${String(pr.number ?? "?")} recorded on ScribeClock${notified.length ? `; reviewers notified: ${notified.join(", ")}` : data.already_notified ? "; reviewers were already notified" : ""}.` +
85
+ (unresolved.length ? ` Not found in the organization: ${unresolved.join(", ")}.` : "") +
86
+ (data.hint ? ` ${String(data.hint)}` : "");
87
+ }
88
+ function gateLine(ctx, g) {
89
+ const mark = g.blocking ? ctx.out.red("●") : ctx.out.yellow("○");
90
+ return `${mark} ${ctx.out.bold(`#${String(g.number ?? "?")}`)} ${String(g.status ?? "").replace(/_/g, " ")} ${ctx.out.dim(`(${String(g.role ?? "")}, ${String(g.repo_name ?? g.repo ?? "")})`)}\n ${String(g.action ?? "")}`;
91
+ }
92
+ function prStatus(pr) {
93
+ if (pr.state === "merged")
94
+ return pr.deploy?.state ? `merged · deploy ${pr.deploy.state}` : "merged";
95
+ if (pr.state === "closed")
96
+ return "closed";
97
+ if (pr.draft)
98
+ return "draft";
99
+ const parts = [`${pr.approvals ?? 0} approval${pr.approvals === 1 ? "" : "s"}`];
100
+ if ((pr.reviewers ?? []).some((r) => r.review === "changes_requested"))
101
+ parts.push("changes requested");
102
+ if (pr.checks)
103
+ parts.push(`CI ${pr.checks}`);
104
+ return parts.join(" · ");
105
+ }
106
+ const REPO_FLAG = { name: "repo", alias: "r", type: "string", placeholder: "<remote|owner/repo>", description: "Repository (default: this folder's git origin)." };
107
+ // ---------------------------------------------------------------------------
108
+ // scribeclock prs
109
+ // ---------------------------------------------------------------------------
110
+ export const prsCommand = cmd({
111
+ path: "prs",
112
+ group: "Git",
113
+ summary: "Pull requests of this repository (or yours everywhere with --mine) and what each needs from you.",
114
+ tool: "list_pull_requests",
115
+ flags: [
116
+ REPO_FLAG,
117
+ { name: "state", alias: "s", type: "string", choices: ["open", "merged", "closed", "all"], description: "Default open." },
118
+ { name: "mine", type: "boolean", description: "Only PRs you authored or review, in every repository." },
119
+ ],
120
+ examples: ["scribeclock prs", "scribeclock prs --state merged", "scribeclock prs --mine --json"],
121
+ async run(ctx, inv) {
122
+ const mine = inv.flags.mine === true;
123
+ const repo = mine ? str(inv.flags.repo) : str(inv.flags.repo) ?? repoRef(ctx.cwd) ?? undefined;
124
+ const data = await ctx.call("list_pull_requests", { repo, state: str(inv.flags.state), mine: mine || undefined });
125
+ return emit(ctx, data, () => {
126
+ const prs = (data.pull_requests ?? []);
127
+ if (!prs.length)
128
+ ctx.out.log(ctx.out.dim("No pull requests recorded. They appear when the GitHub webhook delivers or after report_pull_request."));
129
+ else
130
+ ctx.out.table(["#", "Title", "Branch", "Status", "Needs you"], prs.map((p) => [p.number, p.title ?? "", `${p.head_branch ?? "?"} → ${p.base_branch ?? "?"}`, prStatus(p), p.needs_you ? String(p.needs_you.status ?? "").replace(/_/g, " ") : ""]));
131
+ const gate = (data.gate ?? []);
132
+ if (gate.length) {
133
+ ctx.out.log("");
134
+ for (const g of gate)
135
+ ctx.out.log(gateLine(ctx, g));
136
+ }
137
+ });
138
+ },
139
+ });
140
+ // ---------------------------------------------------------------------------
141
+ // scribeclock pr gate
142
+ // ---------------------------------------------------------------------------
143
+ export const prGateCommand = cmd({
144
+ path: "pr gate",
145
+ group: "Git",
146
+ summary: "What pull requests need from you before new work; exits 4 while something blocks (for scripts and pre-work checks).",
147
+ description: "Blocking: a review asked of you, changes requested on your PR, red CI, an approved PR waiting to be merged, a failed deploy after merge. Waiting on others (review, CI, deploy) is listed but does not block. --all covers every repository you work in.",
148
+ tool: "list_pull_requests",
149
+ flags: [REPO_FLAG, { name: "all", type: "boolean", description: "Every repository, not just this one." }],
150
+ examples: ["scribeclock pr gate", "scribeclock pr gate --all || echo 'resolve your PRs first'"],
151
+ async run(ctx, inv) {
152
+ const repo = inv.flags.all ? undefined : str(inv.flags.repo) ?? repoRef(ctx.cwd) ?? undefined;
153
+ const data = await ctx.call("list_pull_requests", { repo, mine: true });
154
+ const gate = (data.gate ?? []);
155
+ const blocking = gate.filter((g) => g.blocking);
156
+ emit(ctx, { ok: true, repo: repo ?? null, blocking: blocking.length, gate }, () => {
157
+ if (!gate.length)
158
+ return ctx.out.log(`${ctx.out.green("✓")} No pull request needs you${repo ? ` in ${repo}` : ""}.`);
159
+ for (const g of gate)
160
+ ctx.out.log(gateLine(ctx, g));
161
+ });
162
+ return blocking.length ? EXIT.CONFLICT : EXIT.OK;
163
+ },
164
+ });
165
+ /** Where a PR stands for `pr wait`: done (merged, or deployed with --deploy), failed, or still waiting. */
166
+ export function waitOutcome(pr, wantDeploy) {
167
+ if (!pr)
168
+ return "waiting";
169
+ if (pr.state === "closed")
170
+ return "closed";
171
+ if (pr.state !== "merged")
172
+ return "waiting";
173
+ if (!wantDeploy)
174
+ return "merged";
175
+ if (pr.deploy?.state === "failure")
176
+ return "deploy_failed";
177
+ return pr.deploy?.state === "success" ? "deployed" : "waiting";
178
+ }
179
+ export const prWaitCommand = cmd({
180
+ path: "pr wait",
181
+ group: "Git",
182
+ summary: "Block until a pull request is merged (--deploy: and deployed), printing reviews, CI and deploy as they change.",
183
+ description: "Default PR: the open one for the current branch. Exit 0 when merged (or deployed with --deploy), 1 when it was closed without merging, the deploy failed, or --timeout passed. While waiting, the reviewers have already been told through ScribeClock.",
184
+ tool: "list_pull_requests",
185
+ positionals: [{ name: "number", description: "PR number (default: the PR of the current branch)." }],
186
+ flags: [
187
+ REPO_FLAG,
188
+ { name: "deploy", type: "boolean", description: "Also wait for a successful production deploy of the merge." },
189
+ { name: "interval", type: "number", placeholder: "<seconds>", description: "Seconds between checks (default 30).", default: 30 },
190
+ { name: "timeout", type: "number", placeholder: "<minutes>", description: "Give up after this many minutes (default 120).", default: 120 },
191
+ { name: "once", type: "boolean", description: "Check once and exit (scripts, tests)." },
192
+ ],
193
+ examples: ["scribeclock pr wait", "scribeclock pr wait 42 --deploy --timeout 60"],
194
+ async run(ctx, inv) {
195
+ const repo = str(inv.flags.repo) ?? repoRef(ctx.cwd);
196
+ if (!repo)
197
+ throw usageError("Not in a git repository.", "Pass --repo owner/repo.");
198
+ let number = prNumber(inv.positionals[0]);
199
+ if (!number) {
200
+ const branch = currentBranch(ctx.cwd);
201
+ const data = await ctx.call("list_pull_requests", { repo, state: "open" });
202
+ const mine = (data.pull_requests ?? []).find((p) => p.head_branch && p.head_branch === branch);
203
+ number = mine?.number ?? prNumber(ghPrView(ctx.cwd, undefined, ctx.env)?.number);
204
+ if (!number)
205
+ throw usageError(`No open pull request for ${branch ?? "this branch"}.`, "Pass the PR number: scribeclock pr wait 42");
206
+ }
207
+ const wantDeploy = inv.flags.deploy === true;
208
+ const interval = Math.max(5, num(inv.flags.interval) ?? 30) * 1000;
209
+ const deadline = ctx.now().getTime() + Math.max(1, num(inv.flags.timeout) ?? 120) * 60_000;
210
+ let last = "";
211
+ let stop = false;
212
+ const onSignal = () => {
213
+ stop = true;
214
+ };
215
+ process.once("SIGINT", onSignal);
216
+ try {
217
+ for (;;) {
218
+ const data = await ctx.call("list_pull_requests", { repo, number, state: "all" });
219
+ const pr = (data.pull_requests ?? [])[0];
220
+ const outcome = waitOutcome(pr, wantDeploy);
221
+ const line = pr ? `#${number} ${prStatus(pr)}${pr.needs_you?.action ? ` — ${pr.needs_you.action}` : ""}` : `#${number} not recorded yet`;
222
+ if (line !== last) {
223
+ if (ctx.flags.json)
224
+ ctx.out.ndjson({ event: "pr_status", at: ctx.now().toISOString(), number, outcome, pull_request: pr ?? null });
225
+ else
226
+ ctx.out.log(`${ctx.out.dim(ctx.now().toISOString().slice(11, 19))} ${line}`);
227
+ last = line;
228
+ }
229
+ if (outcome === "merged" || outcome === "deployed") {
230
+ if (!ctx.flags.json)
231
+ ctx.out.log(`${ctx.out.green("✓")} #${number} ${outcome}. Pull the base branch: git checkout ${pr?.base_branch ?? "main"} && git pull --rebase --autostash`);
232
+ return EXIT.OK;
233
+ }
234
+ if (outcome === "closed" || outcome === "deploy_failed")
235
+ throw new CliError(`#${number} ${outcome === "closed" ? "was closed without merging" : "was merged but its deploy failed"}.`, { id: outcome });
236
+ if (inv.flags.once || stop)
237
+ return EXIT.OK;
238
+ if (ctx.now().getTime() >= deadline)
239
+ throw new CliError(`#${number} is still not ${wantDeploy ? "deployed" : "merged"} after ${num(inv.flags.timeout) ?? 120} minutes.`, { id: "timeout", hint: "Ask the reviewers (scribeclock prs) or wait longer with --timeout." });
240
+ await new Promise((r) => setTimeout(r, interval));
241
+ }
242
+ }
243
+ finally {
244
+ process.off("SIGINT", onSignal);
245
+ }
246
+ },
247
+ });
248
+ // ---------------------------------------------------------------------------
249
+ // scribeclock pr report
250
+ // ---------------------------------------------------------------------------
251
+ export const prReportCommand = cmd({
252
+ path: "pr report",
253
+ group: "Git",
254
+ summary: "Record a pull request on ScribeClock and notify its reviewers (what the hook does after `gh pr create`).",
255
+ tool: "report_pull_request",
256
+ positionals: [{ name: "pr", description: "PR number or URL (default: the PR of the current branch, via gh)." }],
257
+ flags: [REPO_FLAG, { name: "reviewer", type: "array", description: "Reviewers: GitHub logins, emails or member names (comma-separated or repeated)." }],
258
+ examples: ["scribeclock pr report", "scribeclock pr report 42 --reviewer octocat,sam@example.com"],
259
+ async run(ctx, inv) {
260
+ const repo = str(inv.flags.repo) ?? repoRef(ctx.cwd);
261
+ if (!repo)
262
+ throw usageError("Not in a git repository.", "Pass --repo owner/repo.");
263
+ const ref = inv.positionals[0];
264
+ const reviewers = list(inv.flags.reviewer) ?? [];
265
+ const view = ghPrView(ctx.cwd, ref, ctx.env);
266
+ const args = view
267
+ ? reportArgsFromGh(repo, view, reviewers)
268
+ : { repo, url: prUrlFrom(ref) ?? undefined, number: prNumber(ref), head_branch: currentBranch(ctx.cwd) ?? undefined, reviewers };
269
+ if (!args.url && !args.number)
270
+ throw usageError("Which pull request?", "Pass its number or URL, or install gh (https://cli.github.com) so the current branch's PR is found.");
271
+ if (!view && !args.head_branch)
272
+ args.head_branch = currentBranch(ctx.cwd) ?? undefined;
273
+ if (!args.title)
274
+ args.title = lastCommit(ctx.cwd)?.message.split("\n")[0];
275
+ const data = await ctx.call("report_pull_request", args);
276
+ return emit(ctx, data, () => ctx.out.log(`${ctx.out.green("✓")} ${reportNotice(data)}`));
277
+ },
278
+ });
279
+ export const PULL_COMMANDS = [prsCommand, prGateCommand, prWaitCommand, prReportCommand];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scribeclock",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "ScribeClock from the terminal: tasks, time clock, projects, PRDs, meetings, files, vault and Cloudflare — a thin client over the ScribeClock MCP server.",
5
5
  "license": "UNLICENSED",
6
6
  "author": "Haydar Al-Karar LLC, dba Karar Tech",