ima2-gen 1.1.7 → 1.1.8

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/config.js CHANGED
@@ -122,6 +122,46 @@ export const config = {
122
122
  fileCfg.limits?.promptImportMaxSourceCharsScanned,
123
123
  512 * 1024,
124
124
  ),
125
+ promptImportMaxRepoIndexFiles: pickInt(
126
+ env.IMA2_PROMPT_IMPORT_MAX_REPO_INDEX_FILES,
127
+ fileCfg.limits?.promptImportMaxRepoIndexFiles,
128
+ 500,
129
+ ),
130
+ promptImportCuratedSearchLimit: pickInt(
131
+ env.IMA2_PROMPT_IMPORT_CURATED_SEARCH_LIMIT,
132
+ fileCfg.limits?.promptImportCuratedSearchLimit,
133
+ 50,
134
+ ),
135
+ promptImportIndexCacheTtlMs: pickInt(
136
+ env.IMA2_PROMPT_IMPORT_INDEX_CACHE_TTL_MS,
137
+ fileCfg.limits?.promptImportIndexCacheTtlMs,
138
+ 24 * 60 * 60 * 1000,
139
+ ),
140
+ promptImportMaxFolderFiles: pickInt(
141
+ env.IMA2_PROMPT_IMPORT_MAX_FOLDER_FILES,
142
+ fileCfg.limits?.promptImportMaxFolderFiles,
143
+ 100,
144
+ ),
145
+ promptImportMaxFolderPreviewFiles: pickInt(
146
+ env.IMA2_PROMPT_IMPORT_MAX_FOLDER_PREVIEW_FILES,
147
+ fileCfg.limits?.promptImportMaxFolderPreviewFiles,
148
+ 20,
149
+ ),
150
+ promptImportDiscoverySearchLimit: pickInt(
151
+ env.IMA2_PROMPT_IMPORT_DISCOVERY_SEARCH_LIMIT,
152
+ fileCfg.limits?.promptImportDiscoverySearchLimit,
153
+ 20,
154
+ ),
155
+ promptImportDiscoveryCacheTtlMs: pickInt(
156
+ env.IMA2_PROMPT_IMPORT_DISCOVERY_CACHE_TTL_MS,
157
+ fileCfg.limits?.promptImportDiscoveryCacheTtlMs,
158
+ 60 * 60 * 1000,
159
+ ),
160
+ promptImportDiscoveryMaxQueries: pickInt(
161
+ env.IMA2_PROMPT_IMPORT_DISCOVERY_MAX_QUERIES,
162
+ fileCfg.limits?.promptImportDiscoveryMaxQueries,
163
+ 5,
164
+ ),
125
165
  },
