@gmickel/gno 1.22.0 → 1.23.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 (42) hide show
  1. package/README.md +16 -1
  2. package/assets/skill/SKILL.md +15 -0
  3. package/package.json +1 -1
  4. package/spec/cli.md +36 -20
  5. package/spec/evals-agentic.md +35 -0
  6. package/spec/evals.md +6 -0
  7. package/spec/mcp.md +18 -0
  8. package/spec/output-schemas/query-diagnose-v1.schema.json +123 -0
  9. package/spec/output-schemas/query-diagnose.schema.json +89 -2
  10. package/src/app/context-runtime-types.ts +3 -0
  11. package/src/app/context-runtime.ts +1 -0
  12. package/src/app/context-surface.ts +4 -2
  13. package/src/cli/commands/ask.ts +31 -20
  14. package/src/cli/commands/context-build.ts +17 -7
  15. package/src/cli/commands/query.ts +58 -37
  16. package/src/cli/commands/search.ts +29 -19
  17. package/src/cli/commands/vsearch.ts +31 -22
  18. package/src/cli/options.ts +39 -0
  19. package/src/cli/program.ts +48 -0
  20. package/src/config/defaults.ts +10 -1
  21. package/src/config/types.ts +71 -0
  22. package/src/core/project-affinity-surface.ts +114 -0
  23. package/src/core/project-affinity.ts +330 -0
  24. package/src/core/validation.ts +20 -1
  25. package/src/mcp/tools/ask.ts +10 -1
  26. package/src/mcp/tools/context.ts +18 -0
  27. package/src/mcp/tools/index.ts +13 -2
  28. package/src/mcp/tools/query.ts +12 -0
  29. package/src/mcp/tools/search.ts +7 -0
  30. package/src/mcp/tools/vsearch.ts +7 -0
  31. package/src/pipeline/diagnose.ts +48 -3
  32. package/src/pipeline/explain.ts +54 -13
  33. package/src/pipeline/hybrid.ts +100 -59
  34. package/src/pipeline/project-affinity.ts +162 -0
  35. package/src/pipeline/search.ts +76 -10
  36. package/src/pipeline/types.ts +9 -0
  37. package/src/pipeline/vsearch.ts +117 -91
  38. package/src/sdk/client.ts +80 -20
  39. package/src/sdk/index.ts +2 -0
  40. package/src/sdk/types.ts +20 -7
  41. package/src/serve/context-capsule.ts +18 -1
  42. package/src/serve/routes/api.ts +69 -0
