offwatch 0.5.8 → 0.5.10

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.
Files changed (94) hide show
  1. package/bin/offwatch.js +7 -6
  2. package/package.json +4 -3
  3. package/src/__tests__/agent-jwt-env.test.ts +79 -0
  4. package/src/__tests__/allowed-hostname.test.ts +80 -0
  5. package/src/__tests__/auth-command-registration.test.ts +16 -0
  6. package/src/__tests__/board-auth.test.ts +53 -0
  7. package/src/__tests__/common.test.ts +98 -0
  8. package/src/__tests__/company-delete.test.ts +95 -0
  9. package/src/__tests__/company-import-export-e2e.test.ts +502 -0
  10. package/src/__tests__/company-import-url.test.ts +74 -0
  11. package/src/__tests__/company-import-zip.test.ts +44 -0
  12. package/src/__tests__/company.test.ts +599 -0
  13. package/src/__tests__/context.test.ts +70 -0
  14. package/src/__tests__/data-dir.test.ts +79 -0
  15. package/src/__tests__/doctor.test.ts +102 -0
  16. package/src/__tests__/feedback.test.ts +177 -0
  17. package/src/__tests__/helpers/embedded-postgres.ts +6 -0
  18. package/src/__tests__/helpers/zip.ts +87 -0
  19. package/src/__tests__/home-paths.test.ts +44 -0
  20. package/src/__tests__/http.test.ts +106 -0
  21. package/src/__tests__/network-bind.test.ts +62 -0
  22. package/src/__tests__/onboard.test.ts +166 -0
  23. package/src/__tests__/routines.test.ts +249 -0
  24. package/src/__tests__/telemetry.test.ts +117 -0
  25. package/src/__tests__/worktree-merge-history.test.ts +492 -0
  26. package/src/__tests__/worktree.test.ts +982 -0
  27. package/src/adapters/http/format-event.ts +4 -0
  28. package/src/adapters/http/index.ts +7 -0
  29. package/src/adapters/index.ts +2 -0
  30. package/src/adapters/process/format-event.ts +4 -0
  31. package/src/adapters/process/index.ts +7 -0
  32. package/src/adapters/registry.ts +63 -0
  33. package/src/checks/agent-jwt-secret-check.ts +40 -0
  34. package/src/checks/config-check.ts +33 -0
  35. package/src/checks/database-check.ts +59 -0
  36. package/src/checks/deployment-auth-check.ts +88 -0
  37. package/src/checks/index.ts +18 -0
  38. package/src/checks/llm-check.ts +82 -0
  39. package/src/checks/log-check.ts +30 -0
  40. package/src/checks/path-resolver.ts +1 -0
  41. package/src/checks/port-check.ts +24 -0
  42. package/src/checks/secrets-check.ts +146 -0
  43. package/src/checks/storage-check.ts +51 -0
  44. package/src/client/board-auth.ts +282 -0
  45. package/src/client/command-label.ts +4 -0
  46. package/src/client/context.ts +175 -0
  47. package/src/client/http.ts +255 -0
  48. package/src/commands/allowed-hostname.ts +40 -0
  49. package/src/commands/auth-bootstrap-ceo.ts +138 -0
  50. package/src/commands/client/activity.ts +71 -0
  51. package/src/commands/client/agent.ts +315 -0
  52. package/src/commands/client/approval.ts +259 -0
  53. package/src/commands/client/auth.ts +113 -0
  54. package/src/commands/client/common.ts +221 -0
  55. package/src/commands/client/company.ts +1578 -0
  56. package/src/commands/client/context.ts +125 -0
  57. package/src/commands/client/dashboard.ts +34 -0
  58. package/src/commands/client/feedback.ts +645 -0
  59. package/src/commands/client/issue.ts +411 -0
  60. package/src/commands/client/plugin.ts +374 -0
  61. package/src/commands/client/zip.ts +129 -0
  62. package/src/commands/configure.ts +201 -0
  63. package/src/commands/db-backup.ts +102 -0
  64. package/src/commands/doctor.ts +203 -0
  65. package/src/commands/env.ts +411 -0
  66. package/src/commands/heartbeat-run.ts +344 -0
  67. package/src/commands/onboard.ts +692 -0
  68. package/src/commands/routines.ts +352 -0
  69. package/src/commands/run.ts +216 -0
  70. package/src/commands/worktree-lib.ts +279 -0
  71. package/src/commands/worktree-merge-history-lib.ts +764 -0
  72. package/src/commands/worktree.ts +2876 -0
  73. package/src/config/data-dir.ts +48 -0
  74. package/src/config/env.ts +125 -0
  75. package/src/config/home.ts +80 -0
  76. package/src/config/hostnames.ts +26 -0
  77. package/src/config/schema.ts +30 -0
  78. package/src/config/secrets-key.ts +48 -0
  79. package/src/config/server-bind.ts +183 -0
  80. package/src/config/store.ts +120 -0
  81. package/src/index.ts +182 -0
  82. package/src/prompts/database.ts +157 -0
  83. package/src/prompts/llm.ts +43 -0
  84. package/src/prompts/logging.ts +37 -0
  85. package/src/prompts/secrets.ts +99 -0
  86. package/src/prompts/server.ts +221 -0
  87. package/src/prompts/storage.ts +146 -0
  88. package/src/telemetry.ts +49 -0
  89. package/src/utils/banner.ts +24 -0
  90. package/src/utils/net.ts +18 -0
  91. package/src/utils/path-resolver.ts +25 -0
  92. package/src/version.ts +10 -0
  93. package/lib/downloader.js +0 -112
  94. package/postinstall.js +0 -23
