scribeclock 0.1.7 → 0.2.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
@@ -143,8 +143,24 @@ Put a `.scribeclock.json` at the repository root to save typing:
143
143
 
144
144
  ## Agents
145
145
 
146
- `scribeclock serve --stdio` runs the CLI as a local MCP server that proxies to ScribeClock with your
147
- login, for clients that prefer local servers. `scribeclock mcp-config claude-code|cursor|vscode|windsurf|codex|gemini [--local] [--install]`
146
+ Connected coding agents cost tokens every time they talk to ScribeClock. Two commands take most of that
147
+ traffic out of the model loop:
148
+
149
+ ```bash
150
+ scribeclock hooks install # Claude Code: .claude/settings.json; or: scribeclock hooks install cursor
151
+ scribeclock hooks status
152
+ ```
153
+
154
+ With the hooks installed, the agent's session starts with one server call (`scribeclock session`, which
155
+ runs `start_repo_session`: clock, your tasks, who is active, the handoff to resume from, overlaps, inbox),
156
+ 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.
159
+ Commit `.claude/settings.json` / `.cursor/hooks.json` so the whole team gets it.
160
+
161
+ `scribeclock session` and `scribeclock heartbeat` also work by hand, and `scribeclock serve --stdio` runs
162
+ the CLI as a local MCP server that proxies to ScribeClock with your login, for clients that prefer local
163
+ servers. `scribeclock mcp-config claude-code|cursor|vscode|windsurf|codex|gemini [--local] [--install]`
148
164
  prints or writes the matching client configuration. `scribeclock ask "what's overdue for me?"` maps a
149
165
  plain request to one tool call (built-in rules, no AI service), shows it, and asks before anything that
150
166
  writes.
