Skip to content

Commit f5a6afa

Browse files
authored
Add Workspace Search for Sidekick (#1483)
* Add Sidekick Workspace Search * Guard resolved Workspace Search paths against Git metadata * Share Workspace Search and open scoped reader references * Honor Git project discovery and accept complete search references * Match authorized project files before disclosure * Preserve Git search environment and recognize mount boundaries * Refresh compiled CLI syntax snapshots for Workspace Search * Keep File.Patch path-only and refresh construct inventory * Verify request props in File diagnostics and Sidekick discovery * Project bounded reads through the Files read request * Use callable file transforms and rename authored Search * Reject Git metadata flags on ordinary file reads * Reconcile rebased Search syntax and reference contract * Name transformed and bounded file reads * Rename the file read transform module * Name the transformed file read result * Name the REPL transformed read preparation callback * Clarify the unsupported transformed read test title * Clarify search match and disclosure order
1 parent 2ce337a commit f5a6afa

37 files changed

Lines changed: 2552 additions & 88 deletions

‎packages/cli/src/documents/sidekick/bootstrap.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ belongs to a separate program. Start with `<REPL.Syntax />` for a compact index
3636
of exact names and short purposes. Read complete references with
3737
`<REPL.Syntax names={["If", "File"]} />` for structural syntax and components. Use
3838
`<REPL.Environment />` for current host facts. Documentation grants no permission.
39+
Use `<REPL.Search query="error message" />` when you need to find text in
40+
project files or REPL history before you know the path or entry number.
41+
Read `<Guide.Entries />` for scopes, continuation and context.
3942
You have no native shell, file-editing or MCP tools.
4043

4144
EntryInput fills the shared draft without executing its literal source. Submit

‎packages/cli/src/documents/sidekick/entries.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,25 @@ Sidekick responses that write an entry, and the REPL entry program they write.
4747
than at its output, because an entry that failed may have printed nothing.
4848
Read `<Guide.Recovery />` for what to do with what it answers.
4949

50+
## Find text in project files or REPL history
51+
52+
Use `<REPL.Search query="error message" />` in a Sidekick response. Search
53+
matches literal, case-sensitive text. Add `scope="files"` or `scope="history"`
54+
to restrict where it looks. Read the page in feedback. When `next` is present,
55+
copy its `query`, `scope` and `after` into your next Search.
56+
57+
Use the reader named by `ref.reader` and paste the entire `ref` object as
58+
that reader's `request` prop in your next response. File matches use
59+
`REPL.File.Read`; use it directly when the path is already known.
60+
61+
```xmd
62+
<REPL.File.Read request={{"path":"note.txt","lines":"38:46"}} />
63+
```
64+
65+
File references compare the current file to the version search matched.
66+
Retained references read the saved entry and field. Searching and opening
67+
references perform no entry or command replay.
68+
5069
## Example
5170

5271
````xmd

‎packages/cli/src/repl/file-recorder.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ export interface EntryFileCalls {
5151
}
5252
interface CopyRouting {
5353
guard(): Operation<void>;
54+
prepareTransformedRead?(input: FilePathInput): Operation<Result<void>>;
5455
restoreSelection?(): Operation<unknown>;
5556
route(source: string, destination: string): Operation<Operation<void> | undefined>;
5657
}
@@ -127,6 +128,7 @@ function copyRecorder(routing: CopyRouting) {
127128
function recordingBody(
128129
route: FileRecordingRoute,
129130
copy: ReturnType<typeof copyRecorder> | undefined,
131+
routing: CopyRouting,
130132
) {
131133
return {
132134
*read(
@@ -158,7 +160,17 @@ function recordingBody(
158160
boundary(): Partial<Around<FilesHandler>> {
159161
const body = this;
160162
return {
161-
readTextFile: ([input], next) => body.read(input, () => next(input)),
163+
*readTextFile([input], next) {
164+
if (input.transform === undefined) {
165+
return yield* body.read(input, () => next(input));
166+
}
167+
yield* routing.guard();
168+
const permitted =
169+
routing.prepareTransformedRead === undefined
170+
? Ok(undefined)
171+
: yield* routing.prepareTransformedRead(input);
172+
return permitted.ok ? yield* next(input) : permitted;
173+
},
162174
ensureDirectory: ([input], next) => body.ensure(input, () => next(input)),
163175
*writeTextFile([input], next) {
164176
const result = yield* route("file-write", { ...input }, () => writeOutcome(next(input)));
@@ -189,7 +201,7 @@ export function* useEntryFileRecorder(
189201
const scope = yield* useScope();
190202
const alreadyInstalled = scope.hasOwn(entryCopyInstalled);
191203
scope.set(entryCopyInstalled, true);
192-
const body = recordingBody(route, alreadyInstalled ? undefined : copyRecorder(copy));
204+
const body = recordingBody(route, alreadyInstalled ? undefined : copyRecorder(copy), copy);
193205
const handle = yield* registerFileRecorder(body.boundary());
194206
const read = assembleFileCall(handle, "readTextFile");
195207
const ensure = assembleFileCall(handle, "ensureDirectory");

‎packages/cli/src/repl/repositories/deno/files.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ import { createMountPolicy } from "../../mount-files.ts";
5151
import type { Operation, Result } from "effection";
5252
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5353
import { realpath } from "node:fs/promises";
54-
import { Err, until } from "effection";
54+
import { Err, Ok, until } from "effection";
5555
import { filesFailure, Permissions } from "@executablemd/runtime";
5656
import {
5757
localRecordName,
@@ -356,6 +356,23 @@ export function* useReplFileRecorder(
356356
routed(recorder, operation, request, perform, workspace, authored, policy, access),
357357
{
358358
guard: () => policy.guard(),
359+
*prepareTransformedRead(input) {
360+
if (!(yield* Permissions.operations.files("read"))) {
361+
return Err(
362+
filesFailure({ operation: "read", phase: "resolution", reason: "permission-denied" }),
363+
);
364+
}
365+
const reason = yield* hostFileAccessReason(access, "read", input);
366+
if (reason !== undefined) {
367+
return Err(filesFailure({ operation: "read", phase: "resolution", reason }));
368+
}
369+
const target = yield* targetOf(input);
370+
const managed = covering(recorder.placements(), target);
371+
if (managed !== undefined) {
372+
yield* managed.own();
373+
}
374+
return Ok(undefined);
375+
},
359376
restoreSelection: () => recorder.selection(),
360377
route: (source, destination) => copyRoute(recorder, source, destination, roots),
361378
},

‎packages/cli/src/repl/session.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { SearchProject } from "@executablemd/core/host";
12
import type { EntryPlacement } from "./entry-placement.ts";
23
import { useHostFiles } from "@executablemd/runtime";
34
import type { HostFilesAccess } from "@executablemd/runtime";
@@ -2004,6 +2005,9 @@ function* start(
20042005
if (workspace !== undefined && options.access !== undefined) {
20052006
yield* useHostFiles({ access: options.access, temporaryRoot: options.access.project });
20062007
}
2008+
if (options.projectCwd !== undefined) {
2009+
yield* SearchProject.set(options.access?.project ?? options.projectCwd);
2010+
}
20072011
const directory = workspace === true ? options.workspace : options.projectCwd;
20082012
if (directory !== undefined) {
20092013
yield* API.Env.around(

‎packages/cli/src/repl/sidekick/controls.ts‎

Lines changed: 118 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
import type {
2+
ProjectFilePage,
3+
HistoryReader,
4+
HistoryWindow,
5+
SearchPage,
6+
SearchRequest,
7+
} from "./workspace-search.ts";
18
import type { EntryPlacement } from "../entry-placement.ts";
29
import type { ReplTesting, ReplTestReport } from "./testing.ts";
310
/**
@@ -29,8 +36,8 @@ import type { ReplTesting, ReplTestReport } from "./testing.ts";
2936
* ## Reads, writes, and which returns become feedback
3037
*
3138
* The read class observes and returns: bindings, the entry vocabulary, the six
32-
* guide chapters, the environment, and the four bounded reads of one entry's
33-
* saved evidence. The write class is
39+
* guide chapters, the environment, entry inspection and Workspace Search.
40+
* The write class is
3441
* what changes something a person can see or asks them something: filling the
3542
* shared draft, submitting it, and canonical `<Elicit>`. Keeping them in
3643
* separate classes is what lets the captured ceiling say, exactly, that a reply
@@ -128,6 +135,9 @@ export type GuideChapter = (typeof GUIDE_CHAPTERS)[number];
128135
* unavailable may well ask for something else next.
129136
*/
130137
export interface SidekickRequests {
138+
search(request: SearchRequest): Operation<Result<SearchPage>>;
139+
projectFile(request: Json): Operation<Result<ProjectFilePage>>;
140+
historyWindow(reader: HistoryReader, request: Json): Operation<Result<HistoryWindow>>;
131141
readonly test?: ReplTesting;
132142
inspectImage?(path: string): Operation<Result<string>>;
133143
importAsset(source: string, destination: string): Operation<Result<string>>;
@@ -286,6 +296,8 @@ export const DESIGNATED: ReadonlySet<string> = new Set([
286296
"REPL.InspectImage",
287297
"REPL.EntryOutput",
288298
...ENTRY_INSPECTIONS,
299+
"REPL.Search",
300+
"REPL.File.Read",
289301
ELICIT_CONTROL,
290302
...GUIDE_CHAPTERS.map((chapter) => `Guide.${chapter}`),
291303
]);
@@ -581,7 +593,58 @@ export function sidekickObservations(
581593
}),
582594
);
583595
}
584-
observations.push(...entryInspections(requests, journal));
596+
observations.push(
597+
...entryInspections(requests, journal),
598+
reading("REPL.Search", "Search project files and REPL history", {
599+
kind: "function",
600+
name: "REPL.Search",
601+
description:
602+
'Find literal text with `<REPL.Search query="error message" />`. Pass the returned reference as request to its named reader.',
603+
props: {
604+
type: "object",
605+
properties: {
606+
query: { type: "string", minLength: 1, maxLength: 160 },
607+
scope: { type: "string", enum: ["files", "history", "both"] },
608+
after: { type: "object" },
609+
},
610+
required: ["query"],
611+
additionalProperties: false,
612+
},
613+
*fn(props: Record<string, Json>): Operation<SearchPage | string> {
614+
const { query, scope, after } = props;
615+
if (
616+
typeof query !== "string" ||
617+
(scope !== undefined && scope !== "files" && scope !== "history" && scope !== "both")
618+
) {
619+
throw new Error("Invalid Workspace Search arguments.");
620+
}
621+
return yield* inspected(
622+
journal,
623+
{ component: "REPL.Search", arguments: { ...props } },
624+
() => requests.search({ query, scope, after }),
625+
);
626+
},
627+
}),
628+
reading("REPL.File.Read", "Read a bounded project file window", {
629+
kind: "function",
630+
name: "REPL.File.Read",
631+
description:
632+
'Read project context with `<REPL.File.Read request={{"path":"note.txt","lines":"2:4"}} />`.',
633+
props: {
634+
type: "object",
635+
properties: { request: { type: "object" } },
636+
required: ["request"],
637+
additionalProperties: false,
638+
},
639+
*fn(props: Record<string, Json>): Operation<ProjectFilePage | string> {
640+
return yield* inspected(
641+
journal,
642+
{ component: "REPL.File.Read", arguments: { ...props } },
643+
() => requests.projectFile(props.request),
644+
);
645+
},
646+
}),
647+
);
585648
for (const chapter of GUIDE_CHAPTERS) {
586649
const name = `Guide.${chapter}`;
587650
observations.push(
@@ -629,18 +692,27 @@ function entryInspections(requests: SidekickRequests, journal: ControlJournal):
629692
name: "REPL.Entry.Source",
630693
props: {
631694
type: "object",
632-
properties: { ...ENTRY_SELECTION },
695+
properties: { ...ENTRY_SELECTION, request: { type: "object" } },
633696
additionalProperties: false,
634697
},
635698
description:
636699
"Read the exact source one entry was admitted with. " +
637700
"`<REPL.Entry.Source entry={22} />` answers with a window of that source, counted in " +
638701
"Unicode code points, and the arguments of the windows either side of it.",
639-
*fn(props: EntryReadRequest): Operation<EntryTextPage | string> {
640-
return yield* inspected(
702+
*fn(
703+
props: EntryReadRequest & { request?: Json },
704+
): Operation<EntryTextPage | HistoryWindow | string> {
705+
return yield* inspected<EntryTextPage | HistoryWindow>(
641706
journal,
642707
{ component: "REPL.Entry.Source", arguments: { ...props } },
643-
() => requests.inspectSource(props),
708+
() =>
709+
props.request === undefined
710+
? requests.inspectSource(props)
711+
: Object.keys(props).length === 1
712+
? requests.historyWindow("REPL.Entry.Source", props.request)
713+
: (function* () {
714+
return Err(new Error("Pass a history request by itself."));
715+
})(),
644716
);
645717
},
646718
}),
@@ -650,6 +722,7 @@ function entryInspections(requests: SidekickRequests, journal: ControlJournal):
650722
props: {
651723
type: "object",
652724
properties: {
725+
request: { type: "object" },
653726
...ENTRY_SELECTION,
654727
prompt: { type: "number" },
655728
field: { type: "string" },
@@ -661,11 +734,20 @@ function entryInspections(requests: SidekickRequests, journal: ControlJournal):
661734
'`<REPL.Entry.Prompt entry={22} prompt={9} field="error" />` answers with that turn\'s ' +
662735
"reply, request or complete failure message, its own status and where it was written. " +
663736
"A turn that recorded no failure answers with null text rather than an empty one.",
664-
*fn(props: EntryPromptRequest): Operation<EntryPromptPage | string> {
665-
return yield* inspected(
737+
*fn(
738+
props: EntryPromptRequest & { request?: Json },
739+
): Operation<EntryPromptPage | HistoryWindow | string> {
740+
return yield* inspected<EntryPromptPage | HistoryWindow>(
666741
journal,
667742
{ component: "REPL.Entry.Prompt", arguments: { ...props } },
668-
() => requests.inspectPrompt(props),
743+
() =>
744+
props.request === undefined
745+
? requests.inspectPrompt(props)
746+
: Object.keys(props).length === 1
747+
? requests.historyWindow("REPL.Entry.Prompt", props.request)
748+
: (function* () {
749+
return Err(new Error("Pass a history request by itself."));
750+
})(),
669751
);
670752
},
671753
}),
@@ -674,18 +756,27 @@ function entryInspections(requests: SidekickRequests, journal: ControlJournal):
674756
name: "REPL.Entry.Output",
675757
props: {
676758
type: "object",
677-
properties: { ...ENTRY_SELECTION },
759+
properties: { ...ENTRY_SELECTION, request: { type: "object" } },
678760
additionalProperties: false,
679761
},
680762
description:
681763
"Read what one entry printed. `<REPL.Entry.Output entry={22} />` answers with the last " +
682764
"window of that entry's output; `offset={0}` reads from the beginning. An entry that " +
683765
"retained none answers with an empty window.",
684-
*fn(props: EntryReadRequest): Operation<EntryTextPage | string> {
685-
return yield* inspected(
766+
*fn(
767+
props: EntryReadRequest & { request?: Json },
768+
): Operation<EntryTextPage | HistoryWindow | string> {
769+
return yield* inspected<EntryTextPage | HistoryWindow>(
686770
journal,
687771
{ component: "REPL.Entry.Output", arguments: { ...props } },
688-
() => requests.inspectOutput(props),
772+
() =>
773+
props.request === undefined
774+
? requests.inspectOutput(props)
775+
: Object.keys(props).length === 1
776+
? requests.historyWindow("REPL.Entry.Output", props.request)
777+
: (function* () {
778+
return Err(new Error("Pass a history request by itself."));
779+
})(),
689780
);
690781
},
691782
}),
@@ -695,6 +786,7 @@ function entryInspections(requests: SidekickRequests, journal: ControlJournal):
695786
props: {
696787
type: "object",
697788
properties: {
789+
request: { type: "object" },
698790
entry: { type: "number" },
699791
yq: { type: "string", minLength: 1 },
700792
maxBytes: { type: "integer", minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
@@ -709,11 +801,20 @@ function entryInspections(requests: SidekickRequests, journal: ControlJournal):
709801
"Read .exec.exitCode, .exec.stdout and .exec.stderr on a command record; " +
710802
"reuse next, prev or last as yq with the same positive entry. " +
711803
"Use maxBytes={8388608} for an 8 MiB compact UTF-8 JSON response budget; navigation carries it, and a later explicit budget overrides it.",
712-
*fn(props: EntryJournalRequest): Operation<EntryJournalPage | string> {
713-
return yield* inspected(
804+
*fn(
805+
props: EntryJournalRequest & { request?: Json },
806+
): Operation<EntryJournalPage | HistoryWindow | string> {
807+
return yield* inspected<EntryJournalPage | HistoryWindow>(
714808
journal,
715809
{ component: "REPL.Entry.Journal", arguments: { ...props } },
716-
() => requests.inspectJournal(props),
810+
() =>
811+
props.request === undefined
812+
? requests.inspectJournal(props)
813+
: Object.keys(props).length === 1
814+
? requests.historyWindow("REPL.Entry.Journal", props.request)
815+
: (function* () {
816+
return Err(new Error("Pass a history request by itself."));
817+
})(),
717818
);
718819
},
719820
}),

‎packages/cli/src/repl/sidekick/requests.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import type { HostFilesAccess } from "@executablemd/runtime";
2+
import { readHistoryWindow, readProjectFile, searchWorkspace } from "./workspace-search.ts";
13
import { resolveJournalMaxBytes } from "./journal-policy.ts";
24
import type { ReplTesting } from "./testing.ts";
35
/**
@@ -71,6 +73,7 @@ import type {
7173
* cannot grow one by being handed something that has it.
7274
*/
7375
export interface RootReading {
76+
readonly projectAccess?: HostFilesAccess;
7477
/**
7578
* The acknowledged head of this execution's history, however it is navigated.
7679
*
@@ -143,13 +146,15 @@ export type RootReads = Omit<RootReading, "fill">;
143146
export function rootReads(
144147
session: ReplSession,
145148
profile: {
149+
readonly access?: HostFilesAccess;
146150
readonly includes: readonly string[];
147151
readonly permissionMode: string;
148152
readonly plugins: readonly string[];
149153
readonly vocabulary: EntryVocabulary;
150154
},
151155
): RootReads {
152156
return {
157+
projectAccess: profile.access,
153158
*inspectJournal(request: EntryJournalRequest): Operation<Result<EntryJournalPage>> {
154159
const policy = resolveJournalMaxBytes(request.yq ?? ".", request.maxBytes);
155160
if (!policy.ok) {
@@ -235,6 +240,10 @@ export function sidekickRequests(
235240
return {
236241
...(test === undefined ? {} : { test }),
237242
importAsset: importAsset ?? refusedImport,
243+
search: (request) => searchWorkspace(request, root.projectAccess, () => root.acknowledged()),
244+
projectFile: (request) => readProjectFile(request, root.projectAccess),
245+
historyWindow: (reader, request) =>
246+
readHistoryWindow(reader, request, () => root.acknowledged()),
238247
*bindings(): Operation<Result<Json>> {
239248
// The root data as it stands: the retained head for every entry that has
240249
// settled, and the current root of the entry running now on top of it.

0 commit comments

Comments
 (0)