@gmickel/gno 1.24.0 → 1.26.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.
Files changed (96) hide show
  1. package/README.md +18 -4
  2. package/assets/skill/SKILL.md +40 -17
  3. package/assets/skill/recipes/capture-and-file.md +20 -5
  4. package/browser-extension/artifacts/gno-browser-clipper-v1.26.0.zip +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v1.26.0.zip.sha256 +1 -0
  6. package/browser-extension/dist/PRIVACY.md +55 -0
  7. package/browser-extension/dist/chunk-vn5f663b.js +50 -0
  8. package/browser-extension/dist/chunk-ydfx5d7p.css +1 -0
  9. package/browser-extension/dist/content.js +1 -0
  10. package/browser-extension/dist/manifest.json +25 -0
  11. package/browser-extension/dist/preview.html +13 -0
  12. package/browser-extension/dist/service-worker.js +40 -0
  13. package/package.json +13 -3
  14. package/spec/cli.md +196 -4
  15. package/spec/db/schema.sql +102 -1
  16. package/spec/mcp.md +10 -0
  17. package/spec/output-schemas/browser-clip-preview.schema.json +83 -0
  18. package/spec/output-schemas/browser-clip.schema.json +586 -0
  19. package/spec/output-schemas/capture-receipt.schema.json +22 -1
  20. package/spec/output-schemas/clipper-csrf.schema.json +12 -0
  21. package/spec/output-schemas/clipper-error.schema.json +46 -0
  22. package/spec/output-schemas/clipper-pair-approval.schema.json +17 -0
  23. package/spec/output-schemas/clipper-pair-start.schema.json +26 -0
  24. package/spec/output-schemas/clipper-pair-status.schema.json +46 -0
  25. package/spec/output-schemas/clipper-revoke.schema.json +28 -0
  26. package/spec/output-schemas/mcp-capture-result.schema.json +12 -1
  27. package/spec/output-schemas/project-profile-apply.schema.json +209 -0
  28. package/spec/output-schemas/project-profile-command.schema.json +160 -0
  29. package/spec/output-schemas/query-diagnose.schema.json +7 -1
  30. package/spec/output-schemas/setup-profile-result.schema.json +87 -0
  31. package/spec/project-profile.schema.json +301 -0
  32. package/src/cli/commands/collection/add.ts +39 -45
  33. package/src/cli/commands/collection/remove.ts +28 -28
  34. package/src/cli/commands/collection/rename.ts +55 -73
  35. package/src/cli/commands/context/add.ts +37 -26
  36. package/src/cli/commands/context/rm.ts +47 -20
  37. package/src/cli/commands/init.ts +55 -125
  38. package/src/cli/commands/models/use.ts +43 -38
  39. package/src/cli/commands/profile-apply.ts +334 -0
  40. package/src/cli/commands/profile.ts +409 -0
  41. package/src/cli/commands/setup-activation.ts +205 -54
  42. package/src/cli/commands/setup-profile.ts +223 -0
  43. package/src/cli/commands/setup.ts +3 -0
  44. package/src/cli/program.ts +110 -9
  45. package/src/config/index.ts +3 -0
  46. package/src/config/project-profile.ts +367 -0
  47. package/src/config/saver.ts +16 -7
  48. package/src/config/types.ts +42 -0
  49. package/src/core/browser-clip-provenance.ts +139 -0
  50. package/src/core/browser-clip.ts +473 -0
  51. package/src/core/capture-write.ts +5 -0
  52. package/src/core/capture.ts +75 -18
  53. package/src/core/config-mutation.ts +138 -76
  54. package/src/core/config-write-lock.ts +89 -0
  55. package/src/core/context-identity.ts +16 -0
  56. package/src/core/context-resolver.ts +2 -12
  57. package/src/core/file-lock.ts +20 -6
  58. package/src/core/folder-setup-planning.ts +6 -21
  59. package/src/core/folder-setup.ts +30 -2
  60. package/src/core/path-rules.ts +53 -0
  61. package/src/core/project-affinity-surface.ts +102 -7
  62. package/src/core/project-profile-apply-state.ts +268 -0
  63. package/src/core/project-profile-apply-validation.ts +95 -0
  64. package/src/core/project-profile-apply.ts +408 -0
  65. package/src/core/project-profile-canonical.ts +71 -0
  66. package/src/core/project-profile-diff.ts +302 -0
  67. package/src/core/project-profile-discovery.ts +519 -0
  68. package/src/core/project-profile-file.ts +37 -0
  69. package/src/core/project-profile-parser.ts +98 -0
  70. package/src/core/project-profile.ts +490 -0
  71. package/src/ingestion/walker.ts +85 -44
  72. package/src/llm/cache.ts +21 -0
  73. package/src/serve/capture-service.ts +420 -0
  74. package/src/serve/clipper-body.ts +62 -0
  75. package/src/serve/clipper-capture.ts +248 -0
  76. package/src/serve/clipper-contract.ts +57 -0
  77. package/src/serve/clipper-idempotency.ts +35 -0
  78. package/src/serve/clipper-pairing.ts +297 -0
  79. package/src/serve/clipper-security-errors.ts +23 -0
  80. package/src/serve/clipper-security.ts +449 -0
  81. package/src/serve/config-sync.ts +2 -2
  82. package/src/serve/public/app.tsx +8 -1
  83. package/src/serve/public/globals.built.css +1 -1
  84. package/src/serve/public/index.html +1 -0
  85. package/src/serve/public/lib/clipper-approval.ts +206 -0
  86. package/src/serve/public/pages/ClipperPairing.tsx +210 -0
  87. package/src/serve/resident-runtime.ts +1 -0
  88. package/src/serve/routes/api.ts +20 -115
  89. package/src/serve/routes/clipper.ts +394 -0
  90. package/src/serve/server.ts +22 -0
  91. package/src/store/migrations/020-browser-clipper-security.ts +128 -0
  92. package/src/store/migrations/021-multi-context-identity.ts +37 -0
  93. package/src/store/migrations/index.ts +4 -0
  94. package/src/store/sqlite/adapter.ts +83 -0
  95. package/src/store/sqlite/clipper-store-types.ts +104 -0
  96. package/src/store/sqlite/clipper-store.ts +496 -0