@@ -0,0 +1,330 @@
1
+ /**
2
+ * Trusted project-root resolution for project-aware retrieval affinity.
3
+ *
4
+ * This module resolves local roots only. Remote hints remain opaque and never
5
+ * trigger filesystem probes. Returned metadata is path-redacted; ranking is a
6
+ * separate concern.
7
+ *
8
+ * @module src/core/project-affinity
9
+ */
10
+
11
+ // node:fs/promises for directory stat/realpath (no Bun directory equivalent)
12
+ import { realpath, stat } from "node:fs/promises";
13
+ // node:path for path utilities (no Bun path utils)
14
+ import { dirname, join, relative, sep } from "node:path";
15
+
16
+ import type {
17
+ Collection,
18
+ ProjectAffinityInput,
19
+ ProjectAffinityRoot,
20
+ TrustedProjectRootSource,
21
+ } from "../config/types";
22
+
23
+ import { isCanonicalPathContained } from "./validation";
24
+
25
+ export type ProjectAffinityZeroReason =
26
+ | "no_collection_match"
27
+ | "root_unavailable"
28
+ | "untrusted_remote_hint";
29
+
30
+ export type ProjectAffinityRelation =
31
+ | "collection_contains_root"
32
+ | "exact"
33
+ | "root_contains_collection";
34
+
35
+ export interface ProjectAffinityMatch {
36
+ collection: string;
37
+ collectionAlias: string;
38
+ distance: number;
39
+ relation: ProjectAffinityRelation;
40
+ rootAlias: string;
41
+ source: TrustedProjectRootSource;
42
+ }
43
+
44
+ export interface ProjectAffinityRootMetadata {
45
+ collectionAliases: string[];
46
+ reason: ProjectAffinityZeroReason | null;
47
+ repositoryRootDiscovered: boolean;
48
+ rootAlias: string;
49
+ source: ProjectAffinityRoot["source"];
50
+ status: "matched" | "zero";
51
+ }
52
+
53
+ export interface ProjectAffinityResolution {
54
+ matches: ProjectAffinityMatch[];
55
+ roots: ProjectAffinityRootMetadata[];
56
+ }
57
+
58
+ export interface ProjectAffinityResolverDependencies {
59
+ canonicalizePath: (path: string) => Promise<string>;
60
+ discoverRepositoryRoot: (path: string) => Promise<string | null>;
61
+ }
62
+
63
+ /**
64
+ * Trust is supplied by the invoking surface, never inferred from payload data.
65
+ */
66
+ export interface ProjectAffinityResolverContext {
67
+ channel: "local" | "remote";
68
+ }
69
+
70
+ interface CanonicalCollection {
71
+ alias: string;
72
+ name: string;
73
+ path: string;
74
+ }
75
+
76
+ interface CanonicalTrustedRoot {
77
+ path: string;
78
+ repositoryRootDiscovered: boolean;
79
+ rootAlias: string;
80
+ source: TrustedProjectRootSource;
81
+ }
82
+
83
+ const alias = (namespace: "collection" | "root", value: string): string => {
84
+ const hash = new Bun.CryptoHasher("sha256")
85
+ .update(`${namespace}\0${value}`)
86
+ .digest("hex")
87
+ .slice(0, 12);
88
+ return `${namespace}_${hash}`;
89
+ };
90
+
91
+ const defaultCanonicalizePath = (path: string): Promise<string> =>
92
+ realpath(path);
93
+
94
+ const isDirectoryOrFile = async (path: string): Promise<boolean> => {
95
+ try {
96
+ await stat(path);
97
+ return true;
98
+ } catch {
99
+ return false;
100
+ }
101
+ };
102
+
103
+ const defaultDiscoverRepositoryRoot = async (
104
+ startingPath: string
105
+ ): Promise<string | null> => {
106
+ let current = startingPath;
107
+ while (true) {
108
+ if (await isDirectoryOrFile(join(current, ".git"))) {
109
+ return current;
110
+ }
111
+ const parent = dirname(current);
112
+ if (parent === current) {
113
+ return null;
114
+ }
115
+ current = parent;
116
+ }
117
+ };
118
+
119
+ const pathDistance = (parent: string, child: string): number => {
120
+ const nestedPath = relative(parent, child);
121
+ if (nestedPath === "") {
122
+ return 0;
123
+ }
124
+ return nestedPath.split(sep).filter(Boolean).length;
125
+ };
126
+
127
+ const describeRelationship = (
128
+ collectionPath: string,
129
+ rootPath: string
130
+ ): Pick<ProjectAffinityMatch, "distance" | "relation"> | null => {
131
+ if (collectionPath === rootPath) {
132
+ return { distance: 0, relation: "exact" };
133
+ }
134
+ if (isCanonicalPathContained(collectionPath, rootPath)) {
135
+ return {
136
+ distance: pathDistance(collectionPath, rootPath),
137
+ relation: "collection_contains_root",
138
+ };
139
+ }
140
+ if (isCanonicalPathContained(rootPath, collectionPath)) {
141
+ return {
142
+ distance: pathDistance(rootPath, collectionPath),
143
+ relation: "root_contains_collection",
144
+ };
145
+ }
146
+ return null;
147
+ };
148
+
149
+ const canonicalizeCollections = async (
150
+ collections: readonly Collection[],
151
+ canonicalizePath: ProjectAffinityResolverDependencies["canonicalizePath"]
152
+ ): Promise<CanonicalCollection[]> => {
153
+ const resolved = await Promise.all(
154
+ collections.map(async (collection): Promise<CanonicalCollection | null> => {
155
+ try {
156
+ const path = await canonicalizePath(collection.path);
157
+ return {
158
+ alias: alias("collection", collection.name),
159
+ name: collection.name,
160
+ path,
161
+ };
162
+ } catch {
163
+ return null;
164
+ }
165
+ })
166
+ );
167
+ return resolved
168
+ .filter((collection): collection is CanonicalCollection =>
169
+ Boolean(collection)
170
+ )
171
+ .sort((left, right) => left.name.localeCompare(right.name));
172
+ };
173
+
174
+ const canonicalizeTrustedRoot = async (
175
+ root: Extract<ProjectAffinityRoot, { path: string }>,
176
+ dependencies: ProjectAffinityResolverDependencies
177
+ ): Promise<CanonicalTrustedRoot | null> => {
178
+ let canonicalPath: string;
179
+ try {
180
+ canonicalPath = await dependencies.canonicalizePath(root.path);
181
+ } catch {
182
+ return null;
183
+ }
184
+
185
+ let repositoryRootDiscovered = false;
186
+ if (root.source === "cli_cwd" || root.source === "cli_worktree") {
187
+ let discovered: string | null = null;
188
+ try {
189
+ discovered = await dependencies.discoverRepositoryRoot(canonicalPath);
190
+ } catch {
191
+ // Repository discovery is opportunistic; the trusted canonical cwd
192
+ // remains a valid affinity root when discovery is unavailable.
193
+ }
194
+ if (discovered) {
195
+ try {
196
+ canonicalPath = await dependencies.canonicalizePath(discovered);
197
+ repositoryRootDiscovered = true;
198
+ } catch {
199
+ return null;
200
+ }
201
+ }
202
+ }
203
+
204
+ return {
205
+ path: canonicalPath,
206
+ repositoryRootDiscovered,
207
+ rootAlias: alias("root", canonicalPath),
208
+ source: root.source,
209
+ };
210
+ };
211
+
212
+ const zeroMetadata = (
213
+ root: ProjectAffinityRoot,
214
+ reason: ProjectAffinityZeroReason,
215
+ source: ProjectAffinityRoot["source"] = root.source
216
+ ): ProjectAffinityRootMetadata => ({
217
+ collectionAliases: [],
218
+ reason,
219
+ repositoryRootDiscovered: false,
220
+ rootAlias: alias(
221
+ "root",
222
+ root.source === "remote_hint" ? root.hint : root.path
223
+ ),
224
+ source,
225
+ status: "zero",
226
+ });
227
+
228
+ const relationOrder: Record<ProjectAffinityRelation, number> = {
229
+ exact: 0,
230
+ collection_contains_root: 1,
231
+ root_contains_collection: 2,
232
+ };
233
+
234
+ const compareMatches = (
235
+ left: ProjectAffinityMatch,
236
+ right: ProjectAffinityMatch
237
+ ): number =>
238
+ relationOrder[left.relation] - relationOrder[right.relation] ||
239
+ left.distance - right.distance ||
240
+ left.collection.localeCompare(right.collection) ||
241
+ left.rootAlias.localeCompare(right.rootAlias);
242
+
243
+ export async function resolveProjectAffinity(
244
+ input: ProjectAffinityInput,
245
+ collections: readonly Collection[],
246
+ context: ProjectAffinityResolverContext,
247
+ overrides: Partial<ProjectAffinityResolverDependencies> = {}
248
+ ): Promise<ProjectAffinityResolution> {
249
+ if (context.channel === "remote") {
250
+ return {
251
+ matches: [],
252
+ roots: input.roots.map((root) =>
253
+ zeroMetadata(root, "untrusted_remote_hint", "remote_hint")
254
+ ),
255
+ };
256
+ }
257
+
258
+ const dependencies: ProjectAffinityResolverDependencies = {
259
+ canonicalizePath: overrides.canonicalizePath ?? defaultCanonicalizePath,
260
+ discoverRepositoryRoot:
261
+ overrides.discoverRepositoryRoot ?? defaultDiscoverRepositoryRoot,
262
+ };
263
+ const trustedRoots = input.roots.filter(
264
+ (root): root is Extract<ProjectAffinityRoot, { path: string }> =>
265
+ root.source !== "remote_hint"
266
+ );
267
+ const canonicalCollections =
268
+ trustedRoots.length === 0
269
+ ? []
270
+ : await canonicalizeCollections(
271
+ collections,
272
+ dependencies.canonicalizePath
273
+ );
274
+ const matches: ProjectAffinityMatch[] = [];
275
+ const roots: ProjectAffinityRootMetadata[] = [];
276
+
277
+ for (const root of input.roots) {
278
+ if (root.source === "remote_hint") {
279
+ roots.push(zeroMetadata(root, "untrusted_remote_hint"));
280
+ continue;
281
+ }
282
+
283
+ const canonicalRoot = await canonicalizeTrustedRoot(root, dependencies);
284
+ if (!canonicalRoot) {
285
+ roots.push(zeroMetadata(root, "root_unavailable"));
286
+ continue;
287
+ }
288
+
289
+ const rootMatches = canonicalCollections
290
+ .map((collection): ProjectAffinityMatch | null => {
291
+ const relationship = describeRelationship(
292
+ collection.path,
293
+ canonicalRoot.path
294
+ );
295
+ return relationship
296
+ ? {
297
+ collection: collection.name,
298
+ collectionAlias: collection.alias,
299
+ rootAlias: canonicalRoot.rootAlias,
300
+ source: canonicalRoot.source,
301
+ ...relationship,
302
+ }
303
+ : null;
304
+ })
305
+ .filter((match): match is ProjectAffinityMatch => Boolean(match))
306
+ .sort(compareMatches);
307
+
308
+ if (rootMatches.length === 0) {
309
+ roots.push({
310
+ ...zeroMetadata(root, "no_collection_match"),
311
+ repositoryRootDiscovered: canonicalRoot.repositoryRootDiscovered,
312
+ rootAlias: canonicalRoot.rootAlias,
313
+ });
314
+ continue;
315
+ }
316
+
317
+ matches.push(...rootMatches);
318
+ roots.push({
319
+ collectionAliases: rootMatches.map((match) => match.collectionAlias),
320
+ reason: null,
321
+ repositoryRootDiscovered: canonicalRoot.repositoryRootDiscovered,
322
+ rootAlias: canonicalRoot.rootAlias,
323
+ source: root.source,
324
+ status: "matched",
325
+ });
326
+ }
327
+
328
+ matches.sort(compareMatches);
329
+ return { matches, roots };
330
+ }
@@ -9,7 +9,7 @@ import { realpath } from "node:fs/promises";
9
9
  // node:os for homedir (no Bun os utils)