@@ -0,0 +1,645 @@
1
+ import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import pc from "picocolors";
4
+ import { Command } from "commander";
5
+ import type { Company, FeedbackTrace, FeedbackTraceBundle } from "@paperclipai/shared";
6
+ import {
7
+ addCommonClientOptions,
8
+ handleCommandError,
9
+ printOutput,
10
+ resolveCommandContext,
11
+ type BaseClientOptions,
12
+ type ResolvedClientContext,
13
+ } from "./common.js";
14
+
15
+ interface FeedbackFilterOptions extends BaseClientOptions {
16
+ targetType?: string;
17
+ vote?: string;
18
+ status?: string;
19
+ projectId?: string;
20
+ issueId?: string;
21
+ from?: string;
22
+ to?: string;
23
+ sharedOnly?: boolean;
24
+ }
25
+
26
+ export interface FeedbackTraceQueryOptions {
27
+ targetType?: string;
28
+ vote?: string;
29
+ status?: string;
30
+ projectId?: string;
31
+ issueId?: string;
32
+ from?: string;
33
+ to?: string;
34
+ sharedOnly?: boolean;
35
+ }
36
+
37
+ interface FeedbackReportOptions extends FeedbackFilterOptions {
38
+ payloads?: boolean;
39
+ }
40
+
41
+ interface FeedbackExportOptions extends FeedbackFilterOptions {
42
+ out?: string;
43
+ }
44
+
45
+ interface FeedbackSummary {
46
+ total: number;
47
+ thumbsUp: number;
48
+ thumbsDown: number;
49
+ withReason: number;
50
+ statuses: Record<string, number>;
51
+ }
52
+
53
+ interface FeedbackExportManifest {
54
+ exportedAt: string;
55
+ serverUrl: string;
56
+ companyId: string;
57
+ summary: FeedbackSummary & {
58
+ uniqueIssues: number;
59
+ issues: string[];
60
+ };
61
+ files: {
62
+ votes: string[];
63
+ traces: string[];
64
+ fullTraces: string[];
65
+ zip: string;
66
+ };
67
+ }
68
+
69
+ interface FeedbackExportResult {
70
+ outputDir: string;
71
+ zipPath: string;
72
+ manifest: FeedbackExportManifest;
73
+ }
74
+
75
+ export function registerFeedbackCommands(program: Command): void {
76
+ const feedback = program.command("feedback").description("Inspect and export local feedback traces");
77
+
78
+ addCommonClientOptions(
79
+ feedback
80
+ .command("report")
81
+ .description("Render a terminal report for company feedback traces")
82
+ .option("-C, --company-id <id>", "Company ID (overrides context default)")
83
+ .option("--target-type <type>", "Filter by target type")
84
+ .option("--vote <vote>", "Filter by vote value")
85
+ .option("--status <status>", "Filter by trace status")
86
+ .option("--project-id <id>", "Filter by project ID")
87
+ .option("--issue-id <id>", "Filter by issue ID")
88
+ .option("--from <iso8601>", "Only include traces created at or after this timestamp")
89
+ .option("--to <iso8601>", "Only include traces created at or before this timestamp")
90
+ .option("--shared-only", "Only include traces eligible for sharing/export")
91
+ .option("--payloads", "Include raw payload dumps in the terminal report", false)
92
+ .action(async (opts: FeedbackReportOptions) => {
93
+ try {
94
+ const ctx = resolveCommandContext(opts);
95
+ const companyId = await resolveFeedbackCompanyId(ctx, opts.companyId);
96
+ const traces = await fetchCompanyFeedbackTraces(ctx, companyId, opts);
97
+ const summary = summarizeFeedbackTraces(traces);
98
+ if (ctx.json) {
99
+ printOutput(
100
+ {
101
+ apiBase: ctx.api.apiBase,
102
+ companyId,
103
+ summary,
104
+ traces,
105
+ },
106
+ { json: true },
107
+ );
108
+ return;
109
+ }
110
+ console.log(renderFeedbackReport({
111
+ apiBase: ctx.api.apiBase,
112
+ companyId,
113
+ traces,
114
+ summary,
115
+ includePayloads: Boolean(opts.payloads),
116
+ }));
117
+ } catch (err) {
118
+ handleCommandError(err);
119
+ }
120
+ }),
121
+ { includeCompany: false },
122
+ );
123
+
124
+ addCommonClientOptions(
125
+ feedback
126
+ .command("export")
127
+ .description("Export feedback votes and raw trace bundles into a folder plus zip archive")
128
+ .option("-C, --company-id <id>", "Company ID (overrides context default)")
129
+ .option("--target-type <type>", "Filter by target type")
130
+ .option("--vote <vote>", "Filter by vote value")
131
+ .option("--status <status>", "Filter by trace status")
132
+ .option("--project-id <id>", "Filter by project ID")
133
+ .option("--issue-id <id>", "Filter by issue ID")
134
+ .option("--from <iso8601>", "Only include traces created at or after this timestamp")
135
+ .option("--to <iso8601>", "Only include traces created at or before this timestamp")
136
+ .option("--shared-only", "Only include traces eligible for sharing/export")
137
+ .option("--out <path>", "Output directory (default: ./feedback-export-<timestamp>)")
138
+ .action(async (opts: FeedbackExportOptions) => {
139
+ try {
140
+ const ctx = resolveCommandContext(opts);
141
+ const companyId = await resolveFeedbackCompanyId(ctx, opts.companyId);
142
+ const traces = await fetchCompanyFeedbackTraces(ctx, companyId, opts);
143
+ const outputDir = path.resolve(opts.out?.trim() || defaultFeedbackExportDirName());
144
+ const exported = await writeFeedbackExportBundle({
145
+ apiBase: ctx.api.apiBase,
146
+ companyId,
147
+ traces,
148
+ outputDir,
149
+ traceBundleFetcher: (trace) => fetchFeedbackTraceBundle(ctx, trace.id),
150
+ });
151
+ if (ctx.json) {
152
+ printOutput(
153
+ {
154
+ companyId,
155
+ outputDir: exported.outputDir,
156
+ zipPath: exported.zipPath,
157
+ summary: exported.manifest.summary,
158
+ },
159
+ { json: true },
160
+ );
161
+ return;
162
+ }
163
+ console.log(renderFeedbackExportSummary(exported));
164
+ } catch (err) {
165
+ handleCommandError(err);
166
+ }
167
+ }),
168
+ { includeCompany: false },
169
+ );
170
+ }
171
+
172
+ export async function resolveFeedbackCompanyId(
173
+ ctx: ResolvedClientContext,
174
+ explicitCompanyId?: string,
175
+ ): Promise<string> {
176
+ const direct = explicitCompanyId?.trim() || ctx.companyId?.trim();
177
+ if (direct) return direct;
178
+ const companies = (await ctx.api.get<Company[]>("/api/companies")) ?? [];
179
+ const companyId = companies[0]?.id?.trim();
180
+ if (!companyId) {
181
+ throw new Error(
182
+ "Company ID is required. Pass --company-id, set PAPERCLIP_COMPANY_ID, or configure a CLI context default.",
183
+ );
184
+ }
185
+ return companyId;
186
+ }
187
+
188
+ export function buildFeedbackTraceQuery(opts: FeedbackTraceQueryOptions, includePayload = true): string {
189
+ const params = new URLSearchParams();
190
+ if (opts.targetType) params.set("targetType", opts.targetType);
191
+ if (opts.vote) params.set("vote", opts.vote);
192
+ if (opts.status) params.set("status", opts.status);
193
+ if (opts.projectId) params.set("projectId", opts.projectId);
194
+ if (opts.issueId) params.set("issueId", opts.issueId);
195
+ if (opts.from) params.set("from", opts.from);
196
+ if (opts.to) params.set("to", opts.to);
197
+ if (opts.sharedOnly) params.set("sharedOnly", "true");
198
+ if (includePayload) params.set("includePayload", "true");
199
+ const query = params.toString();
200
+ return query ? `?${query}` : "";
201
+ }
202
+
203
+ export function normalizeFeedbackTraceExportFormat(value: string | undefined): "json" | "ndjson" {
204
+ if (!value || value === "ndjson") return "ndjson";
205
+ if (value === "json") return "json";
206
+ throw new Error(`Unsupported export format: ${value}`);
207
+ }
208
+
209
+ export function serializeFeedbackTraces(traces: FeedbackTrace[], format: string | undefined): string {
210
+ if (normalizeFeedbackTraceExportFormat(format) === "json") {
211
+ return JSON.stringify(traces, null, 2);
212
+ }
213
+ return traces.map((trace) => JSON.stringify(trace)).join("\n");
214
+ }
215
+
216
+ export async function fetchCompanyFeedbackTraces(
217
+ ctx: ResolvedClientContext,
218
+ companyId: string,
219
+ opts: FeedbackFilterOptions,
220
+ ): Promise<FeedbackTrace[]> {
221
+ return (
222
+ (await ctx.api.get<FeedbackTrace[]>(
223
+ `/api/companies/${companyId}/feedback-traces${buildFeedbackTraceQuery(opts, true)}`,
224
+ )) ?? []
225
+ );
226
+ }
227
+
228
+ export async function fetchFeedbackTraceBundle(
229
+ ctx: ResolvedClientContext,
230
+ traceId: string,
231
+ ): Promise<FeedbackTraceBundle> {
232
+ const bundle = await ctx.api.get<FeedbackTraceBundle>(`/api/feedback-traces/${traceId}/bundle`);
233
+ if (!bundle) {
234
+ throw new Error(`Feedback trace bundle ${traceId} not found`);
235
+ }
236
+ return bundle;
237
+ }
238
+
239
+ export function summarizeFeedbackTraces(traces: FeedbackTrace[]): FeedbackSummary {
240
+ const statuses: Record<string, number> = {};
241
+ let thumbsUp = 0;
242
+ let thumbsDown = 0;
243
+ let withReason = 0;
244
+
245
+ for (const trace of traces) {
246
+ if (trace.vote === "up") thumbsUp += 1;
247
+ if (trace.vote === "down") thumbsDown += 1;
248
+ if (readFeedbackReason(trace)) withReason += 1;
249
+ statuses[trace.status] = (statuses[trace.status] ?? 0) + 1;
250
+ }
251
+
252
+ return {
253
+ total: traces.length,
254
+ thumbsUp,
255
+ thumbsDown,
256
+ withReason,
257
+ statuses,
258
+ };
259
+ }
260
+
261
+ export function renderFeedbackReport(input: {
262
+ apiBase: string;
263
+ companyId: string;
264
+ traces: FeedbackTrace[];
265
+ summary: FeedbackSummary;
266
+ includePayloads: boolean;
267
+ }): string {
268
+ const lines: string[] = [];
269
+ lines.push("");
270
+ lines.push(pc.bold(pc.magenta("Paperclip Feedback Report")));
271
+ lines.push(pc.dim(new Date().toISOString()));
272
+ lines.push(horizontalRule());
273
+ lines.push(`${pc.dim("Server:")} ${input.apiBase}`);
274
+ lines.push(`${pc.dim("Company:")} ${input.companyId}`);
275
+ lines.push("");
276
+
277
+ if (input.traces.length === 0) {
278
+ lines.push(pc.yellow("[!!] No feedback traces found."));
279
+ lines.push("");
280
+ return lines.join("\n");
281
+ }
282
+
283
+ lines.push(pc.bold(pc.cyan("Summary")));
284
+ lines.push(horizontalRule());
285
+ lines.push(` ${pc.green(pc.bold(String(input.summary.thumbsUp)))} thumbs up`);
286
+ lines.push(` ${pc.red(pc.bold(String(input.summary.thumbsDown)))} thumbs down`);
287
+ lines.push(` ${pc.yellow(pc.bold(String(input.summary.withReason)))} downvotes with a reason`);
288
+ lines.push(` ${pc.bold(String(input.summary.total))} total traces`);
289
+ lines.push("");
290
+ lines.push(pc.dim("Export status:"));
291
+ for (const status of ["pending", "sent", "local_only", "failed"]) {
292
+ lines.push(` ${padRight(status, 10)} ${input.summary.statuses[status] ?? 0}`);
293
+ }
294
+ lines.push("");
295
+ lines.push(pc.bold(pc.cyan("Trace Details")));
296
+ lines.push(horizontalRule());
297
+
298
+ for (const trace of input.traces) {
299
+ const voteColor = trace.vote === "up" ? pc.green : pc.red;
300
+ const voteIcon = trace.vote === "up" ? "^" : "v";
301
+ const issueRef = trace.issueIdentifier ?? trace.issueId;
302
+ const label = trace.targetSummary.label?.trim() || trace.targetType;
303
+ const excerpt = compactText(trace.targetSummary.excerpt);
304
+ const reason = readFeedbackReason(trace);
305
+ lines.push(
306
+ ` ${voteColor(voteIcon)} ${pc.bold(issueRef)} ${pc.dim(compactText(trace.issueTitle, 64))}`,
307
+ );
308
+ lines.push(
309
+ ` ${pc.dim("Trace:")} ${trace.id.slice(0, 8)} ${pc.dim("Status:")} ${trace.status} ${pc.dim("Date:")} ${formatTimestamp(trace.createdAt)}`,
310
+ );
311
+ lines.push(` ${pc.dim("Target:")} ${label}`);
312
+ if (excerpt) {
313
+ lines.push(` ${pc.dim("Excerpt:")} ${excerpt}`);
314
+ }
315
+ if (reason) {
316
+ lines.push(` ${pc.yellow(pc.bold("Reason:"))} ${pc.yellow(reason)}`);
317
+ }
318
+ lines.push("");
319
+ }
320
+
321
+ if (input.includePayloads) {
322
+ lines.push(pc.bold(pc.cyan("Raw Payloads")));
323
+ lines.push(horizontalRule());
324
+ for (const trace of input.traces) {
325
+ if (!trace.payloadSnapshot) continue;
326
+ const issueRef = trace.issueIdentifier ?? trace.issueId;
327
+ lines.push(` ${pc.bold(`${issueRef} (${trace.id.slice(0, 8)})`)}`);
328
+ const body = JSON.stringify(trace.payloadSnapshot, null, 2)?.split("\n") ?? [];
329
+ for (const line of body) {
330
+ lines.push(` ${pc.dim(line)}`);
331
+ }
332
+ lines.push("");
333
+ }
334
+ }
335
+
336
+ lines.push(horizontalRule());
337
+ lines.push(pc.dim(`Report complete. ${input.traces.length} trace(s) displayed.`));
338
+ lines.push("");
339
+ return lines.join("\n");
340
+ }
341
+
342
+ export async function writeFeedbackExportBundle(input: {
343
+ apiBase: string;
344
+ companyId: string;
345
+ traces: FeedbackTrace[];
346
+ outputDir: string;
347
+ traceBundleFetcher?: (trace: FeedbackTrace) => Promise<FeedbackTraceBundle>;
348
+ }): Promise<FeedbackExportResult> {
349
+ await ensureEmptyOutputDirectory(input.outputDir);
350
+ await mkdir(path.join(input.outputDir, "votes"), { recursive: true });
351
+ await mkdir(path.join(input.outputDir, "traces"), { recursive: true });
352
+ await mkdir(path.join(input.outputDir, "full-traces"), { recursive: true });
353
+
354
+ const summary = summarizeFeedbackTraces(input.traces);
355
+ const voteFiles: string[] = [];
356
+ const traceFiles: string[] = [];
357
+ const fullTraceDirs: string[] = [];
358
+ const fullTraceFiles: string[] = [];
359
+ const issueSet = new Set<string>();
360
+
361
+ for (const trace of input.traces) {
362
+ const issueRef = sanitizeFileSegment(trace.issueIdentifier ?? trace.issueId);
363
+ const voteRecord = buildFeedbackVoteRecord(trace);
364
+ const voteFileName = `${issueRef}-${trace.feedbackVoteId.slice(0, 8)}.json`;
365
+ const traceFileName = `${issueRef}-${trace.id.slice(0, 8)}.json`;
366
+ voteFiles.push(voteFileName);
367
+ traceFiles.push(traceFileName);
368
+ issueSet.add(trace.issueIdentifier ?? trace.issueId);
369
+ await writeFile(
370
+ path.join(input.outputDir, "votes", voteFileName),
371
+ `${JSON.stringify(voteRecord, null, 2)}\n`,
372
+ "utf8",
373
+ );
374
+ await writeFile(
375
+ path.join(input.outputDir, "traces", traceFileName),
376
+ `${JSON.stringify(trace, null, 2)}\n`,
377
+ "utf8",
378
+ );
379
+
380
+ if (input.traceBundleFetcher) {
381
+ const bundle = await input.traceBundleFetcher(trace);
382
+ const bundleDirName = `${issueRef}-${trace.id.slice(0, 8)}`;
383
+ const bundleDir = path.join(input.outputDir, "full-traces", bundleDirName);
384
+ await mkdir(bundleDir, { recursive: true });
385
+ fullTraceDirs.push(bundleDirName);
386
+ await writeFile(
387
+ path.join(bundleDir, "bundle.json"),
388
+ `${JSON.stringify(bundle, null, 2)}\n`,
389
+ "utf8",
390
+ );
391
+ fullTraceFiles.push(path.posix.join("full-traces", bundleDirName, "bundle.json"));
392
+ for (const file of bundle.files) {
393
+ const targetPath = path.join(bundleDir, file.path);
394
+ await mkdir(path.dirname(targetPath), { recursive: true });
395
+ await writeFile(targetPath, file.contents, "utf8");
396
+ fullTraceFiles.push(path.posix.join("full-traces", bundleDirName, file.path.replace(/\\/g, "/")));
397
+ }
398
+ }
399
+ }
400
+
401
+ const zipPath = `${input.outputDir}.zip`;
402
+ const manifest: FeedbackExportManifest = {
403
+ exportedAt: new Date().toISOString(),
404
+ serverUrl: input.apiBase,
405
+ companyId: input.companyId,
406
+ summary: {
407
+ ...summary,
408
+ uniqueIssues: issueSet.size,
409
+ issues: Array.from(issueSet).sort((left, right) => left.localeCompare(right)),
410
+ },
411
+ files: {
412
+ votes: voteFiles.slice().sort((left, right) => left.localeCompare(right)),
413
+ traces: traceFiles.slice().sort((left, right) => left.localeCompare(right)),
414
+ fullTraces: fullTraceDirs.slice().sort((left, right) => left.localeCompare(right)),
415
+ zip: path.basename(zipPath),
416
+ },
417
+ };
418
+
419
+ await writeFile(
420
+ path.join(input.outputDir, "index.json"),
421
+ `${JSON.stringify(manifest, null, 2)}\n`,
422
+ "utf8",
423
+ );
424
+ const archiveFiles = await collectJsonFilesForArchive(input.outputDir, [
425
+ "index.json",
426
+ ...manifest.files.votes.map((file) => path.posix.join("votes", file)),
427
+ ...manifest.files.traces.map((file) => path.posix.join("traces", file)),
428
+ ...fullTraceFiles,
429
+ ]);
430
+ await writeFile(zipPath, createStoredZipArchive(archiveFiles, path.basename(input.outputDir)));
431
+
432
+ return {
433
+ outputDir: input.outputDir,
434
+ zipPath,
435
+ manifest,
436
+ };
437
+ }
438
+
439
+ export function renderFeedbackExportSummary(exported: FeedbackExportResult): string {
440
+ const lines: string[] = [];
441
+ lines.push("");
442
+ lines.push(pc.bold(pc.magenta("Paperclip Feedback Export")));
443
+ lines.push(pc.dim(exported.manifest.exportedAt));
444
+ lines.push(horizontalRule());
445
+ lines.push(`${pc.dim("Company:")} ${exported.manifest.companyId}`);
446
+ lines.push(`${pc.dim("Output:")} ${exported.outputDir}`);
447
+ lines.push(`${pc.dim("Archive:")} ${exported.zipPath}`);
448
+ lines.push("");
449
+ lines.push(pc.bold("Export Summary"));
450
+ lines.push(horizontalRule());
451
+ lines.push(` ${pc.green(pc.bold(String(exported.manifest.summary.thumbsUp)))} thumbs up`);
452
+ lines.push(` ${pc.red(pc.bold(String(exported.manifest.summary.thumbsDown)))} thumbs down`);
453
+ lines.push(` ${pc.yellow(pc.bold(String(exported.manifest.summary.withReason)))} with reason`);
454
+ lines.push(` ${pc.bold(String(exported.manifest.summary.uniqueIssues))} unique issues`);
455
+ lines.push("");
456
+ lines.push(pc.dim("Files:"));
457
+ lines.push(` ${path.join(exported.outputDir, "index.json")}`);
458
+ lines.push(` ${path.join(exported.outputDir, "votes")} (${exported.manifest.files.votes.length} files)`);
459
+ lines.push(` ${path.join(exported.outputDir, "traces")} (${exported.manifest.files.traces.length} files)`);
460
+ lines.push(` ${path.join(exported.outputDir, "full-traces")} (${exported.manifest.files.fullTraces.length} bundles)`);
461
+ lines.push(` ${exported.zipPath}`);
462
+ lines.push("");
463
+ return lines.join("\n");
464
+ }
465
+
466
+ function readFeedbackReason(trace: FeedbackTrace): string | null {
467
+ const payload = asRecord(trace.payloadSnapshot);
468
+ const vote = asRecord(payload?.vote);
469
+ const reason = vote?.reason;
470
+ return typeof reason === "string" && reason.trim() ? reason.trim() : null;
471
+ }
472
+
473
+ function buildFeedbackVoteRecord(trace: FeedbackTrace) {
474
+ return {
475
+ voteId: trace.feedbackVoteId,
476
+ traceId: trace.id,
477
+ issueId: trace.issueId,
478
+ issueIdentifier: trace.issueIdentifier,
479
+ issueTitle: trace.issueTitle,
480
+ vote: trace.vote,
481
+ targetType: trace.targetType,
482
+ targetId: trace.targetId,
483
+ targetSummary: trace.targetSummary,
484
+ status: trace.status,
485
+ consentVersion: trace.consentVersion,
486
+ createdAt: trace.createdAt,
487
+ updatedAt: trace.updatedAt,
488
+ reason: readFeedbackReason(trace),
489
+ };
490
+ }
491
+
492
+ function asRecord(value: unknown): Record<string, unknown> | null {
493
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
494
+ return value as Record<string, unknown>;
495
+ }
496
+
497
+ function compactText(value: string | null | undefined, maxLength = 88): string | null {
498
+ if (!value) return null;
499
+ const compact = value.replace(/\s+/g, " ").trim();
500
+ if (!compact) return null;
501
+ if (compact.length <= maxLength) return compact;
502
+ return `${compact.slice(0, maxLength - 3)}...`;
503
+ }
504
+
505
+ function formatTimestamp(value: unknown): string {
506
+ if (value instanceof Date) return value.toISOString().slice(0, 19).replace("T", " ");
507
+ if (typeof value === "string") return value.slice(0, 19).replace("T", " ");
508
+ return "-";
509
+ }
510
+
511
+ function horizontalRule(): string {
512
+ return pc.dim("-".repeat(72));
513
+ }
514
+
515
+ function padRight(value: string, width: number): string {
516
+ return `${value}${" ".repeat(Math.max(0, width - value.length))}`;
517
+ }
518
+
519
+ function defaultFeedbackExportDirName(): string {
520
+ const iso = new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
521
+ return `feedback-export-${iso}`;
522
+ }
523
+
524
+ async function ensureEmptyOutputDirectory(outputDir: string): Promise<void> {
525
+ try {
526
+ const info = await stat(outputDir);
527
+ if (!info.isDirectory()) {
528
+ throw new Error(`Output path already exists and is not a directory: ${outputDir}`);
529
+ }
530
+ const entries = await readdir(outputDir);
531
+ if (entries.length > 0) {
532
+ throw new Error(`Output directory already exists and is not empty: ${outputDir}`);
533
+ }
534
+ } catch (error) {
535
+ const message = error instanceof Error ? error.message : "";
536
+ if (/ENOENT/.test(message)) {
537
+ await mkdir(outputDir, { recursive: true });
538
+ return;
539
+ }
540
+ throw error;
541
+ }
542
+ }
543
+
544
+ async function collectJsonFilesForArchive(
545
+ outputDir: string,
546
+ relativePaths: string[],
547
+ ): Promise<Record<string, string>> {
548
+ const files: Record<string, string> = {};
549
+ for (const relativePath of relativePaths) {
550
+ const normalized = relativePath.replace(/\\/g, "/");
551
+ files[normalized] = await readFile(path.join(outputDir, normalized), "utf8");
552
+ }
553
+ return files;
554
+ }
555
+
556
+ function sanitizeFileSegment(value: string): string {
557
+ return value.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "feedback";
558
+ }
559
+
560
+ function writeUint16(target: Uint8Array, offset: number, value: number) {
561
+ target[offset] = value & 0xff;
562
+ target[offset + 1] = (value >>> 8) & 0xff;
563
+ }
564
+
565
+ function writeUint32(target: Uint8Array, offset: number, value: number) {
566
+ target[offset] = value & 0xff;
567
+ target[offset + 1] = (value >>> 8) & 0xff;
568
+ target[offset + 2] = (value >>> 16) & 0xff;
569
+ target[offset + 3] = (value >>> 24) & 0xff;
570
+ }
571
+
572
+ function crc32(bytes: Uint8Array) {
573
+ let crc = 0xffffffff;
574
+ for (const byte of bytes) {
575
+ crc ^= byte;
576
+ for (let bit = 0; bit < 8; bit += 1) {
577
+ crc = (crc & 1) === 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
578
+ }
579
+ }
580
+ return (crc ^ 0xffffffff) >>> 0;
581
+ }
582
+
583
+ function createStoredZipArchive(files: Record<string, string>, rootPath: string): Uint8Array {
584
+ const encoder = new TextEncoder();
585
+ const localChunks: Uint8Array[] = [];
586
+ const centralChunks: Uint8Array[] = [];
587
+ let localOffset = 0;
588
+ let entryCount = 0;
589
+
590
+ for (const [relativePath, content] of Object.entries(files).sort(([left], [right]) => left.localeCompare(right))) {
591
+ const fileName = encoder.encode(`${rootPath}/${relativePath}`);
592
+ const body = encoder.encode(content);
593
+ const checksum = crc32(body);
594
+
595
+ const localHeader = new Uint8Array(30 + fileName.length);
596
+ writeUint32(localHeader, 0, 0x04034b50);
597
+ writeUint16(localHeader, 4, 20);
598
+ writeUint16(localHeader, 6, 0x0800);
599
+ writeUint16(localHeader, 8, 0);
600
+ writeUint32(localHeader, 14, checksum);
601
+ writeUint32(localHeader, 18, body.length);
602
+ writeUint32(localHeader, 22, body.length);
603
+ writeUint16(localHeader, 26, fileName.length);
604
+ localHeader.set(fileName, 30);
605
+
606
+ const centralHeader = new Uint8Array(46 + fileName.length);
607
+ writeUint32(centralHeader, 0, 0x02014b50);
608
+ writeUint16(centralHeader, 4, 20);
609
+ writeUint16(centralHeader, 6, 20);
610
+ writeUint16(centralHeader, 8, 0x0800);
611
+ writeUint16(centralHeader, 10, 0);
612
+ writeUint32(centralHeader, 16, checksum);
613
+ writeUint32(centralHeader, 20, body.length);
614
+ writeUint32(centralHeader, 24, body.length);
615
+ writeUint16(centralHeader, 28, fileName.length);
616
+ writeUint32(centralHeader, 42, localOffset);
617
+ centralHeader.set(fileName, 46);
618
+
619
+ localChunks.push(localHeader, body);
620
+ centralChunks.push(centralHeader);
621
+ localOffset += localHeader.length + body.length;
622
+ entryCount += 1;
623
+ }
624
+
625
+ const centralDirectoryLength = centralChunks.reduce((sum, chunk) => sum + chunk.length, 0);
626
+ const archive = new Uint8Array(
627
+ localChunks.reduce((sum, chunk) => sum + chunk.length, 0) + centralDirectoryLength + 22,
628
+ );
629
+ let offset = 0;
630
+ for (const chunk of localChunks) {
631
+ archive.set(chunk, offset);
632
+ offset += chunk.length;
633
+ }
634
+ const centralDirectoryOffset = offset;
635
+ for (const chunk of centralChunks) {
636
+ archive.set(chunk, offset);
637
+ offset += chunk.length;
638
+ }
639
+ writeUint32(archive, offset, 0x06054b50);
640
+ writeUint16(archive, offset + 8, entryCount);
641
+ writeUint16(archive, offset + 10, entryCount);
642
+ writeUint32(archive, offset + 12, centralDirectoryLength);
643
+ writeUint32(archive, offset + 16, centralDirectoryOffset);
644
+ return archive;
645
+ }