@@ -0,0 +1,139 @@
1
+ import { z } from "zod";
2
+
3
+ export const BROWSER_CLIP_SCHEMA_VERSION = "1.0" as const;
4
+ export const BROWSER_CLIP_MAX_BYTES = 512 * 1024;
5
+
6
+ export const BROWSER_CLIP_WARNING_CODES = [
7
+ "authenticated_visible_content",
8
+ "canonical_url_differs",
9
+ "edited_content",
10
+ "line_endings_normalized",
11
+ "reader_partial",
12
+ "selection_truncated",
13
+ "spa_snapshot",
14
+ "unicode_normalized",
15
+ ] as const;
16
+
17
+ export const BROWSER_CLIP_HTTP_URL_PATTERN =
18
+ "^[Hh][Tt][Tt][Pp][Ss]?://(?:(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])|(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)*[A-Za-z](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(?::(?:[1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?(?:(?:/(?:[A-Za-z0-9._~!$&'()*+,;=:@-]|%[0-9A-Fa-f]{2})*)*)(?:\\?(?:[A-Za-z0-9._~!$&'()*+,;=:@/?-]|%[0-9A-Fa-f]{2})*)?(?:#(?:[A-Za-z0-9._~!$&'()*+,;=:@/?-]|%[0-9A-Fa-f]{2})*)?$";
19
+
20
+ const hasDisallowedControlCharacter = (value: string): boolean => {
21
+ for (const character of value) {
22
+ const codePoint = character.codePointAt(0);
23
+ if (
24
+ codePoint !== undefined &&
25
+ (codePoint <= 8 ||
26
+ codePoint === 11 ||
27
+ codePoint === 12 ||
28
+ (codePoint >= 14 && codePoint <= 31) ||
29
+ (codePoint >= 127 && codePoint <= 159))
30
+ ) {
31
+ return true;
32
+ }
33
+ }
34
+ return false;
35
+ };
36
+
37
+ export const findDisallowedBrowserClipControlPath = (
38
+ value: unknown,
39
+ path: Array<string | number> = []
40
+ ): Array<string | number> | null => {
41
+ if (typeof value === "string") {
42
+ return hasDisallowedControlCharacter(value) ? path : null;
43
+ }
44
+ if (Array.isArray(value)) {
45
+ for (const [index, child] of value.entries()) {
46
+ const match = findDisallowedBrowserClipControlPath(child, [
47
+ ...path,
48
+ index,
49
+ ]);
50
+ if (match !== null) return match;
51
+ }
52
+ return null;
53
+ }
54
+ if (value !== null && typeof value === "object") {
55
+ for (const [key, child] of Object.entries(value)) {
56
+ const match = findDisallowedBrowserClipControlPath(child, [...path, key]);
57
+ if (match !== null) return match;
58
+ }
59
+ }
60
+ return null;
61
+ };
62
+
63
+ export const browserClipHttpUrlSchema = z
64
+ .string()
65
+ .max(4096)
66
+ .regex(
67
+ new RegExp(BROWSER_CLIP_HTTP_URL_PATTERN, "u"),
68
+ "URL must use the browser clip HTTP(S) URL subset"
69
+ );
70
+
71
+ const publishedAtSchema = z.union([
72
+ z.string().date(),
73
+ z.string().datetime({ offset: true }),
74
+ ]);
75
+
76
+ const browserSchema = z
77
+ .object({
78
+ name: z.string().min(1).max(128),
79
+ version: z.string().max(128).nullable(),
80
+ platform: z.string().max(128).nullable(),
81
+ })
82
+ .strict();
83
+
84
+ const sha256Schema = z.string().regex(/^[a-f0-9]{64}$/);
85
+
86
+ export const browserClipProvenanceSchema = z
87
+ .object({
88
+ schemaVersion: z.literal(BROWSER_CLIP_SCHEMA_VERSION),
89
+ mode: z.enum(["selection", "reader"]),
90
+ sourceUrl: browserClipHttpUrlSchema,
91
+ canonicalUrl: browserClipHttpUrlSchema.nullable(),
92
+ title: z.string().min(1).max(2048),
93
+ author: z.string().max(1024).nullable(),
94
+ site: z.string().max(1024).nullable(),
95
+ publishedAt: publishedAtSchema.nullable(),
96
+ observedAt: z.string().datetime({ offset: true }),
97
+ capturedAt: z.string().datetime({ offset: true }),
98
+ extractionHash: sha256Schema,
99
+ finalBodyHash: sha256Schema,
100
+ clipIdentity: sha256Schema,
101
+ previewDigest: sha256Schema,
102
+ exactSelection: z.string().min(1).max(BROWSER_CLIP_MAX_BYTES).nullable(),
103
+ extractionWarnings: z.array(z.enum(BROWSER_CLIP_WARNING_CODES)).max(16),
104
+ browser: browserSchema,
105
+ })
106
+ .strict()
107
+ .superRefine((value, context) => {
108
+ const controlPath = findDisallowedBrowserClipControlPath(value);
109
+ if (controlPath !== null) {
110
+ context.addIssue({
111
+ code: "custom",
112
+ message: "Browser clip text cannot contain C0 or C1 control characters",
113
+ path: controlPath,
114
+ });
115
+ }
116
+ if (
117
+ new Set(value.extractionWarnings).size !== value.extractionWarnings.length
118
+ ) {
119
+ context.addIssue({
120
+ code: "custom",
121
+ message: "Warning codes must be unique",
122
+ path: ["extractionWarnings"],
123
+ });
124
+ }
125
+ if (
126
+ (value.mode === "selection" && value.exactSelection === null) ||
127
+ (value.mode === "reader" && value.exactSelection !== null)
128
+ ) {
129
+ context.addIssue({
130
+ code: "custom",
131
+ message: "Exact selection must match the extraction mode",
132
+ path: ["exactSelection"],
133
+ });
134
+ }
135
+ });
136
+
137
+ export type BrowserClipProvenance = z.infer<typeof browserClipProvenanceSchema>;
138
+ export type BrowserClipWarningCode =
139
+ (typeof BROWSER_CLIP_WARNING_CODES)[number];
@@ -0,0 +1,473 @@
1
+ import { z } from "zod";
2
+
3
+ import { canonicalize } from "../converters/canonicalize";
4
+ import {
5
+ BROWSER_CLIP_MAX_BYTES,
6
+ BROWSER_CLIP_SCHEMA_VERSION,
7
+ BROWSER_CLIP_WARNING_CODES,
8
+ browserClipHttpUrlSchema,
9
+ findDisallowedBrowserClipControlPath,
10
+ type BrowserClipProvenance,
11
+ type BrowserClipWarningCode,
12
+ } from "./browser-clip-provenance";
13
+ import {
14
+ hashCaptureContent,
15
+ type CaptureInput,
16
+ type CaptureSource,
17
+ } from "./capture";
18
+
19
+ export {
20
+ BROWSER_CLIP_MAX_BYTES,
21
+ BROWSER_CLIP_SCHEMA_VERSION,
22
+ } from "./browser-clip-provenance";
23
+ export type {
24
+ BrowserClipProvenance,
25
+ BrowserClipWarningCode,
26
+ } from "./browser-clip-provenance";
27
+
28
+ const sha256 = (value: string): string =>
29
+ new Bun.CryptoHasher("sha256").update(value).digest("hex");
30
+
31
+ const stableJsonValue = (value: unknown): unknown => {
32
+ if (Array.isArray(value)) return value.map(stableJsonValue);
33
+ if (value !== null && typeof value === "object") {
34
+ return Object.fromEntries(
35
+ Object.entries(value as Record<string, unknown>)
36
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
37
+ .map(([key, child]) => [key, stableJsonValue(child)])
38
+ );
39
+ }
40
+ return value;
41
+ };
42
+
43
+ const stableJson = (value: unknown): string =>
44
+ JSON.stringify(stableJsonValue(value));
45
+
46
+ const strictDateTime = z.string().datetime({ offset: true });
47
+ const strictPublishedDate = z
48
+ .union([z.string().date(), z.string().datetime({ offset: true })])
49
+ .nullable();
50
+
51
+ const safeInlineText = z.string().min(1).max(32_768);
52
+ const inlineNodeSchema = z.discriminatedUnion("type", [
53
+ z.object({ type: z.literal("text"), text: safeInlineText }).strict(),
54
+ z
55
+ .object({
56
+ type: z.literal("link"),
57
+ text: safeInlineText,
58
+ href: browserClipHttpUrlSchema,
59
+ })
60
+ .strict(),
61
+ ]);
62
+ const inlineContentSchema = z.array(inlineNodeSchema).min(1).max(256);
63
+
64
+ const readerBlockSchema = z.discriminatedUnion("type", [
65
+ z
66
+ .object({ type: z.literal("paragraph"), content: inlineContentSchema })
67
+ .strict(),
68
+ z
69
+ .object({
70
+ type: z.literal("heading"),
71
+ level: z.number().int().min(1).max(6),
72
+ content: inlineContentSchema,
73
+ })
74
+ .strict(),
75
+ z.object({ type: z.literal("quote"), content: inlineContentSchema }).strict(),
76
+ z
77
+ .object({
78
+ type: z.literal("list"),
79
+ ordered: z.boolean(),
80
+ items: z.array(inlineContentSchema).min(1).max(256),
81
+ })
82
+ .strict(),
83
+ z
84
+ .object({
85
+ type: z.literal("code"),
86
+ language: z
87
+ .string()
88
+ .regex(/^[A-Za-z0-9_+-]{1,32}$/)
89
+ .nullable(),
90
+ text: z.string().max(131_072),
91
+ })
92
+ .strict(),
93
+ z.object({ type: z.literal("horizontal_rule") }).strict(),
94
+ ]);
95
+
96
+ const commonPayload = z
97
+ .object({
98
+ schemaVersion: z.literal(BROWSER_CLIP_SCHEMA_VERSION),
99
+ sourceUrl: browserClipHttpUrlSchema,
100
+ canonicalUrl: browserClipHttpUrlSchema.nullable(),
101
+ title: z.string().min(1).max(2048),
102
+ author: z.string().max(1024).nullable(),
103
+ site: z.string().max(1024).nullable(),
104
+ publishedAt: strictPublishedDate,
105
+ observedAt: strictDateTime,
106
+ browser: z
107
+ .object({
108
+ name: z.string().min(1).max(128),
109
+ version: z.string().max(128).nullable(),
110
+ platform: z.string().max(128).nullable(),
111
+ })
112
+ .strict(),
113
+ extraction: z
114
+ .object({
115
+ visibility: z.literal("user_visible"),
116
+ authenticated: z.boolean(),
117
+ extractorVersion: z.string().min(1).max(128),
118
+ warnings: z.array(z.enum(BROWSER_CLIP_WARNING_CODES)).max(16),
119
+ })
120
+ .strict(),
121
+ destination: z
122
+ .object({
123
+ collection: z.string().min(1).max(128),
124
+ relPath: z.string().min(1).max(2048).nullable(),
125
+ folderPath: z.string().min(1).max(2048).nullable(),
126
+ collisionPolicy: z.enum([
127
+ "error",
128
+ "open_existing",
129
+ "create_with_suffix",
130
+ ]),
131
+ })
132
+ .strict(),
133
+ tags: z.array(z.string().min(1).max(256)).max(128),
134
+ note: z.string().max(32_768).nullable(),
135
+ })
136
+ .strict();
137
+
138
+ const selectionPayload = commonPayload
139
+ .extend({
140
+ mode: z.literal("selection"),
141
+ selection: z
142
+ .object({
143
+ exactText: z.string().min(1).max(BROWSER_CLIP_MAX_BYTES),
144
+ editedMarkdown: z.string().max(BROWSER_CLIP_MAX_BYTES).nullable(),
145
+ })
146
+ .strict(),
147
+ })
148
+ .strict();
149
+
150
+ const readerPayload = commonPayload
151
+ .extend({
152
+ mode: z.literal("reader"),
153
+ reader: z
154
+ .object({
155
+ blocks: z.array(readerBlockSchema).min(1).max(4096),
156
+ editedMarkdown: z.string().max(BROWSER_CLIP_MAX_BYTES).nullable(),
157
+ })
158
+ .strict(),
159
+ })
160
+ .strict();
161
+
162
+ export const browserClipPayloadSchema = z
163
+ .discriminatedUnion("mode", [selectionPayload, readerPayload])
164
+ .superRefine((value, context) => {
165
+ const controlPath = findDisallowedBrowserClipControlPath(value);
166
+ if (controlPath !== null) {
167
+ context.addIssue({
168
+ code: "custom",
169
+ message: "Browser clip text cannot contain C0 or C1 control characters",
170
+ path: controlPath,
171
+ });
172
+ }
173
+ if (
174
+ new TextEncoder().encode(stableJson(value)).byteLength >
175
+ BROWSER_CLIP_MAX_BYTES
176
+ ) {
177
+ context.addIssue({
178
+ code: "custom",
179
+ message: "Browser clip payload is too large",
180
+ });
181
+ }
182
+ if (
183
+ new Set(value.extraction.warnings).size !==
184
+ value.extraction.warnings.length
185
+ ) {
186
+ context.addIssue({
187
+ code: "custom",
188
+ message: "Warning codes must be unique",
189
+ });
190
+ }
191
+ if (
192
+ value.destination.relPath !== null &&
193
+ value.destination.folderPath !== null
194
+ ) {
195
+ context.addIssue({
196
+ code: "custom",
197
+ message: "Use relPath or folderPath, not both",
198
+ path: ["destination"],
199
+ });
200
+ }
201
+ });
202
+
203
+ export type BrowserClipPayload = z.infer<typeof browserClipPayloadSchema>;
204
+ export type BrowserClipBlock = z.infer<typeof readerBlockSchema>;
205
+
206
+ export interface PreparedBrowserClip {
207
+ payload: BrowserClipPayload;
208
+ captureInput: CaptureInput;
209
+ provenance: BrowserClipProvenance;
210
+ preview: {
211
+ body: string;
212
+ digest: string;
213
+ source: CaptureSource;
214
+ destination: BrowserClipPayload["destination"];
215
+ tags: string[];
216
+ };
217
+ }
218
+
219
+ const normalizeUrl = (value: string): string => {
220
+ const url = new URL(value);
221
+ url.hash = "";
222
+ url.searchParams.sort();
223
+ return url.toString();
224
+ };
225
+
226
+ const normalizePublishedAt = (value: string | null): string | null => {
227
+ if (value === null || /^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
228
+ return new Date(value).toISOString();
229
+ };
230
+
231
+ const escapeInline = (value: string): string =>
232
+ value
233
+ .replaceAll("<", "&lt;")
234
+ .replaceAll(">", "&gt;")
235
+ .replace(/([\\*_[\]~`])/g, "\\$1");
236
+
237
+ const normalizeLink = (value: string): string =>
238
+ normalizeUrl(value).replaceAll("(", "%28").replaceAll(")", "%29");
239
+
240
+ const renderInline = (content: z.infer<typeof inlineContentSchema>): string =>
241
+ content
242
+ .map((node) =>
243
+ node.type === "text"
244
+ ? escapeInline(node.text)
245
+ : `[${escapeInline(node.text)}](${normalizeLink(node.href)})`
246
+ )
247
+ .join("");
248
+
249
+ const codeFence = (text: string): string => {
250
+ const longest = Math.max(
251
+ 0,
252
+ ...[...text.matchAll(/`+/g)].map((match) => match[0].length)
253
+ );
254
+ return "`".repeat(Math.max(3, longest + 1));
255
+ };
256
+
257
+ export const renderBrowserClipReader = (
258
+ blocks: readonly BrowserClipBlock[]
259
+ ): string =>
260
+ canonicalize(
261
+ blocks
262
+ .map((block) => {
263
+ switch (block.type) {
264
+ case "paragraph":
265
+ return renderInline(block.content);
266
+ case "heading":
267
+ return `${"#".repeat(block.level)} ${renderInline(block.content)}`;
268
+ case "quote":
269
+ return renderInline(block.content)
270
+ .split("\n")
271
+ .map((line) => `> ${line}`)
272
+ .join("\n");
273
+ case "list":
274
+ return block.items
275
+ .map(
276
+ (item, index) =>
277
+ `${block.ordered ? `${index + 1}.` : "-"} ${renderInline(item)}`
278
+ )
279
+ .join("\n");
280
+ case "code": {
281
+ const fence = codeFence(block.text);
282
+ return `${fence}${block.language ?? ""}\n${block.text}\n${fence}`;
283
+ }
284
+ case "horizontal_rule":
285
+ return "---";
286
+ }
287
+ })
288
+ .join("\n\n")
289
+ );
290
+
291
+ const INLINE_MARKDOWN_LINK = /(?<!!)\[[^\]\r\n]*\]\(([^()\s]+)\)/gu;
292
+ const REFERENCE_LINK = /\[[^\]\r\n]*\]\s*\[[^\]\r\n]*\]/u;
293
+ const REFERENCE_DEFINITION = /^[ \t]{0,3}\[[^\]\r\n]+\]:/mu;
294
+
295
+ const assertSafeEditedMarkdown = (markdown: string): void => {
296
+ if (markdown.includes("<")) {
297
+ throw new Error(
298
+ "Edited clip Markdown cannot contain HTML, comments, or autolinks."
299
+ );
300
+ }
301
+ if (markdown.includes("![")) {
302
+ throw new Error("Edited clip Markdown cannot contain images.");
303
+ }
304
+ if (REFERENCE_LINK.test(markdown) || REFERENCE_DEFINITION.test(markdown)) {
305
+ throw new Error("Edited clip Markdown cannot contain reference links.");
306
+ }
307
+ const unmatchedInlineSyntax = markdown.replace(
308
+ INLINE_MARKDOWN_LINK,
309
+ (_link, destination: string) => {
310
+ browserClipHttpUrlSchema.parse(destination);
311
+ return "";
312
+ }
313
+ );
314
+ if (unmatchedInlineSyntax.includes("](")) {
315
+ throw new Error(
316
+ "Edited clip Markdown links must use a simple absolute HTTP(S) destination."
317
+ );
318
+ }
319
+ };
320
+
321
+ const notePrefix = (note: string | null): string => {
322
+ const trimmed = note?.trim();
323
+ if (!trimmed) return "";
324
+ return `> **Clip note:** ${escapeInline(trimmed).replaceAll("\n", "\n> ")}\n\n`;
325
+ };
326
+
327
+ const dedupeWarnings = (
328
+ values: readonly BrowserClipWarningCode[]
329
+ ): BrowserClipWarningCode[] => [...new Set(values)].sort();
330
+
331
+ export const prepareBrowserClip = (
332
+ input: unknown,
333
+ options: { now?: Date } = {}
334
+ ): PreparedBrowserClip => {
335
+ const payload = browserClipPayloadSchema.parse(input);
336
+ const capturedAt = (options.now ?? new Date()).toISOString();
337
+ const sourceUrl = normalizeUrl(payload.sourceUrl);
338
+ const canonicalUrl =
339
+ payload.canonicalUrl === null ? null : normalizeUrl(payload.canonicalUrl);
340
+ const extracted =
341
+ payload.mode === "selection"
342
+ ? payload.selection.exactText
343
+ : stableJson(payload.reader.blocks);
344
+ const edited =
345
+ payload.mode === "selection"
346
+ ? payload.selection.editedMarkdown
347
+ : payload.reader.editedMarkdown;
348
+ if (edited !== null) assertSafeEditedMarkdown(edited);
349
+ const uneditedBody =
350
+ payload.mode === "selection"
351
+ ? escapeInline(payload.selection.exactText)
352
+ : renderBrowserClipReader(payload.reader.blocks);
353
+ const body = canonicalize(
354
+ `${notePrefix(payload.note)}${edited ?? uneditedBody}`
355
+ );
356
+ const extractionHash = sha256(extracted);
357
+ const finalBodyHash = hashCaptureContent(body);
358
+ const clipIdentity = sha256(
359
+ stableJson({
360
+ canonicalUrl,
361
+ extractionHash,
362
+ finalBodyHash,
363
+ mode: payload.mode,
364
+ schemaVersion: payload.schemaVersion,
365
+ sourceUrl,
366
+ })
367
+ );
368
+ const warnings: BrowserClipWarningCode[] = [...payload.extraction.warnings];
369
+ if (payload.extraction.authenticated)
370
+ warnings.push("authenticated_visible_content");
371
+ if (canonicalUrl !== null && canonicalUrl !== sourceUrl) {
372
+ warnings.push("canonical_url_differs");
373
+ }
374
+ if (edited !== null) warnings.push("edited_content");
375
+ if (extracted.includes("\r")) warnings.push("line_endings_normalized");
376
+ if (extracted.normalize("NFC") !== extracted)
377
+ warnings.push("unicode_normalized");
378
+ const extractionWarnings = dedupeWarnings(warnings);
379
+ const publishedAt = normalizePublishedAt(payload.publishedAt);
380
+ const observedAt = new Date(payload.observedAt).toISOString();
381
+ const exactSelection =
382
+ payload.mode === "selection" ? payload.selection.exactText : null;
383
+ const previewSource = {
384
+ kind: "web",
385
+ title: payload.title,
386
+ url: sourceUrl,
387
+ author: payload.author,
388
+ observedAt,
389
+ canonicalUrl,
390
+ site: payload.site,
391
+ publishedAt,
392
+ };
393
+ const previewProvenance = {
394
+ schemaVersion: payload.schemaVersion,
395
+ mode: payload.mode,
396
+ sourceUrl,
397
+ canonicalUrl,
398
+ title: payload.title,
399
+ author: payload.author,
400
+ site: payload.site,
401
+ publishedAt,
402
+ observedAt,
403
+ extractionHash,
404
+ finalBodyHash,
405
+ clipIdentity,
406
+ exactSelection,
407
+ extractionWarnings,
408
+ browser: payload.browser,
409
+ };
410
+ const previewDigest = sha256(
411
+ stableJson({
412
+ body,
413
+ destination: payload.destination,
414
+ extraction: payload.extraction,
415
+ provenance: previewProvenance,
416
+ source: previewSource,
417
+ tags: payload.tags,
418
+ })
419
+ );
420
+ const provenance: BrowserClipProvenance = {
421
+ schemaVersion: payload.schemaVersion,
422
+ mode: payload.mode,
423
+ sourceUrl,
424
+ canonicalUrl,
425
+ title: payload.title,
426
+ author: payload.author,
427
+ site: payload.site,
428
+ publishedAt,
429
+ observedAt,
430
+ capturedAt,
431
+ extractionHash,
432
+ finalBodyHash,
433
+ clipIdentity,
434
+ previewDigest,
435
+ exactSelection,
436
+ extractionWarnings,
437
+ browser: payload.browser,
438
+ };
439
+ const source: CaptureSource = {
440
+ kind: "web",
441
+ title: payload.title,
442
+ url: sourceUrl,
443
+ author: payload.author ?? undefined,
444
+ observedAt: provenance.observedAt,
445
+ capturedAt,
446
+ canonicalUrl: canonicalUrl ?? undefined,
447
+ site: payload.site ?? undefined,
448
+ publishedAt: provenance.publishedAt ?? undefined,
449
+ browserClip: provenance,
450
+ };
451
+ const captureInput: CaptureInput = {
452
+ collection: payload.destination.collection,
453
+ content: body,
454
+ title: payload.title,
455
+ relPath: payload.destination.relPath ?? undefined,
456
+ folderPath: payload.destination.folderPath ?? undefined,
457
+ collisionPolicy: payload.destination.collisionPolicy,
458
+ tags: payload.tags,
459
+ source,
460
+ };
461
+ return {
462
+ payload,
463
+ captureInput,
464
+ provenance,
465
+ preview: {
466
+ body,
467
+ digest: previewDigest,
468
+ source,
469
+ destination: payload.destination,
470
+ tags: payload.tags,
471
+ },
472
+ };
473
+ };
@@ -21,6 +21,11 @@ export async function writeCapturePlanFile(
21
21
  plan: CapturePlan,
22
22
  absPath: string
23
23
  ): Promise<void> {
24
+ if (plan.provenanceConflict) {
25
+ throw new Error(
26
+ "Existing capture has different provenance. Use create_with_suffix or a different destination."
27
+ );
28
+ }
24
29
  try {
25
30
  if (plan.overwrite) {
26
31
  await atomicWrite(absPath, plan.content);