126
166
  history: {
127
167
  defaultPageSize: pickInt(
@@ -153,6 +193,9 @@ export const config = {
153
193
  : ["auto", "low"],
154
194
  ),
155
195
  },
196
+ github: {
197
+ token: pickStr(env.IMA2_GITHUB_TOKEN, fileCfg.github?.token, ""),
198
+ },
156
199
  storage: {
157
200
  configDir,
158
201
  packageRoot,
@@ -161,6 +204,16 @@ export const config = {
161
204
  generatedDirName: pickStr(env.IMA2_GENERATED_DIRNAME, fileCfg.storage?.generatedDirName, "generated"),
162
205
  trashDirName: pickStr(env.IMA2_TRASH_DIRNAME, fileCfg.storage?.trashDirName, ".trash"),
163
206
  dbPath: pickStr(env.IMA2_DB_PATH, fileCfg.storage?.dbPath, join(configDir, "sessions.db")),
207
+ promptImportIndexCacheFile: pickStr(
208
+ env.IMA2_PROMPT_IMPORT_INDEX_CACHE_FILE,
209
+ fileCfg.storage?.promptImportIndexCacheFile,
210
+ join(configDir, "prompt-import-index.json"),
211
+ ),
212
+ promptImportDiscoveryRegistryFile: pickStr(
213
+ env.IMA2_PROMPT_IMPORT_DISCOVERY_REGISTRY_FILE,
214
+ fileCfg.storage?.promptImportDiscoveryRegistryFile,
215
+ join(configDir, "prompt-import-discovery.json"),
216
+ ),
164
217
  configFile: join(configDir, "config.json"),
165
218
  advertiseFile: pickStr(env.IMA2_ADVERTISE_FILE, fileCfg.storage?.advertiseFile, join(configDir, "server.json")),
166
219
  staticMaxAge: pickStr(env.IMA2_STATIC_MAX_AGE, fileCfg.storage?.staticMaxAge, "1y"),
@@ -0,0 +1,111 @@
1
+ import { mkdir, writeFile } from "fs/promises";
2
+ import { basename, join, normalize } from "path";
3
+ import { randomBytes } from "crypto";
4
+ import { embedImageMetadataBestEffort } from "./imageMetadataStore.js";
5
+
6
+ const PNG_SIGNATURE_HEX = "89504e470d0a1a0a";
7
+ const JPEG_SIGNATURE_HEX = "ffd8ff";
8
+ const WEBP_RIFF_HEAD = "52494646";
9
+ const WEBP_VP_TAIL = "57454250";
10
+
11
+ function detectFormat(buffer) {
12
+ if (!Buffer.isBuffer(buffer) || buffer.length < 12) return null;
13
+ const head8 = buffer.subarray(0, 8).toString("hex");
14
+ if (head8 === PNG_SIGNATURE_HEX) return "png";
15
+ if (head8.startsWith(JPEG_SIGNATURE_HEX)) return "jpeg";
16
+ if (
17
+ buffer.subarray(0, 4).toString("hex") === WEBP_RIFF_HEAD &&
18
+ buffer.subarray(8, 12).toString("hex") === WEBP_VP_TAIL
19
+ ) {
20
+ return "webp";
21
+ }
22
+ return null;
23
+ }
24
+
25
+ function ensureInsideGeneratedDir(generatedDir, filename) {
26
+ const full = normalize(join(generatedDir, filename));
27
+ const root = normalize(generatedDir);
28
+ if (!full.startsWith(root)) {
29
+ const err = new Error("Imported path escapes generated directory");
30
+ err.status = 400;
31
+ err.code = "IMPORT_PATH_ESCAPE";
32
+ throw err;
33
+ }
34
+ return full;
35
+ }
36
+
37
+ function makeImportedFilename(format) {
38
+ const stamp = new Date().toISOString().slice(0, 19).replace(/[-:T]/g, "");
39
+ const rand = randomBytes(3).toString("hex");
40
+ return `imported-${stamp}-${rand}.${format}`;
41
+ }
42
+
43
+ function safeOriginalName(input) {
44
+ if (typeof input !== "string" || !input) return null;
45
+ const trimmed = input.slice(0, 200);
46
+ return basename(trimmed);
47
+ }
48
+
49
+ export async function createLocalImport(ctx, { buffer, originalFilename }) {
50
+ if (!Buffer.isBuffer(buffer) || buffer.length === 0) {
51
+ const err = new Error("Image body is required");
52
+ err.status = 400;
53
+ err.code = "EMPTY_IMPORT";
54
+ throw err;
55
+ }
56
+ const format = detectFormat(buffer);
57
+ if (!format) {
58
+ const err = new Error("Only PNG, JPEG, or WebP is supported");
59
+ err.status = 400;
60
+ err.code = "IMPORT_BAD_FORMAT";
61
+ throw err;
62
+ }
63
+ const filename = makeImportedFilename(format);
64
+ const fullPath = ensureInsideGeneratedDir(ctx.config.storage.generatedDir, filename);
65
+ await mkdir(ctx.config.storage.generatedDir, { recursive: true });
66
+
67
+ const meta = {
68
+ schema: "ima2.generation.v1",
69
+ app: "ima2-gen",
70
+ version: ctx.packageVersion,
71
+ createdAt: Date.now(),
72
+ kind: "imported",
73
+ canvasVersion: false,
74
+ originalFilename: safeOriginalName(originalFilename),
75
+ format,
76
+ };
77
+ const embedded = await embedImageMetadataBestEffort(buffer, format, meta, {
78
+ version: ctx.packageVersion,
79
+ });
80
+ await writeFile(fullPath, embedded.buffer);
81
+ await writeFile(`${fullPath}.json`, JSON.stringify(meta)).catch(() => {});
82
+
83
+ const url = `/generated/${encodeURIComponent(filename)}`;
84
+ return {
85
+ filename,
86
+ url,
87
+ image: url,
88
+ thumb: url,
89
+ createdAt: meta.createdAt,
90
+ format,
91
+ kind: "imported",
92
+ canvasVersion: false,
93
+ canvasSourceFilename: null,
94
+ canvasEditableFilename: null,
95
+ prompt: null,
96
+ userPrompt: null,
97
+ revisedPrompt: null,
98
+ promptMode: null,
99
+ quality: null,
100
+ size: null,
101
+ model: null,
102
+ provider: null,
103
+ usage: null,
104
+ webSearchCalls: 0,
105
+ sessionId: null,
106
+ nodeId: null,
107
+ parentNodeId: null,
108
+ refsCount: 0,
109
+ isFavorite: false,
110
+ };
111
+ }
@@ -0,0 +1,139 @@
1
+ const CURATED_SOURCES = [
2
+ {
3
+ id: "picotrex-nano-banana",
4
+ repo: "PicoTrex/Awesome-Nano-Banana-images",
5
+ owner: "PicoTrex",
6
+ name: "Awesome-Nano-Banana-images",
7
+ displayName: "Awesome Nano Banana Images",
8
+ defaultRef: "main",
9
+ allowedPaths: ["README_en.md", "README.md"],
10
+ extensions: ["md"],
11
+ sourceType: "nano-banana-gallery",
12
+ licenseSpdx: "Apache-2.0",
13
+ requiresAttribution: true,
14
+ trustTier: "curated",
15
+ lastVerifiedAt: "2026-04-28",
16
+ notes: "High-signal Nano Banana image prompt and example collection.",
17
+ searchSeeds: ["nano banana", "image generation", "reference image", "style transfer", "prompt"],
18
+ defaultSearch: true,
19
+ },
20
+ {
21
+ id: "aimikoda-nano-banana-pro",
22
+ repo: "aimikoda/nano-banana-pro-prompts",
23
+ owner: "aimikoda",
24
+ name: "nano-banana-pro-prompts",
25
+ displayName: "Nano Banana Pro Prompts",
26
+ defaultRef: "main",
27
+ allowedPaths: ["README.md"],
28
+ extensions: ["md"],
29
+ sourceType: "nano-banana-prompts",
30
+ licenseSpdx: "NOASSERTION",
31
+ requiresAttribution: true,
32
+ trustTier: "curated",
33
+ lastVerifiedAt: "2026-04-28",
34
+ notes: "Nano Banana Pro / Nano Banana 2 prompt source.",
35
+ searchSeeds: ["nano banana pro", "gpt-image-2", "prompt", "2k", "4k"],
36
+ defaultSearch: true,
37
+ },
38
+ {
39
+ id: "stable-diffusion-awesome-manual",
40
+ repo: "yuyan124/awesome-stable-diffusion-prompts",
41
+ displayName: "Awesome Stable Diffusion Prompts",
42
+ defaultRef: "main",
43
+ allowedPaths: [],
44
+ extensions: ["md", "txt"],
45
+ sourceType: "manual-review",
46
+ licenseSpdx: "NOASSERTION",
47
+ requiresAttribution: true,
48
+ trustTier: "manual-review",
49
+ lastVerifiedAt: null,
50
+ notes: "Manual-review candidate for a later registry promotion.",
51
+ searchSeeds: ["stable diffusion", "prompt"],
52
+ defaultSearch: false,
53
+ },
54
+ {
55
+ id: "stable-diffusion-templates-manual",
56
+ repo: "Dalabad/stable-diffusion-prompt-templates",
57
+ displayName: "Stable Diffusion Prompt Templates",
58
+ defaultRef: "main",
59
+ allowedPaths: [],
60
+ extensions: ["md", "txt"],
61
+ sourceType: "manual-review",
62
+ licenseSpdx: "NOASSERTION",
63
+ requiresAttribution: true,
64
+ trustTier: "manual-review",
65
+ lastVerifiedAt: null,
66
+ notes: "Manual-review candidate for structured Stable Diffusion prompt templates.",
67
+ searchSeeds: ["stable diffusion", "template", "prompt"],
68
+ defaultSearch: false,
69
+ },
70
+ {
71
+ id: "midjourney-awesome-manual",
72
+ repo: "Ezagor-dev/awesome-midjourney-prompts",
73
+ displayName: "Awesome Midjourney Prompts",
74
+ defaultRef: "main",
75
+ allowedPaths: [],
76
+ extensions: ["md", "txt"],
77
+ sourceType: "manual-review",
78
+ licenseSpdx: "NOASSERTION",
79
+ requiresAttribution: true,
80
+ trustTier: "manual-review",
81
+ lastVerifiedAt: null,
82
+ notes: "Manual-review candidate for broader model-aware search.",
83
+ searchSeeds: ["midjourney", "prompt"],
84
+ defaultSearch: false,
85
+ },
86
+ {
87
+ id: "diagram-image-prompts-manual",
88
+ repo: "danielrosehill/Tech-Diagram-Image-Gen-Prompts",
89
+ displayName: "Tech Diagram Image Gen Prompts",
90
+ defaultRef: "main",
91
+ allowedPaths: [],
92
+ extensions: ["md", "txt"],
93
+ sourceType: "manual-review",
94
+ licenseSpdx: "NOASSERTION",
95
+ requiresAttribution: true,
96
+ trustTier: "manual-review",
97
+ lastVerifiedAt: null,
98
+ notes: "Manual-review candidate for technical diagram image-generation prompts.",
99
+ searchSeeds: ["diagram", "technical", "image generation", "prompt"],
100
+ defaultSearch: false,
101
+ },
102
+ ];
103
+
104
+ function publicSource(source) {
105
+ return {
106
+ id: source.id,
107
+ repo: source.repo,
108
+ owner: source.owner,
109
+ name: source.name,
110
+ displayName: source.displayName,
111
+ defaultRef: source.defaultRef,
112
+ allowedPaths: [...source.allowedPaths],
113
+ extensions: [...source.extensions],
114
+ sourceType: source.sourceType,
115
+ licenseSpdx: source.licenseSpdx,
116
+ requiresAttribution: source.requiresAttribution,
117
+ trustTier: source.trustTier,
118
+ lastVerifiedAt: source.lastVerifiedAt,
119
+ notes: source.notes,
120
+ searchSeeds: [...source.searchSeeds],
121
+ defaultSearch: source.defaultSearch,
122
+ };
123
+ }
124
+
125
+ export function listCuratedSources({ includeManualReview = true, defaultSearchOnly = false } = {}) {
126
+ return CURATED_SOURCES
127
+ .filter((source) => includeManualReview || source.trustTier !== "manual-review")
128
+ .filter((source) => !defaultSearchOnly || source.defaultSearch)
129
+ .map(publicSource);
130
+ }
131
+
132
+ export function getCuratedSource(sourceId) {
133
+ const source = CURATED_SOURCES.find((item) => item.id === sourceId);
134
+ return source ? publicSource(source) : null;
135
+ }
136
+
137
+ export function getDefaultSearchSources() {
138
+ return listCuratedSources({ includeManualReview: false, defaultSearchOnly: true });
139
+ }
@@ -0,0 +1,236 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import { promptImportError } from "./errors.js";
4
+
5
+ const REGISTRY_VERSION = 1;
6
+ const OWNER_REPO_RE = /^[A-Za-z0-9_.-]+$/;
7
+ const SUPPORTED_EXTENSIONS = new Set(["md", "markdown", "txt"]);
8
+
9
+ function registryFile(ctx) {
10
+ return ctx.config.storage.promptImportDiscoveryRegistryFile;
11
+ }
12
+
13
+ function emptyRegistry() {
14
+ return { version: REGISTRY_VERSION, updatedAt: null, candidates: {} };
15
+ }
16
+
17
+ function normalizeRepoFullName(repo) {
18
+ const value = String(repo || "").trim();
19
+ const parts = value.split("/");
20
+ if (parts.length !== 2 || !OWNER_REPO_RE.test(parts[0]) || !OWNER_REPO_RE.test(parts[1])) {
21
+ throw promptImportError("GITHUB_DISCOVERY_REVIEW_INVALID", "Review repo must be owner/repo");
22
+ }
23
+ return `${parts[0]}/${parts[1]}`;
24
+ }
25
+
26
+ function extensionForPath(path) {
27
+ const match = /\.([A-Za-z0-9]+)$/.exec(path);
28
+ return match?.[1]?.toLowerCase() ?? "";
29
+ }
30
+
31
+ function assertAllowedPath(path) {
32
+ const value = String(path || "").trim();
33
+ if (!value) {
34
+ throw promptImportError("GITHUB_DISCOVERY_REVIEW_INVALID", "Allowed path is required");
35
+ }
36
+ if (/^https?:\/\//i.test(value)) {
37
+ throw promptImportError("GITHUB_DISCOVERY_REVIEW_INVALID", "Allowed path must be repo-relative");
38
+ }
39
+ if (value.includes("\0") || /%00/i.test(value)) {
40
+ throw promptImportError("GITHUB_DISCOVERY_REVIEW_INVALID", "Allowed path contains a null byte");
41
+ }
42
+ if (/%2f|%5c/i.test(value)) {
43
+ throw promptImportError("GITHUB_DISCOVERY_REVIEW_INVALID", "Allowed path contains an encoded slash");
44
+ }
45
+ if (value.includes("\\") || value.split("/").includes("..")) {
46
+ throw promptImportError("GITHUB_DISCOVERY_REVIEW_INVALID", "Allowed path traversal is not allowed");
47
+ }
48
+ const clean = value.replace(/^\/+/, "");
49
+ const extension = extensionForPath(clean);
50
+ if (!SUPPORTED_EXTENSIONS.has(extension)) {
51
+ throw promptImportError("GITHUB_DISCOVERY_REVIEW_INVALID", "Allowed paths must be .md, .markdown, or .txt");
52
+ }
53
+ return clean;
54
+ }
55
+
56
+ function normalizeAllowedPaths(paths, limits) {
57
+ if (paths === undefined) return [];
58
+ if (!Array.isArray(paths)) {
59
+ throw promptImportError("GITHUB_DISCOVERY_REVIEW_INVALID", "allowedPaths must be an array");
60
+ }
61
+ if (paths.length > limits.maxRepoIndexFiles) {
62
+ throw promptImportError("GITHUB_DISCOVERY_REVIEW_INVALID", "Too many allowed paths", 413);
63
+ }
64
+ return [...new Set(paths.map(assertAllowedPath))];
65
+ }
66
+
67
+ function publicCandidate(candidate) {
68
+ return {
69
+ id: candidate.id,
70
+ repo: candidate.repo,
71
+ owner: candidate.owner,
72
+ name: candidate.name,
73
+ fullName: candidate.fullName,
74
+ htmlUrl: candidate.htmlUrl,
75
+ description: candidate.description,
76
+ defaultBranch: candidate.defaultBranch,
77
+ stars: candidate.stars,
78
+ forks: candidate.forks,
79
+ openIssues: candidate.openIssues,
80
+ updatedAt: candidate.updatedAt,
81
+ pushedAt: candidate.pushedAt,
82
+ licenseSpdx: candidate.licenseSpdx,
83
+ topics: Array.isArray(candidate.topics) ? [...candidate.topics] : [],
84
+ language: candidate.language,
85
+ score: candidate.score,
86
+ scoreReasons: Array.isArray(candidate.scoreReasons) ? [...candidate.scoreReasons] : [],
87
+ warnings: Array.isArray(candidate.warnings) ? [...candidate.warnings] : [],
88
+ status: candidate.status || "candidate",
89
+ query: candidate.query,
90
+ discoveredAt: candidate.discoveredAt,
91
+ reviewedAt: candidate.reviewedAt || null,
92
+ reviewNotes: candidate.reviewNotes || "",
93
+ approvedSource: candidate.approvedSource || null,
94
+ };
95
+ }
96
+
97
+ function reviewedSourceId(candidate) {
98
+ return `discovered-${candidate.fullName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}`;
99
+ }
100
+
101
+ export async function readDiscoveryRegistry(ctx) {
102
+ try {
103
+ const parsed = JSON.parse(await readFile(registryFile(ctx), "utf8"));
104
+ if (parsed.version !== REGISTRY_VERSION) return emptyRegistry();
105
+ return {
106
+ version: REGISTRY_VERSION,
107
+ updatedAt: parsed.updatedAt || null,
108
+ candidates: parsed.candidates || {},
109
+ };
110
+ } catch {
111
+ return emptyRegistry();
112
+ }
113
+ }
114
+
115
+ export async function writeDiscoveryRegistry(ctx, registry) {
116
+ const file = registryFile(ctx);
117
+ await mkdir(dirname(file), { recursive: true });
118
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
119
+ await writeFile(tmp, JSON.stringify(registry, null, 2));
120
+ await rename(tmp, file);
121
+ }
122
+
123
+ export async function listDiscoveryCandidates(ctx, filters = {}) {
124
+ const registry = await readDiscoveryRegistry(ctx);
125
+ const status = typeof filters.status === "string" ? filters.status : null;
126
+ return Object.values(registry.candidates)
127
+ .filter((candidate) => !status || candidate.status === status)
128
+ .map(publicCandidate)
129
+ .sort((a, b) => b.score - a.score || a.fullName.localeCompare(b.fullName));
130
+ }
131
+
132
+ export async function upsertDiscoveryCandidates(ctx, candidates) {
133
+ const registry = await readDiscoveryRegistry(ctx);
134
+ const now = new Date().toISOString();
135
+ for (const candidate of candidates) {
136
+ const fullName = normalizeRepoFullName(candidate.fullName || candidate.repo);
137
+ const existing = registry.candidates[fullName];
138
+ registry.candidates[fullName] = {
139
+ ...existing,
140
+ ...candidate,
141
+ fullName,
142
+ repo: fullName,
143
+ status: existing?.status || candidate.status || "candidate",
144
+ discoveredAt: existing?.discoveredAt || candidate.discoveredAt || now,
145
+ };
146
+ }
147
+ registry.updatedAt = now;
148
+ await writeDiscoveryRegistry(ctx, registry);
149
+ return Object.values(registry.candidates).map(publicCandidate);
150
+ }
151
+
152
+ export function reviewedSourceFromCandidate(candidate) {
153
+ const [owner, name] = String(candidate.fullName || candidate.repo).split("/");
154
+ const allowedPaths = Array.isArray(candidate.allowedPaths) ? candidate.allowedPaths : [];
155
+ return {
156
+ id: reviewedSourceId(candidate),
157
+ repo: `${owner}/${name}`,
158
+ owner,
159
+ name,
160
+ displayName: candidate.name || name,
161
+ defaultRef: candidate.defaultBranch || "main",
162
+ allowedPaths,
163
+ extensions: ["md", "markdown", "txt"],
164
+ sourceType: "discovered",
165
+ licenseSpdx: candidate.licenseSpdx || "NOASSERTION",
166
+ requiresAttribution: true,
167
+ trustTier: "reviewed",
168
+ lastVerifiedAt: candidate.reviewedAt || null,
169
+ notes: candidate.reviewNotes || candidate.description || "Reviewed GitHub discovery source.",
170
+ searchSeeds: [candidate.name, candidate.description, ...(candidate.topics || [])].filter(Boolean).slice(0, 8),
171
+ defaultSearch: Boolean(candidate.defaultSearch && allowedPaths.length > 0 && !String(candidate.defaultBranch || "").includes("/")),
172
+ };
173
+ }
174
+
175
+ export async function reviewDiscoveryCandidate(ctx, payload) {
176
+ const limits = {
177
+ maxRepoIndexFiles: ctx.config.limits.promptImportMaxRepoIndexFiles,
178
+ };
179
+ const repo = normalizeRepoFullName(payload?.repo);
180
+ const status = String(payload?.status || "");
181
+ if (!["approved", "rejected"].includes(status)) {
182
+ throw promptImportError("GITHUB_DISCOVERY_REVIEW_INVALID", "Review status must be approved or rejected");
183
+ }
184
+
185
+ const registry = await readDiscoveryRegistry(ctx);
186
+ const candidate = registry.candidates[repo];
187
+ if (!candidate) {
188
+ throw promptImportError("GITHUB_DISCOVERY_SOURCE_NOT_FOUND", "Discovery candidate was not found", 404);
189
+ }
190
+
191
+ const allowedPaths = normalizeAllowedPaths(payload?.allowedPaths, limits);
192
+ const warnings = [...(candidate.warnings || [])];
193
+ const defaultBranch = String(candidate.defaultBranch || "");
194
+ let defaultSearch = Boolean(payload?.defaultSearch);
195
+
196
+ if (status !== "approved" || allowedPaths.length === 0) defaultSearch = false;
197
+ if (defaultBranch.includes("/")) {
198
+ defaultSearch = false;
199
+ warnings.push("discovery-default-branch-unsupported");
200
+ }
201
+ if (status === "approved" && allowedPaths.length === 0) {
202
+ warnings.push("discovery-requires-paths");
203
+ }
204
+
205
+ const reviewed = {
206
+ ...candidate,
207
+ allowedPaths,
208
+ status,
209
+ warnings: [...new Set(warnings)],
210
+ defaultSearch,
211
+ reviewedAt: new Date().toISOString(),
212
+ reviewNotes: typeof payload?.reviewNotes === "string" ? payload.reviewNotes.slice(0, 500) : "",
213
+ };
214
+ reviewed.approvedSource = status === "approved" ? reviewedSourceFromCandidate(reviewed) : null;
215
+ registry.candidates[repo] = reviewed;
216
+ registry.updatedAt = reviewed.reviewedAt;
217
+ await writeDiscoveryRegistry(ctx, registry);
218
+ return { candidate: publicCandidate(reviewed), source: reviewed.approvedSource, warnings: reviewed.warnings };
219
+ }
220
+
221
+ export async function listReviewedDiscoverySources(ctx, { defaultSearchOnly = false } = {}) {
222
+ const registry = await readDiscoveryRegistry(ctx);
223
+ return Object.values(registry.candidates)
224
+ .filter((candidate) => candidate.status === "approved" && candidate.approvedSource)
225
+ .map((candidate) => candidate.approvedSource)
226
+ .filter((source) => !defaultSearchOnly || source.defaultSearch);
227
+ }
228
+
229
+ export async function getReviewedDiscoverySource(ctx, sourceId) {
230
+ const sources = await listReviewedDiscoverySources(ctx);
231
+ return sources.find((source) => source.id === sourceId) || null;
232
+ }
233
+
234
+ export async function getDefaultReviewedDiscoverySources(ctx) {
235
+ return listReviewedDiscoverySources(ctx, { defaultSearchOnly: true });
236
+ }