@@ -0,0 +1,619 @@
1
+ /**
2
+ * Agent hooks: presence, push notices and the session brief without spending model tokens.
3
+ *
4
+ * `scribeclock session` makes the one start-of-session call (start_repo_session) and prints its brief;
5
+ * `scribeclock heartbeat` reports presence from the local git state, debounced, and reads editor / agent hook
6
+ * events (Claude Code, Cursor) from stdin so file edits, pushes and pulls reach ScribeClock from a hook instead
7
+ * of a tool call; `scribeclock hooks install` writes the hook configuration. Everything a hook runs is fail-soft:
8
+ * an error is recorded for `hooks status` and never blocks the agent.
9
+ */
10
+ import { accessSync, constants, existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
13
+ import { createHash } from "node:crypto";
14
+ import { CliError, usageError } from "../cli/errors.js";
15
+ import { ensureDirPrivate, writeJsonPrivate } from "../config.js";
16
+ import { changedFiles, currentBranch, detectTaskKey, git, gitState, lastCommit, repoRef, repoRoot } from "../git.js";
17
+ import { EXIT } from "../types.js";
18
+ import { fmtDate } from "../util/format.js";
19
+ import { cmd, emit, list, num, str, taskKey } from "./_shared.js";
20
+ export const HOOK_CLIENTS = ["claude-code", "cursor"];
21
+ /** Seconds between two presence reports for the same file set (new files always report). */
22
+ export const HEARTBEAT_MIN_INTERVAL_S = 300;
23
+ /** Files touched longer ago than this drop out of the reported set. */
24
+ const FILE_WINDOW_MS = 90 * 60_000;
25
+ const MAX_REPORTED_FILES = 50;
26
+ const EDIT_TOOLS = /^(Edit|Write|MultiEdit|NotebookEdit)$/;
27
+ /** Normalises what Claude Code / Cursor put on a hook's stdin. Unknown shapes become "other" (ignored). */
28
+ export function parseHookEvent(input, client) {
29
+ if (!input)
30
+ return { kind: "other", files: [] };
31
+ const ti = (input.tool_input ?? {});
32
+ const name = String(input.hook_event_name ?? "");
33
+ const roots = Array.isArray(input.workspace_roots) ? input.workspace_roots.map(String) : [];
34
+ const cwd = str(input.cwd) ?? roots[0];
35
+ const sessionId = str(input.session_id) ?? str(input.conversation_id);
36
+ const base = { sessionId, cwd, eventName: name };
37
+ if (client === "claude-code") {
38
+ if (name === "SessionStart")
39
+ return { ...base, kind: "session_start", files: [] };
40
+ if (name === "SessionEnd")
41
+ return { ...base, kind: "session_end", files: [] };
42
+ const tool = String(input.tool_name ?? "");
43
+ if (name === "PostToolUse" && EDIT_TOOLS.test(tool)) {
44
+ const path = str(ti.file_path) ?? str(ti.notebook_path);
45
+ return { ...base, kind: "edit", files: path ? [path] : [] };
46
+ }
47
+ if (name === "PostToolUse" && tool === "Bash")
48
+ return { ...base, kind: "shell", files: [], command: str(ti.command) ?? "" };
49
+ return { ...base, kind: "other", files: [] };
50
+ }
51
+ // Cursor
52
+ if (name === "sessionStart")
53
+ return { ...base, kind: "session_start", files: [] };
54
+ if (name === "sessionEnd" || name === "stop")
55
+ return { ...base, kind: "session_end", files: [] };
56
+ if (name === "afterFileEdit" || name === "afterTabFileEdit") {
57
+ const path = str(input.file_path);
58
+ return { ...base, kind: "edit", files: path ? [path] : [] };
59
+ }
60
+ if (name === "afterShellExecution")
61
+ return { ...base, kind: "shell", files: [], command: str(input.command) ?? "" };
62
+ return { ...base, kind: "other", files: [] };
63
+ }
64
+ export function isGitPush(command) {
65
+ return Boolean(command && /(^|[;&|\s])git\s+(?:-C\s+\S+\s+)?push\b/.test(command));
66
+ }
67
+ export function isGitPull(command) {
68
+ return Boolean(command && /(^|[;&|\s])git\s+(?:-C\s+\S+\s+)?pull\b/.test(command));
69
+ }
70
+ async function readStdinJson(ctx) {
71
+ if (ctx.stdin.isTTY)
72
+ return null;
73
+ const chunks = [];
74
+ try {
75
+ for await (const chunk of ctx.stdin.stream)
76
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ const text = Buffer.concat(chunks).toString("utf8").trim();
82
+ if (!text)
83
+ return null;
84
+ try {
85
+ const parsed = JSON.parse(text);
86
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
87
+ }
88
+ catch {
89
+ return null;
90
+ }
91
+ }
92
+ /** The session key teammates see: SCRIBECLOCK_SESSION, else the agent's session id, else "cli". */
93
+ export function sessionKeyFor(env, client, sessionId) {
94
+ if (env.SCRIBECLOCK_SESSION)
95
+ return env.SCRIBECLOCK_SESSION;
96
+ if (client && sessionId)
97
+ return `${client}-${sessionId.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 12)}`;
98
+ return "cli";
99
+ }
100
+ function clientLabel(client) {
101
+ return client === "claude-code" ? "Claude Code (hook)" : client === "cursor" ? "Cursor (hook)" : "ScribeClock CLI";
102
+ }
103
+ export function statePath(configDir, repo, sessionKey) {
104
+ const key = createHash("sha256").update(`${repo.toLowerCase()}\n${sessionKey}`).digest("hex").slice(0, 16);
105
+ return join(configDir, "state", `presence-${key}.json`);
106
+ }
107
+ export function readState(path, repo, sessionKey) {
108
+ try {
109
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
110
+ if (parsed.version === 1 && parsed.files && typeof parsed.files === "object")
111
+ return parsed;
112
+ }
113
+ catch {
114
+ /* fresh */
115
+ }
116
+ return { version: 1, repo, session_key: sessionKey, files: {}, last_sent_at: null, last_sent_files: [], last_error: null, last_error_at: null };
117
+ }
118
+ function writeState(path, state) {
119
+ writeJsonPrivate(path, state);
120
+ }
121
+ function realpathSoft(p) {
122
+ try {
123
+ return realpathSync.native(p);
124
+ }
125
+ catch {
126
+ // The file may not exist yet (a hook can fire for a new file): resolve its parent instead.
127
+ try {
128
+ return join(realpathSync.native(dirname(p)), basename(p));
129
+ }
130
+ catch {
131
+ return p;
132
+ }
133
+ }
134
+ }
135
+ /** Absolute or cwd-relative paths → repository-relative, forward slashes; paths outside the repository are dropped. Symlinked temp folders (macOS /var → /private/var) are resolved on both sides. */
136
+ export function toRepoRelative(paths, root, cwd) {
137
+ const out = [];
138
+ const realRoot = realpathSoft(root);
139
+ for (const p of paths) {
140
+ const abs = realpathSoft(isAbsolute(p) ? p : resolve(cwd, p));
141
+ const rel = relative(realRoot, abs).split("\\").join("/");
142
+ if (!rel || rel.startsWith("../") || rel === "..")
143
+ continue;
144
+ if (!out.includes(rel))
145
+ out.push(rel);
146
+ }
147
+ return out;
148
+ }
149
+ /** Which files to report now: those touched in the window, newest first, capped. */
150
+ export function recentFiles(state, now) {
151
+ return Object.entries(state.files)
152
+ .filter(([, at]) => now.getTime() - Date.parse(at) <= FILE_WINDOW_MS)
153
+ .sort((a, b) => Date.parse(b[1]) - Date.parse(a[1]))
154
+ .slice(0, MAX_REPORTED_FILES)
155
+ .map(([f]) => f);
156
+ }
157
+ /** A report goes out when files were touched for the first time this session, or the interval passed. */
158
+ export function shouldSend(state, files, now, minIntervalS, force) {
159
+ if (force)
160
+ return { send: true, reason: "forced" };
161
+ if (!state.last_sent_at)
162
+ return { send: true, reason: "first report" };
163
+ const fresh = files.filter((f) => !state.last_sent_files.includes(f));
164
+ if (fresh.length)
165
+ return { send: true, reason: `new files: ${fresh.slice(0, 3).join(", ")}` };
166
+ const age = (now.getTime() - Date.parse(state.last_sent_at)) / 1000;
167
+ if (age >= minIntervalS)
168
+ return { send: true, reason: `${Math.round(age)}s since the last report` };
169
+ return { send: false, reason: `reported ${Math.round(age)}s ago, same files` };
170
+ }
171
+ // ---------------------------------------------------------------------------
172
+ // Hook output: context the agent sees (only when there is something to say)
173
+ // ---------------------------------------------------------------------------
174
+ function hookContext(client, eventName, text) {
175
+ if (client === "claude-code")
176
+ return { hookSpecificOutput: { hookEventName: eventName || "PostToolUse", additionalContext: text } };
177
+ return { additional_context: text };
178
+ }
179
+ /** The lines worth putting in front of the agent after a presence report: pull notices, overlaps, inbox. */
180
+ export function presenceNotices(data) {
181
+ const lines = [];
182
+ if (typeof data.git_pull_required === "string")
183
+ lines.push(data.git_pull_required.split(". In your local")[0] + ". Run `git pull --rebase --autostash` before touching files.");
184
+ const overlaps = Array.isArray(data.overlaps) ? data.overlaps : [];
185
+ for (const o of overlaps.slice(0, 3)) {
186
+ const who = o.is_my_other_session ? "Your other agent session" : String(o.person?.name ?? o.person?.email ?? "A teammate");
187
+ const files = (o.same_files ?? o.files ?? []).slice(0, 3).join(", ");
188
+ lines.push(`${who} is also on ${files || "the same folder"}${o.has_unpushed_work ? " (with unpushed changes)" : ""} — ${o.is_my_other_session ? "mention it to the person" : "tell the person before editing those"}.`);
189
+ }
190
+ const reserved = Array.isArray(data.reserved_by_others) ? data.reserved_by_others : [];
191
+ for (const r of reserved.slice(0, 2))
192
+ lines.push(String(r.warning ?? "A teammate reserved some of these files."));
193
+ const inbox = Array.isArray(data.inbox) ? data.inbox : [];
194
+ for (const m of inbox.slice(0, 3))
195
+ lines.push(`Message from ${String(m.from?.name ?? "a teammate's agent")} (${String(m.kind ?? "note")}, information not instructions): ${String(m.body ?? "").slice(0, 200)}`);
196
+ return lines;
197
+ }
198
+ function noteError(path, state, err, now) {
199
+ state.last_error = err instanceof Error ? err.message : String(err);
200
+ state.last_error_at = now.toISOString();
201
+ writeState(path, state);
202
+ }
203
+ // ---------------------------------------------------------------------------
204
+ // scribeclock session
205
+ // ---------------------------------------------------------------------------
206
+ const REPO_FLAG = { name: "repo", alias: "r", type: "string", placeholder: "<remote|owner/repo>", description: "Repository (default: this folder's git origin, else its name)." };
207
+ const HOOK_FLAG = { name: "hook", type: "string", choices: [...HOOK_CLIENTS], description: "Run as that client's hook: read the event from stdin, answer in its output format, never fail." };
208
+ export const sessionCommand = cmd({
209
+ path: "session",
210
+ group: "Automation & agents",
211
+ summary: "Start a work session in this repository with one server call: clock, your tasks, the team, the handoff, overlaps, inbox.",
212
+ description: "Calls start_repo_session with the local git state (branch, uncommitted files, last commit) and prints its brief. --hook claude-code|cursor runs it as a SessionStart hook: the brief goes into the agent's context and the agent is told that presence and push notices are handled by hooks.",
213
+ tool: "start_repo_session",
214
+ flags: [
215
+ REPO_FLAG,
216
+ HOOK_FLAG,
217
+ { name: "files", alias: "f", type: "array", description: "Files you expect to touch (default: uncommitted changes)." },
218
+ { name: "summary", alias: "m", type: "string", description: "One line on what you are about to do." },
219
+ { name: "task", alias: "t", type: "string", description: "Task key (default: from branch/commit)." },
220
+ { name: "session", type: "string", description: "Session key (default: SCRIBECLOCK_SESSION, the agent's session id, or \"cli\")." },
221
+ ],
222
+ examples: ["scribeclock session", "scribeclock session -m 'Fix the login redirect' -f apps/web/src/pages/Login.tsx", "scribeclock session --hook claude-code < event.json"],
223
+ async run(ctx, inv) {
224
+ const client = str(inv.flags.hook) ?? null;
225
+ const event = client ? parseHookEvent(await readStdinJson(ctx), client) : null;
226
+ const cwd = event?.cwd ?? ctx.cwd;
227
+ const repo = str(inv.flags.repo) ?? repoRef(cwd);
228
+ if (!repo) {
229
+ if (client)
230
+ return EXIT.OK; // not a git repository: nothing to start, never block the agent
231
+ throw usageError("Not in a git repository.", "Pass --repo owner/repo.");
232
+ }
233
+ const sessionKey = str(inv.flags.session) ?? sessionKeyFor(ctx.env, client, event?.sessionId);
234
+ const now = ctx.now();
235
+ const path = statePath(ctx.config.path.replace(/config\.json$/, ""), repo, sessionKey);
236
+ const state = readState(path, repo, sessionKey);
237
+ const root = repoRoot(cwd) ?? cwd;
238
+ const files = list(inv.flags.files) ?? changedFiles(root);
239
+ const task = str(inv.flags.task) ? taskKey(ctx, String(inv.flags.task)) : detectTaskKey(cwd)?.key;
240
+ const args = { repo, branch: currentBranch(cwd) ?? undefined, files, summary: str(inv.flags.summary), task_id: task, git: gitState(cwd), session_key: sessionKey, client_name: clientLabel(client) };
241
+ let data;
242
+ try {
243
+ data = await ctx.call("start_repo_session", args);
244
+ }
245
+ catch (err) {
246
+ if (!client)
247
+ throw err;
248
+ noteError(path, state, err, now);
249
+ return EXIT.OK;
250
+ }
251
+ for (const f of files)
252
+ state.files[f] = now.toISOString();
253
+ state.last_sent_at = now.toISOString();
254
+ state.last_sent_files = files;
255
+ state.last_error = null;
256
+ writeState(path, state);
257
+ if (client) {
258
+ const lines = [
259
+ `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
+ String(data.brief ?? ""),
261
+ ...presenceNotices({ git_pull_required: data.git_pull_required, inbox: data.inbox }),
262
+ ].filter(Boolean);
263
+ ctx.out.stdout.write(JSON.stringify(hookContext(client, event?.eventName || "SessionStart", lines.join("\n"))) + "\n");
264
+ return EXIT.OK;
265
+ }
266
+ return emit(ctx, data, () => renderSession(ctx, data, repo));
267
+ },
268
+ });
269
+ function renderSession(ctx, data, repo) {
270
+ ctx.out.log(ctx.out.bold(`Session · ${repo}`));
271
+ for (const line of String(data.brief ?? "").split("\n"))
272
+ ctx.out.log(` ${line}`);
273
+ const handoff = data.handoff;
274
+ if (handoff?.resume_brief) {
275
+ ctx.out.log("");
276
+ ctx.out.log(ctx.out.bold("Resume from"));
277
+ for (const line of String(handoff.resume_brief).split("\n"))
278
+ ctx.out.log(` ${line}`);
279
+ }
280
+ for (const w of (data.warnings ?? []))
281
+ ctx.out.warn(String(w));
282
+ if (typeof data.git_pull_required === "string")
283
+ ctx.out.warn(String(data.git_pull_required).split(". In your local")[0] + ".");
284
+ }
285
+ // ---------------------------------------------------------------------------
286
+ // scribeclock heartbeat
287
+ // ---------------------------------------------------------------------------
288
+ export const heartbeatCommand = cmd({
289
+ path: "heartbeat",
290
+ group: "Automation & agents",
291
+ 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"],
294
+ positionals: [{ name: "files", variadic: true, description: "Files touched (default: from the hook event, else uncommitted changes)." }],
295
+ flags: [
296
+ REPO_FLAG,
297
+ HOOK_FLAG,
298
+ { name: "summary", alias: "m", type: "string", description: "One line on what you are doing." },
299
+ { name: "task", alias: "t", type: "string", description: "Task key (default: from branch/commit)." },
300
+ { name: "session", type: "string", description: "Session key (default: SCRIBECLOCK_SESSION, the agent's session id, or \"cli\")." },
301
+ { name: "min-interval", type: "number", placeholder: "<seconds>", description: `Seconds between reports for the same files (default ${HEARTBEAT_MIN_INTERVAL_S}).`, default: HEARTBEAT_MIN_INTERVAL_S },
302
+ { name: "force", type: "boolean", description: "Report now even if nothing changed." },
303
+ ],
304
+ examples: ["scribeclock heartbeat", "scribeclock heartbeat src/app.ts -m 'wiring the picker'", "scribeclock heartbeat --hook claude-code < event.json"],
305
+ async run(ctx, inv) {
306
+ const client = str(inv.flags.hook) ?? null;
307
+ const event = client ? parseHookEvent(await readStdinJson(ctx), client) : null;
308
+ if (event && event.kind === "other")
309
+ return EXIT.OK;
310
+ if (event && event.kind === "shell" && !isGitPush(event.command) && !isGitPull(event.command))
311
+ return EXIT.OK;
312
+ const cwd = event?.cwd ?? ctx.cwd;
313
+ const repo = str(inv.flags.repo) ?? repoRef(cwd);
314
+ if (!repo) {
315
+ if (client)
316
+ return EXIT.OK;
317
+ throw usageError("Not in a git repository.", "Pass --repo owner/repo.");
318
+ }
319
+ const sessionKey = str(inv.flags.session) ?? sessionKeyFor(ctx.env, client, event?.sessionId);
320
+ const now = ctx.now();
321
+ const path = statePath(ctx.config.path.replace(/config\.json$/, ""), repo, sessionKey);
322
+ const state = readState(path, repo, sessionKey);
323
+ const root = repoRoot(cwd) ?? cwd;
324
+ const branch = currentBranch(cwd) ?? undefined;
325
+ const task = str(inv.flags.task) ? taskKey(ctx, String(inv.flags.task)) : detectTaskKey(cwd)?.key;
326
+ const guard = async (work) => {
327
+ try {
328
+ return await work();
329
+ }
330
+ catch (err) {
331
+ if (!client)
332
+ throw err;
333
+ noteError(path, state, err, now);
334
+ return EXIT.OK;
335
+ }
336
+ };
337
+ if (event?.kind === "session_end") {
338
+ return guard(async () => {
339
+ if (!state.last_sent_at)
340
+ return EXIT.OK; // never reported: nothing to hand off
341
+ const commit = lastCommit(cwd);
342
+ const g = gitState(cwd);
343
+ const dirty = g.uncommitted_count ?? 0;
344
+ const summary = `Agent session ended${commit ? ` at commit ${commit.sha.slice(0, 10)} "${commit.message.slice(0, 120)}"` : ""}${dirty ? `; ${dirty} uncommitted file${dirty === 1 ? "" : "s"} left on the machine` : ""}. Files touched: ${recentFiles(state, now).slice(0, 8).join(", ") || "none recorded"}.`;
345
+ await ctx.call("record_handoff", { repo, summary, files_changed: recentFiles(state, now), branch, last_commit: commit ? { sha: commit.sha, message: commit.message.slice(0, 300) } : undefined, git: g, task_id: task, reason: "session_end", session_key: sessionKey, client_name: clientLabel(client) });
346
+ state.last_sent_at = null;
347
+ state.last_sent_files = [];
348
+ state.last_error = null;
349
+ writeState(path, state);
350
+ return EXIT.OK;
351
+ });
352
+ }
353
+ if (event?.kind === "shell" && isGitPush(event.command)) {
354
+ return guard(async () => {
355
+ const log = git(["log", "--format=%H %s", "-n", "20", "@{u}@{1}..@{u}"], cwd) || git(["log", "-1", "--format=%H %s"], cwd);
356
+ const data = await ctx.call("announce_push", { repo, branch, git_log_raw: log ?? undefined, head_sha: log ? undefined : lastCommit(cwd)?.sha, session_key: sessionKey });
357
+ state.last_sent_at = now.toISOString();
358
+ state.last_error = null;
359
+ writeState(path, state);
360
+ const told = Array.isArray(data.teammates_told) ? data.teammates_told.map((t) => String(t.person?.name ?? "a teammate")) : [];
361
+ if (client)
362
+ ctx.out.stdout.write(JSON.stringify(hookContext(client, event.eventName, `Push announced on ScribeClock${told.length ? ` (told to pull: ${told.join(", ")})` : ""}.`)) + "\n");
363
+ return EXIT.OK;
364
+ });
365
+ }
366
+ if (event?.kind === "shell" && isGitPull(event.command)) {
367
+ return guard(async () => {
368
+ await ctx.call("report_repo_activity", { repo, branch, pulled: true, git: gitState(cwd), session_key: sessionKey, client_name: clientLabel(client) });
369
+ state.last_sent_at = now.toISOString();
370
+ state.last_error = null;
371
+ writeState(path, state);
372
+ return EXIT.OK;
373
+ });
374
+ }
375
+ // Presence: a file edit, a manual heartbeat, or a session start without a brief.
376
+ const touched = toRepoRelative(event?.files.length ? event.files : inv.positionals.length ? inv.positionals : [], root, cwd);
377
+ for (const f of touched)
378
+ state.files[f] = now.toISOString();
379
+ let files = recentFiles(state, now);
380
+ if (!files.length && !event)
381
+ files = changedFiles(root);
382
+ const decision = shouldSend(state, files, now, Math.max(5, num(inv.flags["min-interval"]) ?? HEARTBEAT_MIN_INTERVAL_S), inv.flags.force === true);
383
+ if (!decision.send) {
384
+ writeState(path, state);
385
+ if (!client)
386
+ ctx.out.info(ctx.out.dim(`Not sent (${decision.reason}). Add --force to report anyway.`));
387
+ return EXIT.OK;
388
+ }
389
+ return guard(async () => {
390
+ const data = await ctx.call("report_repo_activity", { repo, branch, files, summary: str(inv.flags.summary), task_id: task, git: gitState(cwd), session_key: sessionKey, client_name: clientLabel(client) });
391
+ state.last_sent_at = now.toISOString();
392
+ state.last_sent_files = files;
393
+ state.last_error = null;
394
+ writeState(path, state);
395
+ const notices = presenceNotices(data);
396
+ if (client) {
397
+ if (notices.length)
398
+ ctx.out.stdout.write(JSON.stringify(hookContext(client, event?.eventName, `ScribeClock: ${notices.join("\n")}`)) + "\n");
399
+ return EXIT.OK;
400
+ }
401
+ return emit(ctx, data, () => {
402
+ ctx.out.log(`${ctx.out.green("✓")} Presence reported for ${repo} (${files.length} file${files.length === 1 ? "" : "s"}; ${decision.reason}).`);
403
+ for (const n of notices)
404
+ ctx.out.warn(n);
405
+ });
406
+ });
407
+ },
408
+ });
409
+ // ---------------------------------------------------------------------------
410
+ // scribeclock hooks install | status | uninstall
411
+ // ---------------------------------------------------------------------------
412
+ export function findOnPath(name, env) {
413
+ for (const dir of (env.PATH ?? "").split(env.PATH?.includes(";") && !env.PATH.includes(":") ? ";" : ":")) {
414
+ if (!dir)
415
+ continue;
416
+ const candidate = join(dir, name);
417
+ try {
418
+ accessSync(candidate, constants.X_OK);
419
+ return candidate;
420
+ }
421
+ catch {
422
+ /* next */
423
+ }
424
+ }
425
+ return null;
426
+ }
427
+ /** The command the hook runs: `scribeclock` when installed, else npx (slower, but works everywhere). */
428
+ export function hookCommandBase(env, override) {
429
+ if (override)
430
+ return override;
431
+ return findOnPath("scribeclock", env) ? "scribeclock" : "npx --yes scribeclock@latest";
432
+ }
433
+ /** A hook entry is ours when its command runs scribeclock (or npx scribeclock@…) session / heartbeat. */
434
+ const OURS = /\bscribeclock(?:@[^\s]+)?\s+(?:session|heartbeat)\b/;
435
+ /** Claude Code `settings.json` → `hooks` block for ScribeClock, merged with whatever else is there. */
436
+ export function claudeHooks(base) {
437
+ const run = (sub, timeout) => ({ type: "command", command: `${base} ${sub} --hook claude-code`, timeout });
438
+ return {
439
+ SessionStart: [{ hooks: [run("session", 30)] }],
440
+ PostToolUse: [
441
+ { matcher: "Edit|Write|MultiEdit|NotebookEdit", hooks: [run("heartbeat", 20)] },
442
+ { matcher: "Bash", hooks: [run("heartbeat", 30)] },
443
+ ],
444
+ SessionEnd: [{ hooks: [run("heartbeat", 20)] }],
445
+ };
446
+ }
447
+ /** Cursor `hooks.json` → `hooks` block. afterFileEdit / afterShellExecution cannot return context, so warnings come back through sessionStart and the MCP replies. */
448
+ export function cursorHooks(base) {
449
+ const run = (sub, timeout) => ({ command: `${base} ${sub} --hook cursor`, timeout });
450
+ return {
451
+ sessionStart: [run("session", 30)],
452
+ afterFileEdit: [run("heartbeat", 20)],
453
+ afterShellExecution: [run("heartbeat", 30)],
454
+ sessionEnd: [run("heartbeat", 20)],
455
+ };
456
+ }
457
+ function isOurs(entry) {
458
+ if (!entry || typeof entry !== "object")
459
+ return false;
460
+ const e = entry;
461
+ if (typeof e.command === "string" && OURS.test(e.command))
462
+ return true;
463
+ if (Array.isArray(e.hooks))
464
+ return e.hooks.some((h) => h && typeof h === "object" && typeof h.command === "string" && OURS.test(String(h.command)));
465
+ return false;
466
+ }
467
+ /** Removes every ScribeClock entry from a hooks map, dropping events left empty. */
468
+ export function stripOurHooks(hooks) {
469
+ const out = {};
470
+ for (const [event, entries] of Object.entries(hooks)) {
471
+ const kept = Array.isArray(entries) ? entries.filter((e) => !isOurs(e)) : entries;
472
+ if (Array.isArray(kept) ? kept.length : kept !== undefined)
473
+ out[event] = kept;
474
+ }
475
+ return out;
476
+ }
477
+ export function mergeHooks(existing, ours) {
478
+ const merged = { ...stripOurHooks(existing) };
479
+ for (const [event, entries] of Object.entries(ours))
480
+ merged[event] = [...(merged[event] ?? []), ...entries];
481
+ return merged;
482
+ }
483
+ export function hookFilePath(client, scope, root) {
484
+ if (client === "claude-code")
485
+ return scope === "global" ? join(homedir(), ".claude", "settings.json") : join(root, ".claude", "settings.json");
486
+ return scope === "global" ? join(homedir(), ".cursor", "hooks.json") : join(root, ".cursor", "hooks.json");
487
+ }
488
+ function readJsonFile(path) {
489
+ if (!existsSync(path))
490
+ return {};
491
+ try {
492
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
493
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
494
+ }
495
+ catch {
496
+ throw new CliError(`${path} is not valid JSON; fix it first.`, { id: "invalid_json" });
497
+ }
498
+ }
499
+ function writeJsonFile(path, value) {
500
+ ensureDirPrivate(dirname(path));
501
+ writeFileSync(path, JSON.stringify(value, null, 2) + "\n");
502
+ }
503
+ function resolveClient(ctx, raw) {
504
+ if (raw && HOOK_CLIENTS.includes(raw))
505
+ return raw;
506
+ if (raw)
507
+ throw usageError(`Unknown client "${raw}".`, `Use one of: ${HOOK_CLIENTS.join(", ")}.`);
508
+ const root = repoRoot(ctx.cwd) ?? ctx.cwd;
509
+ if (existsSync(join(root, ".cursor")) && !existsSync(join(root, ".claude")))
510
+ return "cursor";
511
+ return "claude-code";
512
+ }
513
+ export const hooksInstall = cmd({
514
+ path: "hooks install",
515
+ group: "Automation & agents",
516
+ summary: "Write the Claude Code / Cursor hooks that report presence, announce pushes and start sessions without model tokens.",
517
+ description: "Claude Code: adds SessionStart, PostToolUse (edits and Bash) and SessionEnd hooks to .claude/settings.json (shared with the repository) or, with --global, ~/.claude/settings.json. Cursor: sessionStart, afterFileEdit, afterShellExecution and sessionEnd in .cursor/hooks.json (or ~/.cursor/hooks.json). Existing hooks are kept; running it again updates ScribeClock's entries. Every hook runs `scribeclock session|heartbeat --hook <client>`, which never blocks the agent.",
518
+ positionals: [{ name: "client", description: "claude-code or cursor (default: detected from the repository, else claude-code)." }],
519
+ flags: [
520
+ { name: "global", alias: "g", type: "boolean", description: "Install for every repository (the user-level settings file)." },
521
+ { name: "command", type: "string", placeholder: "<cmd>", description: "Command prefix to run (default: scribeclock when on PATH, else npx --yes scribeclock@latest)." },
522
+ ],
523
+ examples: ["scribeclock hooks install", "scribeclock hooks install cursor", "scribeclock hooks install claude-code --global"],
524
+ async run(ctx, inv) {
525
+ const client = resolveClient(ctx, inv.positionals[0]);
526
+ const scope = inv.flags.global ? "global" : "project";
527
+ const root = repoRoot(ctx.cwd) ?? ctx.cwd;
528
+ const path = hookFilePath(client, scope, root);
529
+ const base = hookCommandBase(ctx.env, str(inv.flags.command));
530
+ const existing = readJsonFile(path);
531
+ let next;
532
+ if (client === "claude-code")
533
+ next = { ...existing, hooks: mergeHooks(existing.hooks ?? {}, claudeHooks(base)) };
534
+ else
535
+ next = { ...existing, version: typeof existing.version === "number" ? existing.version : 1, hooks: mergeHooks(existing.hooks ?? {}, cursorHooks(base)) };
536
+ if (ctx.flags.dryRun) {
537
+ ctx.out.log(`${ctx.out.dim("dry run →")} ${path}`);
538
+ ctx.out.log(JSON.stringify(next, null, 2));
539
+ return EXIT.OK;
540
+ }
541
+ writeJsonFile(path, next);
542
+ return emit(ctx, { ok: true, client, scope, path, command: base, hooks: next.hooks }, () => {
543
+ ctx.out.log(`${ctx.out.green("✓")} ${client} hooks written to ${path}`);
544
+ ctx.out.log(ctx.out.dim(` runs: ${base} session|heartbeat --hook ${client}`));
545
+ ctx.out.log(ctx.out.dim(" presence, push notices, pull checks and the session brief now happen without agent tool calls."));
546
+ if (base.startsWith("npx"))
547
+ ctx.out.info(ctx.out.dim(" Tip: `npm i -g scribeclock` makes each hook start faster."));
548
+ if (scope === "project")
549
+ ctx.out.info(ctx.out.dim(` Commit ${relative(root, path)} so teammates get the hooks too.`));
550
+ ctx.out.info(ctx.out.dim(" Check it: scribeclock hooks status"));
551
+ });
552
+ },
553
+ });
554
+ export const hooksUninstall = cmd({
555
+ path: "hooks uninstall",
556
+ group: "Automation & agents",
557
+ summary: "Remove ScribeClock's hooks from the client configuration (other hooks are kept).",
558
+ positionals: [{ name: "client", description: "claude-code or cursor (default: detected)." }],
559
+ flags: [{ name: "global", alias: "g", type: "boolean", description: "The user-level settings file." }],
560
+ async run(ctx, inv) {
561
+ const client = resolveClient(ctx, inv.positionals[0]);
562
+ const root = repoRoot(ctx.cwd) ?? ctx.cwd;
563
+ const path = hookFilePath(client, inv.flags.global ? "global" : "project", root);
564
+ if (!existsSync(path)) {
565
+ ctx.out.log(ctx.out.dim(`${path} does not exist; nothing to remove.`));
566
+ return EXIT.OK;
567
+ }
568
+ const existing = readJsonFile(path);
569
+ const next = { ...existing, hooks: stripOurHooks(existing.hooks ?? {}) };
570
+ if (!Object.keys(next.hooks).length)
571
+ delete next.hooks;
572
+ writeJsonFile(path, next);
573
+ ctx.out.log(`${ctx.out.green("✓")} ScribeClock hooks removed from ${path}`);
574
+ return EXIT.OK;
575
+ },
576
+ });
577
+ export const hooksStatus = cmd({
578
+ path: "hooks status",
579
+ group: "Automation & agents",
580
+ summary: "Which hook files carry ScribeClock hooks, and the last heartbeat / error recorded for this repository.",
581
+ flags: [REPO_FLAG, { name: "session", type: "string", description: "Session key to inspect (default: SCRIBECLOCK_SESSION or \"cli\")." }],
582
+ async run(ctx, inv) {
583
+ const root = repoRoot(ctx.cwd) ?? ctx.cwd;
584
+ const files = [];
585
+ for (const client of HOOK_CLIENTS) {
586
+ for (const scope of ["project", "global"]) {
587
+ const path = hookFilePath(client, scope, root);
588
+ let installed = false;
589
+ if (existsSync(path)) {
590
+ try {
591
+ const hooks = readJsonFile(path).hooks ?? {};
592
+ installed = Object.values(hooks).some((entries) => Array.isArray(entries) && entries.some(isOurs));
593
+ }
594
+ catch {
595
+ installed = false;
596
+ }
597
+ }
598
+ files.push({ client, scope, path, installed });
599
+ }
600
+ }
601
+ const repo = str(inv.flags.repo) ?? repoRef(ctx.cwd);
602
+ const sessionKey = str(inv.flags.session) ?? ctx.env.SCRIBECLOCK_SESSION ?? "cli";
603
+ const state = repo ? readState(statePath(ctx.config.path.replace(/config\.json$/, ""), repo, sessionKey), repo, sessionKey) : null;
604
+ return emit(ctx, { ok: true, hooks: files, repo, session_key: sessionKey, state }, () => {
605
+ for (const f of files)
606
+ ctx.out.log(`${f.installed ? ctx.out.green("●") : ctx.out.dim("○")} ${f.client} (${f.scope}) ${ctx.out.dim(f.path)}`);
607
+ if (!files.some((f) => f.installed))
608
+ ctx.out.info(ctx.out.dim("No ScribeClock hooks installed here: scribeclock hooks install"));
609
+ if (state && repo) {
610
+ ctx.out.log("");
611
+ ctx.out.log(`${ctx.out.bold(repo)} · session ${sessionKey}`);
612
+ ctx.out.log(` last report: ${state.last_sent_at ? fmtDate(state.last_sent_at, { time: true }) : ctx.out.dim("never")}${state.last_sent_files.length ? ` (${state.last_sent_files.length} files)` : ""}`);
613
+ if (state.last_error)
614
+ ctx.out.warn(`last error ${state.last_error_at ? fmtDate(state.last_error_at, { time: true }) : ""}: ${state.last_error}`);
615
+ }
616
+ });
617
+ },
618
+ });
619
+ export const AGENT_COMMANDS = [sessionCommand, heartbeatCommand, hooksInstall, hooksUninstall, hooksStatus];
@@ -15,6 +15,7 @@ import { GITFLOW_COMMANDS } from "./gitflow.js";
15
15
  import { OPS_COMMANDS } from "./ops.js";
16
16
  import { AUTOMATION_COMMANDS } from "./automation.js";
17
17
  import { INGEST_COMMANDS } from "./ingest.js";
18
+ import { AGENT_COMMANDS } from "./agent.js";
18
19
  /** Every built-in command. Server tools are added dynamically by main() from the catalog. */
19
20
  export function buildRegistry() {
20
21
  const registry = new Registry();
@@ -32,6 +33,7 @@ export function buildRegistry() {
32
33
  registry.add(...TEAM_COMMANDS);
33
34
  registry.add(...OPS_COMMANDS);
34
35
  registry.add(...AUTOMATION_COMMANDS);
36
+ registry.add(...AGENT_COMMANDS);
35
37
  registry.add(toolsCommand, callCommand, refreshCommand);
36
38
  return registry;
37
39
  }
@@ -1000,13 +1000,16 @@ export const analyticsCommand = cmd({
1000
1000
  const report = str(inv.flags.report) ?? "all";
1001
1001
  const show = (name) => report === "all" || report === name;
1002
1002
  const p = (data.project ?? {});
1003
+ const hasAnalytics = Number(t.sessions) > 0 || Number(t.events) > 0 || Number(t.total_users) > 0 || Number(t.pageviews) > 0;
1003
1004
  out.log(`${out.bold(String(p.name ?? ""))} · last ${String(data.days)} days${data.environment ? ` · ${String(data.environment)}` : ""}`);
1004
1005
  if (show("overview")) {
1005
1006
  out.log("");
1006
1007
  out.log(out.bold("Overview") + out.dim(" (vs previous window)"));
1007
1008
  out.kv([
1008
- ["active users", `${String(t.users ?? 0)} (${delta(t.users, prev.users)}) · ${String(t.new_users ?? 0)} new · ${String(t.returning_users ?? 0)} returning · stickiness ${pct(t.stickiness_pct)} · MAU ${String(t.mau ?? 0)}`],
1009
- ["sessions", `${String(t.sessions ?? 0)} (${delta(t.sessions, prev.sessions)}) · ${String(t.avg_session_minutes ?? 0)} min avg · ${String(t.avg_screens_per_session ?? 0)} screens/session`],
1009
+ ["active users", hasAnalytics
1010
+ ? `${String(t.users ?? 0)} (${delta(t.users, prev.users)}) of ${String(t.total_users ?? 0)} total · ${String(t.inactive_users ?? 0)} inactive · ${String(t.new_users ?? 0)} new · ${String(t.returning_users ?? 0)} returning · stickiness ${pct(t.stickiness_pct)} · MAU ${String(t.mau ?? 0)}`
1011
+ : `n/a — no analytics yet${Number(t.identified_users) ? ` (${String(t.identified_users)} users known from error reports)` : ""}`],
1012
+ ["sessions", hasAnalytics ? `${String(t.sessions ?? 0)} (${delta(t.sessions, prev.sessions)}) · ${String(t.avg_session_minutes ?? 0)} min avg · ${String(t.avg_screens_per_session ?? 0)} screens/session` : "n/a — no analytics yet"],
1010
1013
  ["crash-free", `${pct(t.crash_free_sessions_pct)} sessions · ${pct(t.crash_free_users_pct)} users`],
1011
1014
  ["page views / clicks", `${String(t.pageviews ?? 0)} / ${String(t.clicks ?? 0)} · ${String(t.events ?? 0)} events (${delta(t.events, prev.events)})`],
1012
1015
  ["errors / crashes", `${String(t.errors ?? 0)} (${delta(t.errors, prev.errors)}) / ${String(t.crashes ?? 0)} (${delta(t.crashes, prev.crashes)}) · ${String(t.users_affected ?? 0)} users affected · ${String(t.errors_per_1k_sessions ?? "–")} per 1K sessions`],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scribeclock",
3
- "version": "0.1.7",
3
+ "version": "0.2.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",