10
10
  import { homedir } from "node:os";
11
11
  // node:path for path utils (no Bun path utils)
12
- import { isAbsolute, join, posix as pathPosix } from "node:path";
12
+ import { isAbsolute, join, posix as pathPosix, relative, sep } from "node:path";
13
13
 
14
14
  import { toAbsolutePath } from "../config/paths";
15
15
 
@@ -58,6 +58,25 @@ export function validateRelPath(relPath: string): string {
58
58
  return normalized;
59
59
  }
60
60
 
61
+ /**
62
+ * Return whether candidate is equal to or nested beneath parent.
63
+ *
64
+ * Inputs must already be canonical absolute paths. `relative()` keeps this
65
+ * segment-safe, unlike string-prefix checks (`/project` vs `/project-old`).
66
+ */
67
+ export function isCanonicalPathContained(
68
+ parent: string,
69
+ candidate: string
70
+ ): boolean {
71
+ const relativePath = relative(parent, candidate);
72
+ return (
73
+ relativePath === "" ||
74
+ (relativePath !== ".." &&
75
+ !relativePath.startsWith(`..${sep}`) &&
76
+ !isAbsolute(relativePath))
77
+ );
78
+ }
79
+
61
80
  export async function validateCollectionRoot(
62
81
  inputPath: string
63
82
  ): Promise<string> {
@@ -8,6 +8,7 @@ import type { ToolContext } from "../server";
8
8
  import type { ToolResult } from "./index";
9
9
 
10
10
  import { buildVerifiedAsk } from "../../app/verified-ask";
11
+ import { resolveRemoteProjectAffinity } from "../../core/project-affinity-surface";
11
12
  import {
12
13
  finishRetrievalTraceAfterError,
13
14
  retrievalTraceFilters,
@@ -30,6 +31,7 @@ const queryModeSchema = z
30
31
  export const askInputSchema = z
31
32
  .object({
32
33
  query: z.string().trim().min(1),
34
+ projectHints: z.array(z.string()).max(16).optional(),
33
35
  verify: z.literal(true),
34
36
  collection: z.string().optional(),
35
37
  limit: z.number().int().min(1).max(100).default(5),
@@ -153,8 +155,14 @@ export const handleAsk = (
153
155
  );
154
156
  if (!normalized.ok) throw new Error(normalized.error.message);
155
157
  const query = normalized.value.query;
158
+ const { projectHints, ...askInput } = args;
159
+ const projectAffinity = await resolveRemoteProjectAffinity(
160
+ context.config,
161
+ projectHints
162
+ );
156
163
  const options = {
157
- ...args,
164
+ ...askInput,
165
+ projectAffinity,
158
166
  queryModes:
159
167
  normalized.value.queryModes.length > 0
160
168
  ? normalized.value.queryModes
@@ -210,6 +218,7 @@ export const handleAsk = (
210
218
  embedPort: modelPorts.embedPort,
211
219
  rerankPort: modelPorts.rerankPort,
212
220
  genPort: modelPorts.genPort,
221
+ projectAffinity,
213
222
  traceSession,
214
223
  });
215
224
  const finished = await traceSession?.finish(
@@ -25,6 +25,11 @@ import {
25
25
  parseContextVerifySurfaceInput,
26
26
  } from "../../app/context-surface";
27
27
  import { createNonTtyProgressRenderer } from "../../cli/progress";
28
+ import { ContextCapsuleContractError } from "../../core/context-capsule";
29
+ import {
30
+ ProjectAffinityInputError,
31
+ resolveRemoteProjectAffinity,
32
+ } from "../../core/project-affinity-surface";
28
33
  import {
29
34
  finishRetrievalTraceAfterError,
30
35
  startRetrievalTraceRequest,
@@ -224,6 +229,18 @@ export const handleContext = (
224
229
  null;
225
230
  let traceSession: RetrievalTraceSession | undefined;
226
231
  try {
232
+ let projectAffinity;
233
+ try {
234
+ projectAffinity = await resolveRemoteProjectAffinity(
235
+ context.config,
236
+ parsed.projectHints
237
+ );
238
+ } catch (error) {
239
+ if (error instanceof ProjectAffinityInputError) {
240
+ throw new ContextCapsuleContractError("invalid_input", error.message);
241
+ }
242
+ throw error;
243
+ }
227
244
  const traceStart = await startRetrievalTraceRequest({
228
245
  store: context.store,
229
246
  config: context.config,
@@ -261,6 +278,7 @@ export const handleContext = (
261
278
  vectorIndex: modelPorts?.vectorIndex ?? null,
262
279
  embedPort: modelPorts?.embedPort ?? null,
263
280
  rerankPort: modelPorts?.rerankPort ?? null,
281
+ projectAffinity,
264
282
  traceSession,
265
283
  });
266
284
  const finalized = await traceSession?.finish("completed");
@@ -131,13 +131,22 @@ export const MCP_WRITE_TOOL_NAMES = new Set([
131
131
  // Shared Input Schemas
132
132
  // ─────────────────────────────────────────────────────────────────────────────
133
133
 
134
- const searchInputSchema = z.object({
134
+ const projectHintsInputSchema = z
135
+ .array(z.string())
136
+ .max(16)
137
+ .optional()
138
+ .describe(
139
+ "Opaque caller project hints for cross-surface parity; remote hints never inspect server paths"
140
+ );
141
+
142
+ export const searchInputSchema = z.object({
135
143
  query: z
136
144
  .string()
137
145
  .min(1, "Query cannot be empty")
138
146
  .describe(
139
147
  "Exact keyword, identifier, filename, error text, or phrase to match with BM25"
140
148
  ),
149
+ projectHints: projectHintsInputSchema,
141
150
  collection: z
142
151
  .string()
143
152
  .optional()
@@ -378,13 +387,14 @@ const duplicateNoteInputSchema = z.object({
378
387
  name: z.string().optional(),
379
388
  });
380
389
 
381
- const vsearchInputSchema = z.object({
390
+ export const vsearchInputSchema = z.object({
382
391
  query: z
383
392
  .string()
384
393
  .min(1, "Query cannot be empty")
385
394
  .describe(
386
395
  "Natural-language concept to match semantically; use gno_search for exact error text or identifiers"
387
396
  ),
397
+ projectHints: projectHintsInputSchema,
388
398
  collection: z
389
399
  .string()
390
400
  .optional()
@@ -455,6 +465,7 @@ export const queryInputSchema = z.object({
455
465
  .describe(
456
466
  "Primary user query; combine with intent or queryModes for ambiguous requests"
457
467
  ),
468
+ projectHints: projectHintsInputSchema,
458
469
  collection: z
459
470
  .string()
460
471
  .optional()
@@ -26,6 +26,7 @@ import {
26
26
  normalizeContentTypes,
27
27
  } from "../../config";
28
28
  import { resolveDepthPolicy } from "../../core/depth-policy";
29
+ import { resolveRemoteProjectAffinity } from "../../core/project-affinity-surface";
29
30
  import {
30
31
  finishRetrievalTraceAfterError,
31
32
  retrievalTraceFilters,
@@ -49,6 +50,7 @@ import { normalizeTagFilters, runTool, type ToolResult } from "./index";
49
50
 
50
51
  interface QueryInput {
51
52
  query: string;
53
+ projectHints?: string[];
52
54
  collection?: string;
53
55
  limit?: number;
54
56
  minScore?: number;
@@ -227,6 +229,10 @@ export function handleQuery(
227
229
  hasStructuredModes,
228
230
  });
229
231
  const { noExpand, noRerank } = depthPolicy;
232
+ const projectAffinity = await resolveRemoteProjectAffinity(
233
+ ctx.config,
234
+ args.projectHints
235
+ );
230
236
  const expandUri =
231
237
  !noExpand && !hasStructuredModes
232
238
  ? resolveModelUri(ctx.config, "expand", undefined, args.collection)
@@ -253,6 +259,7 @@ export function handleQuery(
253
259
  queryModes,
254
260
  tagsAll: normalizeTagFilters(args.tagsAll),
255
261
  tagsAny: normalizeTagFilters(args.tagsAny),
262
+ projectAffinity,
256
263
  };
257
264
 
258
265
  try {
@@ -440,6 +447,10 @@ export function handleQueryDiagnose(
440
447
  hasStructuredModes,
441
448
  });
442
449
  const { noExpand, noRerank } = depthPolicy;
450
+ const projectAffinity = await resolveRemoteProjectAffinity(
451
+ ctx.config,
452
+ args.projectHints
453
+ );
443
454
 
444
455
  if (!args.fast) {
445
456
  const embedResult = await llm.createEmbeddingPort(embedUri, {
@@ -524,6 +535,7 @@ export function handleQueryDiagnose(
524
535
  queryModes,
525
536
  tagsAll: normalizeTagFilters(args.tagsAll),
526
537
  tagsAny: normalizeTagFilters(args.tagsAny),
538
+ projectAffinity,
527
539
  contentTypeRules,
528
540
  contentTypeRulesFingerprint:
529
541
  fingerprintContentTypeRules(contentTypeRules),
@@ -11,6 +11,7 @@ import type { SearchResult, SearchResults } from "../../pipeline/types";
11
11
  import type { ToolContext } from "../server";
12
12
 
13
13
  import { decorateUriForIndex, parseUri } from "../../app/constants";
14
+ import { resolveRemoteProjectAffinity } from "../../core/project-affinity-surface";
14
15
  import {
15
16
  finishRetrievalTraceAfterError,
16
17
  retrievalTraceFilters,
@@ -22,6 +23,7 @@ import { normalizeTagFilters, runTool, type ToolResult } from "./index";
22
23
 
23
24
  interface SearchInput {
24
25
  query: string;
26
+ projectHints?: string[];
25
27
  collection?: string;
26
28
  limit?: number;
27
29
  minScore?: number;
@@ -113,6 +115,10 @@ export function handleSearch(
113
115
  }
114
116
  }
115
117
 
118
+ const projectAffinity = await resolveRemoteProjectAffinity(
119
+ ctx.config,
120
+ args.projectHints
121
+ );
116
122
  const options = {
117
123
  limit: args.limit ?? 5,
118
124
  minScore: args.minScore,
@@ -126,6 +132,7 @@ export function handleSearch(
126
132
  author: args.author,
127
133
  tagsAll: normalizeTagFilters(args.tagsAll),
128
134
  tagsAny: normalizeTagFilters(args.tagsAny),
135
+ projectAffinity,
129
136
  };
130
137
  let traceSession: RetrievalTraceSession | undefined;
131
138
  try {
@@ -12,6 +12,7 @@ import type { ToolContext } from "../server";
12
12
 
13
13
  import { decorateUriForIndex, parseUri } from "../../app/constants";
14
14
  import { createNonTtyProgressRenderer } from "../../cli/progress";
15
+ import { resolveRemoteProjectAffinity } from "../../core/project-affinity-surface";
15
16
  import {
16
17
  finishRetrievalTraceAfterError,
17
18
  retrievalTraceFilters,
@@ -34,6 +35,7 @@ import { normalizeTagFilters, runTool, type ToolResult } from "./index";
34
35
 
35
36
  interface VsearchInput {
36
37
  query: string;
38
+ projectHints?: string[];
37
39
  collection?: string;
38
40
  limit?: number;
39
41
  minScore?: number;
@@ -135,6 +137,10 @@ export function handleVsearch(
135
137
  undefined,
136
138
  args.collection
137
139
  );
140
+ const projectAffinity = await resolveRemoteProjectAffinity(
141
+ ctx.config,
142
+ args.projectHints
143
+ );
138
144
  const options = {
139
145
  limit: args.limit ?? 5,
140
146
  minScore: args.minScore,
@@ -147,6 +153,7 @@ export function handleVsearch(
147
153
  author: args.author,
148
154
  tagsAll: normalizeTagFilters(args.tagsAll),
149
155
  tagsAny: normalizeTagFilters(args.tagsAny),
156
+ projectAffinity,
150
157
  };
151
158
  let traceSession: RetrievalTraceSession | undefined;
152
159
  const traceStart = await startRetrievalTraceRequest({
@@ -19,6 +19,12 @@ import { resolveDocRef } from "../core/ref-parser";
19
19
  import { err, ok } from "../store/types";
20
20
  import { evaluateQueryTargetFilters } from "./filters";
21
21
  import { searchHybrid } from "./hybrid";
22
+ import {
23
+ getProjectAffinityMetadata,
24
+ type ProjectAffinityScoringInput,
25
+ type ProjectAffinityScoreMetadata,
26
+ scoreProjectAffinity,
27
+ } from "./project-affinity";
22
28
 
23
29
  export type QueryDiagnoseTargetStatus =
24
30
  | "not_found"
@@ -46,7 +52,7 @@ export interface QueryDiagnoseStage {
46
52
  }
47
53
 
48
54
  export interface QueryDiagnoseResult {
49
- schemaVersion: "1.0";
55
+ schemaVersion: "1.0" | "1.1";
50
56
  query: string;
51
57
  target: {
52
58
  ref: string;
@@ -65,6 +71,7 @@ export interface QueryDiagnoseResult {
65
71
  filterReasons: string[];
66
72
  };
67
73
  stages: QueryDiagnoseStage[];
74
+ affinity?: ProjectAffinityScoreMetadata;
68
75
  chunk: {
69
76
  seq: number | null;
70
77
  startLine: number | null;
@@ -155,6 +162,15 @@ function findTargetCandidate(
155
162
  );
156
163
  }
157
164
 
165
+ const hasTrustedProjectAffinityInput = (
166
+ input: ProjectAffinityScoringInput | undefined
167
+ ): boolean =>
168
+ input?.enabled !== false &&
169
+ Boolean(
170
+ input?.resolution.matches.length ||
171
+ input?.resolution.roots.some((root) => root.source !== "remote_hint")
172
+ );
173
+
158
174
  export async function diagnoseQueryTarget(
159
175
  deps: HybridSearchDeps,
160
176
  query: string,
@@ -276,8 +292,28 @@ export async function diagnoseQueryTarget(
276
292
  chunks.find((chunk) => chunk.seq === firstMatched?.seq) ??
277
293
  chunks[0] ??
278
294
  null;
295
+ const targetResult = searchResult.value.results.find(
296
+ (result) => result.uri === doc.uri
297
+ );
298
+ const lastMatched = trace?.stages
299
+ .toReversed()
300
+ .flatMap((stage) => stage.candidates)
301
+ .find(
302
+ (candidate) =>
303
+ candidate.mirrorHash === doc.mirrorHash && targetSeqs.has(candidate.seq)
304
+ );
305
+ const affinity =
306
+ (targetResult ? getProjectAffinityMetadata(targetResult) : undefined) ??
307
+ (lastMatched && options.projectAffinity
308
+ ? scoreProjectAffinity(
309
+ lastMatched.score,
310
+ doc.collection,
311
+ options.projectAffinity,
312
+ { kind: "hybrid_blended", score: lastMatched.score }
313
+ )
314
+ : null);
279
315
 
280
- return ok({
316
+ const baseResult: QueryDiagnoseResult = {
281
317
  ...buildBaseResult(query, options.target, "diagnosed", doc, {
282
318
  graphHints,
283
319
  chunkCount: chunks.length,
@@ -298,5 +334,14 @@ export async function diagnoseQueryTarget(
298
334
  totalResults: searchResult.value.meta.totalResults,
299
335
  queryModes: searchResult.value.meta.queryModes,
300
336
  },
301
- });
337
+ };
338
+ return ok(
339
+ affinity && hasTrustedProjectAffinityInput(options.projectAffinity)
340
+ ? {
341
+ ...baseResult,
342
+ schemaVersion: "1.1",
343
+ affinity,
344
+ }
345
+ : baseResult
346
+ );
302
347
  }