foretext 0.0.0-stage → 0.8.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.
@@ -0,0 +1,488 @@
1
+ import { At as NOTE_STATUSES, M as CaptureMessageId, Nt as SOURCE_TYPES, jt as NOTE_TYPES, s as evaluateCapture, u as MainLiveAt } from "./src-DjnbdRrt.js";
2
+ import { S as reportAutomaticContext, a as autoContextOp, d as searchOp, f as showOp, g as recordAutomaticContextUsage, i as addOp, j as runOpAtDirectory, m as elapsedUsageMs, n as contextualRecallOp, o as contextDigest, s as editOp, t as CONTEXTUAL_RECALL_LIMITS, x as compactAutomaticContext } from "./contextual-recall-DF8e3Oa_.js";
3
+ import { t as stageCapture } from "./capture-admission-DqhzaMDY.js";
4
+ import { Effect, Option, Schema } from "effect";
5
+ import { createHash } from "node:crypto";
6
+ import { isAbsolute, resolve } from "node:path";
7
+ import { z } from "zod";
8
+ //#region ../harnesses/src/opencode/capture-command.ts
9
+ const NAME = "foretext-capture";
10
+ const TEMPLATE = "Note handles this command locally. Direct the user to the Note notification.";
11
+ const MAX_SESSIONS$1 = 100;
12
+ const MAX_MESSAGES = 64;
13
+ const MAX_PROPOSALS = 8;
14
+ const MAX_TEXT = 1e3;
15
+ const CAPTURE_MS = 1500;
16
+ const isId = Schema.is(CaptureMessageId);
17
+ const commandPart = Symbol("OpenCode command part");
18
+ function plainText(parts, sessionID, messageID) {
19
+ const [part] = parts;
20
+ if (parts.length !== 1 || part?.type !== "text" || part.synthetic || part.ignored || part.metadata !== void 0 || commandPart in part || part.sessionID !== sessionID || part.messageID !== messageID || !isId(part.id) || typeof part.text !== "string" || part.text.length > MAX_TEXT || part.text.trimStart().startsWith("/")) return;
21
+ return part;
22
+ }
23
+ const digest = (text) => createHash("sha256").update(text).digest("hex");
24
+ function createCaptureCommand({ client, directory, project }, onWriteSuccess) {
25
+ const sessions = /* @__PURE__ */ new Map();
26
+ const active = /* @__PURE__ */ new Set();
27
+ let registered = false;
28
+ const config = async (value) => {
29
+ value.command ??= {};
30
+ if (Object.hasOwn(value.command, NAME)) return;
31
+ value.command[NAME] = {
32
+ description: "Capture Foretext memory suggestions for project review or opt-in recording",
33
+ template: TEMPLATE
34
+ };
35
+ registered = true;
36
+ };
37
+ const observe = async ({ sessionID }, { message, parts }) => {
38
+ if (!registered || message.role !== "user" || message.sessionID !== sessionID) return;
39
+ if (!isId(sessionID) || !isId(message.id)) return;
40
+ let observed = sessions.get(sessionID);
41
+ if (observed?.has(message.id)) {
42
+ observed.get(message.id).handled = true;
43
+ return;
44
+ }
45
+ if (message.system !== void 0) return;
46
+ const part = plainText(parts, sessionID, message.id);
47
+ if (!part) return;
48
+ if (!observed) {
49
+ observed = /* @__PURE__ */ new Map();
50
+ sessions.set(sessionID, observed);
51
+ if (sessions.size > MAX_SESSIONS$1) sessions.delete(sessions.keys().next().value);
52
+ }
53
+ observed.set(message.id, {
54
+ partId: part.id,
55
+ digest: digest(part.text),
56
+ handled: false
57
+ });
58
+ if (observed.size > MAX_MESSAGES) observed.delete(observed.keys().next().value);
59
+ };
60
+ const notify = (message, variant = "info") => {
61
+ Promise.resolve().then(() => client?.tui?.showToast({
62
+ body: {
63
+ title: "Note capture",
64
+ message,
65
+ variant
66
+ },
67
+ query: { directory },
68
+ signal: AbortSignal.timeout(CAPTURE_MS)
69
+ })).catch(() => void 0);
70
+ };
71
+ const command = async ({ command, sessionID, arguments: args }, { parts }) => {
72
+ if (!registered) return;
73
+ for (const [index, part] of parts.entries()) {
74
+ if (part.type !== "text") continue;
75
+ parts[index] = {
76
+ ...part,
77
+ [commandPart]: true
78
+ };
79
+ }
80
+ if (command !== NAME || !isId(sessionID)) return;
81
+ if (args.trim() || parts.length !== 1) {
82
+ notify("Use /foretext-capture without arguments.", "warning");
83
+ return;
84
+ }
85
+ if (parts[0].type !== "text" || parts[0].text !== TEMPLATE) return;
86
+ if (active.has(sessionID)) {
87
+ notify("Note capture is already running.");
88
+ return;
89
+ }
90
+ const observed = sessions.get(sessionID);
91
+ const abort = new AbortController();
92
+ let timer;
93
+ let count = 0;
94
+ let recorded = 0;
95
+ const capture = async () => {
96
+ if (!client?.session || !project?.id || !directory || !isAbsolute(directory)) return "unavailable";
97
+ const { signal } = abort;
98
+ const { data: session } = await client.session.get({
99
+ path: { id: sessionID },
100
+ query: { directory },
101
+ signal
102
+ });
103
+ if (signal.aborted || !session || session.id !== sessionID || session.projectID !== project.id || !session.directory || !isAbsolute(session.directory) || resolve(session.directory) !== resolve(directory) || session.parentID !== void 0 || session.revert !== void 0) return "unavailable";
104
+ if (!observed?.size) return "complete";
105
+ const { data } = await client.session.messages({
106
+ path: { id: sessionID },
107
+ query: {
108
+ directory,
109
+ limit: MAX_MESSAGES
110
+ },
111
+ signal
112
+ });
113
+ if (signal.aborted || !Array.isArray(data) || data.length > MAX_MESSAGES) return "unavailable";
114
+ const partIds = /* @__PURE__ */ new Map();
115
+ const messages = [];
116
+ for (const item of data) {
117
+ const info = item?.info;
118
+ if (!info || info.sessionID !== sessionID || !isId(info.id)) return "unavailable";
119
+ const evidence = observed.get(info.id);
120
+ const part = info.role === "user" && info.system === void 0 && Array.isArray(item.parts) ? plainText(item.parts, sessionID, info.id) : void 0;
121
+ if (!evidence || !part || evidence.partId !== part.id || evidence.digest !== digest(part.text)) {
122
+ messages.push({
123
+ id: info.id,
124
+ origin: "system",
125
+ text: ""
126
+ });
127
+ continue;
128
+ }
129
+ partIds.set(info.id, part.id);
130
+ messages.push({
131
+ id: info.id,
132
+ origin: "user",
133
+ text: part.text
134
+ });
135
+ }
136
+ const proposals = evaluateCapture({ messages }).filter(({ evidence }) => evidence.every(({ messageId }) => observed.get(messageId)?.handled === false));
137
+ for (const { evidence } of proposals.slice(0, MAX_PROPOSALS)) {
138
+ if (signal.aborted || sessions.get(sessionID) !== observed) return "unavailable";
139
+ const ids = evidence.map(({ messageId }) => messageId);
140
+ if (ids.some((id) => observed.get(id)?.handled !== false)) continue;
141
+ const result = await Effect.runPromise(stageCapture({
142
+ messages,
143
+ selectedEvidence: ids
144
+ }, directory, {
145
+ harness: "opencode",
146
+ sessionKind: "root",
147
+ sessionId: sessionID,
148
+ event: "command.execute.before",
149
+ partIds
150
+ }, signal).pipe(Effect.provide(MainLiveAt(directory))), { signal });
151
+ if (result.status !== "rejected" || result.reason === "duplicate") for (const id of ids) {
152
+ const source = observed.get(id);
153
+ if (source) source.handled = true;
154
+ }
155
+ if (result.status === "pending") count++;
156
+ if (result.status === "recorded") {
157
+ recorded++;
158
+ onWriteSuccess?.();
159
+ }
160
+ }
161
+ return "complete";
162
+ };
163
+ active.add(sessionID);
164
+ try {
165
+ const deadline = new Promise((resolve) => {
166
+ timer = setTimeout(() => {
167
+ resolve("unavailable");
168
+ abort.abort();
169
+ }, CAPTURE_MS);
170
+ });
171
+ const result = await Promise.race([capture(), deadline]);
172
+ if (recorded > 0) notify(`Note automatically recorded ${recorded} ${recorded === 1 ? "memory" : "memories"}.`);
173
+ if (count) notify(`Note staged ${count} ${count === 1 ? "candidate" : "candidates"} for review. Run foretext pending list --scope all.`);
174
+ if (result === "unavailable") notify("Note capture could not complete for this session.", "warning");
175
+ else if (!count && !recorded) notify("Note found no new eligible candidates.");
176
+ } catch {
177
+ notify("Note capture could not complete. Run foretext pending list --scope all.", "warning");
178
+ } finally {
179
+ clearTimeout(timer);
180
+ active.delete(sessionID);
181
+ }
182
+ };
183
+ return {
184
+ config,
185
+ command,
186
+ observe,
187
+ dropSession: (id) => sessions.delete(id)
188
+ };
189
+ }
190
+ const MAX_ID_CHARS = 256;
191
+ const CACHE_MS = 3e4;
192
+ const SDK_TIMEOUT_MS = 500;
193
+ const validId = (id) => typeof id === "string" && id.length > 0 && id.length <= MAX_ID_CHARS;
194
+ /**
195
+ * OpenCode stores the pending assistant message before preparing its system
196
+ * prompt. Its parent identifies the user message for this turn, even when
197
+ * tool calls have added newer assistant messages. The assistant's working
198
+ * directory comes from the same execution context as the native tools.
199
+ */
200
+ const lookupActiveRequest = async (client, sessionID, model, signal) => {
201
+ const session = client?.session;
202
+ if (typeof session?.messages !== "function" || typeof session.message !== "function") return;
203
+ if (!model?.id || !model.providerID) return;
204
+ const { data } = await session.messages({
205
+ path: { id: sessionID },
206
+ query: { limit: 1 },
207
+ signal
208
+ });
209
+ if (!Array.isArray(data) || data.length !== 1) return;
210
+ const assistant = data[0]?.info;
211
+ if (assistant?.role !== "assistant" || assistant.sessionID !== sessionID || assistant.modelID !== model.id || assistant.providerID !== model.providerID || !assistant.time || assistant.time.completed !== void 0 || assistant.summary || assistant.finish !== void 0 || !validId(assistant.parentID)) return;
212
+ const directory = assistant.path?.cwd;
213
+ if (typeof directory !== "string" || directory.length > CONTEXTUAL_RECALL_LIMITS.rootChars || directory.includes("\0") || !isAbsolute(directory)) return;
214
+ const messageID = assistant.parentID;
215
+ const { data: message } = await session.message({
216
+ path: {
217
+ id: sessionID,
218
+ messageID
219
+ },
220
+ signal
221
+ });
222
+ if (signal.aborted || message?.info?.role !== "user" || message.info.id !== messageID || message.info.sessionID !== sessionID || !Array.isArray(message.parts)) return;
223
+ let prompt = "";
224
+ for (const part of message.parts) {
225
+ if (part?.type !== "text" || part.synthetic || part.ignored || part.text === "") continue;
226
+ if (part.sessionID !== sessionID || part.messageID !== messageID || typeof part.text !== "string") return;
227
+ if (prompt.length + part.text.length + Number(Boolean(prompt)) > CONTEXTUAL_RECALL_LIMITS.promptChars) return;
228
+ prompt += prompt ? "\n" + part.text : part.text;
229
+ }
230
+ if (prompt.trim()) return {
231
+ directory,
232
+ messageID,
233
+ prompt
234
+ };
235
+ };
236
+ const resolveActiveRequest = (client) => (sessionID, model) => Effect.runPromise(Effect.promise((signal) => lookupActiveRequest(client, sessionID, model, signal)).pipe(Effect.timeoutOption(SDK_TIMEOUT_MS), Effect.map(Option.getOrUndefined)));
237
+ const loadContext = async ({ directory, prompt }) => {
238
+ const recall = await runOpAtDirectory(directory, contextualRecallOp({
239
+ prompt,
240
+ intent: "task"
241
+ }, true));
242
+ const recalled = {
243
+ source: "recall",
244
+ result: recall
245
+ };
246
+ if (recall.details.reason !== "weak" && recall.details.reason !== "empty-query") return recalled;
247
+ const loaded = await runOpAtDirectory(directory, autoContextOp(true).pipe(Effect.timeoutOption(CONTEXTUAL_RECALL_LIMITS.timeoutMs), Effect.map(Option.getOrElse(() => ({
248
+ text: "",
249
+ isError: false,
250
+ details: { reason: "timeout" }
251
+ })))));
252
+ if (loaded.details.enabled === false || !loaded.automatic && !recall.automatic?.rows.length && !recall.automatic?.omittedFiles && (loaded.details.error || loaded.details.reason === "timeout")) return {
253
+ source: "bootstrap",
254
+ result: loaded
255
+ };
256
+ if (!loaded.automatic) return recalled;
257
+ const source = loaded.automatic;
258
+ const critical = recall.automatic?.rows ?? [];
259
+ const ids = new Set(critical.map(({ scope, id }) => `${scope}/${id}`));
260
+ return {
261
+ source: "bootstrap",
262
+ result: {
263
+ ...loaded,
264
+ automatic: {
265
+ ...source,
266
+ outsideCandidateWindow: (source.outsideCandidateWindow ?? 0) + (recall.automatic?.outsideCandidateWindow ?? 0),
267
+ rows: [...critical, ...source.rows.filter(({ scope, id }) => !ids.has(`${scope}/${id}`))]
268
+ }
269
+ }
270
+ };
271
+ };
272
+ function createContextTransform(resolve, { load = loadContext, onDiagnostics = reportAutomaticContext } = {}) {
273
+ const sessions = /* @__PURE__ */ new Map();
274
+ const outputs = /* @__PURE__ */ new WeakMap();
275
+ const transform = async (input, output) => {
276
+ try {
277
+ const system = output?.system;
278
+ if (!Array.isArray(system) || !Object.isExtensible(system)) return;
279
+ const previous = outputs.get(system)?.injection;
280
+ if (previous) {
281
+ const index = system.indexOf(previous);
282
+ if (index !== -1 && index === system.lastIndexOf(previous)) system.splice(index, 1);
283
+ }
284
+ const state = {};
285
+ outputs.set(system, state);
286
+ const sessionID = input?.sessionID;
287
+ if (!validId(sessionID)) return;
288
+ let cache = sessions.get(sessionID);
289
+ if (!cache) {
290
+ cache = {};
291
+ sessions.set(sessionID, cache);
292
+ const oldest = sessions.keys().next().value;
293
+ if (sessions.size > 100 && oldest !== void 0) sessions.delete(oldest);
294
+ }
295
+ const request = await resolve(sessionID, input.model);
296
+ if (!request || sessions.get(sessionID) !== cache || outputs.get(system) !== state) return;
297
+ const now = performance.now();
298
+ let context = cache.context;
299
+ if (!context || context.until <= now || context.request.directory !== request.directory || context.request.messageID !== request.messageID || context.request.prompt !== request.prompt) {
300
+ const pending = (async () => load(request))().catch(() => void 0);
301
+ context = {
302
+ request,
303
+ until: now + CACHE_MS,
304
+ load: pending
305
+ };
306
+ cache.context = context;
307
+ }
308
+ const delivery = await context.load;
309
+ const source = delivery?.result.automatic;
310
+ if (!source?.rows.length && !source?.omittedFiles && cache.context === context) cache.context = void 0;
311
+ if (!delivery) return;
312
+ if (sessions.get(sessionID) !== cache || outputs.get(system) !== state || output.system !== system) return;
313
+ if (!source) {
314
+ Effect.runFork(recordAutomaticContextUsage(delivery.source, elapsedUsageMs(now), delivery.result));
315
+ return;
316
+ }
317
+ const limit = input.model?.limit;
318
+ const { text, diagnostics } = compactAutomaticContext(source, {
319
+ harness: "opencode",
320
+ system,
321
+ prompt: request.prompt,
322
+ contextWindow: limit?.context,
323
+ inputLimit: limit?.input,
324
+ output: limit?.output
325
+ });
326
+ onDiagnostics(diagnostics);
327
+ if (text) {
328
+ system.push(text);
329
+ state.injection = text;
330
+ }
331
+ Effect.runFork(recordAutomaticContextUsage(delivery.source, elapsedUsageMs(now), delivery.result, text, diagnostics));
332
+ } catch {}
333
+ };
334
+ return {
335
+ transform,
336
+ invalidate: () => sessions.clear(),
337
+ dropSession: (sessionID) => sessions.delete(sessionID)
338
+ };
339
+ }
340
+ //#endregion
341
+ //#region ../harnesses/src/opencode/result.ts
342
+ const toOpencodeResult = (title, r) => ({
343
+ title,
344
+ output: r.text,
345
+ metadata: {
346
+ ...r.details,
347
+ isError: r.isError
348
+ }
349
+ });
350
+ //#endregion
351
+ //#region ../harnesses/src/opencode/tools.ts
352
+ /**
353
+ * foretext_* tool definitions for opencode.
354
+ *
355
+ * Thin adapters over @foretext/harnesses/shared ops: zod arg shapes with
356
+ * per-field descriptions and bounds, mirroring the Pi typebox schemas.
357
+ * Keep descriptions in sync with src/pi/tools.ts.
358
+ */
359
+ const scopeFilter = (description) => z.enum([
360
+ "project",
361
+ "personal",
362
+ "both"
363
+ ]).optional().describe(description);
364
+ const noteTypes = NOTE_TYPES;
365
+ const noteStatuses = NOTE_STATUSES;
366
+ const sourceTypes = SOURCE_TYPES;
367
+ const noteContextTool = {
368
+ description: "Refresh the recorded memory digest for this workspace: decisions, pinned notes, gotchas, conventions. OpenCode can load relevant memory or a compact digest automatically for the current request. Use this tool for an overview, additional pages, or when automatic context is unavailable. Returns compact one-line entries (id, type, title, tags) with decisions and pinned entries first; read a full entry with foretext_show. Results are paginated - when truncated, the footer names the exact next call.",
369
+ args: {
370
+ scope: scopeFilter(`Which memory scope to read. Default "both" (falls back to personal-only with a note outside a project).`),
371
+ limit: z.number().int().min(1).max(100).optional().describe(`Max entries per page. Default 25.`),
372
+ offset: z.number().int().min(0).optional().describe("0-based page offset for pagination."),
373
+ tokens: z.number().int().min(512).optional().describe("Budget the digest text using Foretext's versioned token accounting.")
374
+ },
375
+ async execute(args, context) {
376
+ return toOpencodeResult("Note Context", await runOpAtDirectory(context.directory, contextDigest(args)));
377
+ }
378
+ };
379
+ const noteSearchTool = {
380
+ description: "Keyword-search recorded notes (tags score highest, then aliases, titles, types, bodies). Use when you need specifics beyond the digest - \"auth\", \"migrations\", the name of a library. Returns bounded matching snippets and relevance reasons framed as untrusted memory data, plus structured score summaries; read one with foretext_show. Results are paginated. Set explain to include matched fields and score contributions in metadata.",
381
+ args: {
382
+ query: z.string().describe("Search keywords (matched against tags, aliases, titles, types, and bodies)."),
383
+ explain: z.boolean().optional().describe("Include matched fields, normalized query tokens, and score contributions in metadata. Default false."),
384
+ scope: scopeFilter("Which memory scope to search. Default \"both\"."),
385
+ limit: z.number().int().min(1).max(50).optional().describe(`Max matches per page. Default 10.`),
386
+ offset: z.number().int().min(0).optional().describe("0-based page offset for pagination.")
387
+ },
388
+ async execute(args, context) {
389
+ return toOpencodeResult("Note Search", await runOpAtDirectory(context.directory, searchOp(args)));
390
+ }
391
+ };
392
+ const noteShowTool = {
393
+ description: "Read one full note by id (unique prefixes work, e.g. \"12\" for \"0012\"): frontmatter (type, tags, dates, author, scope) plus the complete body. Use after foretext_context or foretext_search picked an entry worth reading. Very long bodies are sliced - the footer names the exact next call.",
394
+ args: {
395
+ id: z.string().describe("Note id or unique prefix, e.g. \"0012\" or \"12\"."),
396
+ scope: z.enum(["project", "personal"]).optional().describe("Where to look. Default: project inside a project, personal otherwise."),
397
+ offset: z.number().int().min(0).optional().describe("0-based char offset into the body."),
398
+ limit: z.number().int().min(1).optional().describe("Max body chars to return.")
399
+ },
400
+ async execute(args, context) {
401
+ return toOpencodeResult("Note Show", await runOpAtDirectory(context.directory, showOp(args)));
402
+ }
403
+ };
404
+ const noteAddTool = {
405
+ description: `Record a durable fact, decision, gotcha, or convention to shared memory. Use type "decision" for important choices (state the rationale and alternatives in the body), and record gotchas that cost debugging time. Do not record transient state, secrets, or anything the user says not to store. Project scope is committed to git and shared with the team; pass scope "personal" only for notes that must stay on this machine. Optional lifecycle/provenance metadata (status, supersedes, reviewAfter, expires, sourceType, sourceRef) is an unauthenticated claim, not a verified truth. Optional related links exact same-scope entry ids as directional metadata: the whole list is stored as given, and missing targets only dangle as a warning. Optional aliases are alternate names for the entry (max 20, 80 characters each); the store trims, lowercases, and deduplicates them.`,
406
+ args: {
407
+ title: z.string().describe("Short, descriptive title (one line)."),
408
+ body: z.string().describe("Full content: rationale, context, details."),
409
+ type: z.enum(noteTypes).optional().describe(`Entry kind. Default: the project config defaultType ("note" unless configured).`),
410
+ scope: z.enum(["project", "personal"]).optional().describe("Default \"project\" (team-shared, git-committed)."),
411
+ tags: z.array(z.string()).optional().describe("Searchable tags, e.g. [\"auth\", \"deps\"]."),
412
+ pinned: z.boolean().optional().describe("Pin to the top of the digest for high-value entries."),
413
+ status: z.enum(noteStatuses).optional().describe("Lifecycle status: active | superseded | archived. Optional; not set unless passed."),
414
+ supersedes: z.string().optional().describe("Id of the older entry this one replaces. Optional; validated when saved."),
415
+ reviewAfter: z.string().optional().describe("ISO 8601 timestamp with an explicit zone, e.g. 2026-01-01T00:00:00.000Z. Optional; validated when saved."),
416
+ expires: z.string().optional().describe("ISO 8601 timestamp with an explicit zone, e.g. 2026-06-01T00:00:00.000Z. Optional; validated when saved."),
417
+ sourceType: z.enum(sourceTypes).optional().describe("Provenance shape: conversation | file | url | command | other. Optional."),
418
+ sourceRef: z.string().optional().describe("Source reference: path, URL, command, or conversation note. Optional; validated when saved."),
419
+ related: z.array(z.string()).optional().describe("Exact note ids in the same scope, e.g. [\"0002\"]. Replaces the whole list in this order; duplicates are rejected. Missing targets are advisory (a warning on check, not an error). Optional."),
420
+ aliases: z.array(z.string().max(80)).max(20).optional().describe("Alternate names for this entry, e.g. [\"pg\", \"postgres row level security\"]. The store trims, lowercases, and deduplicates them (first occurrence wins); the whole set is replaced. Optional."),
421
+ confirmWrite: z.boolean().optional().describe("Proceed after the user reviews and accepts a write advisory."),
422
+ allowSecrets: z.boolean().optional().describe("Write even if the secret scanner flags this content (project writes block by default). Optional.")
423
+ },
424
+ async execute(args, context) {
425
+ return toOpencodeResult("Note Add", await runOpAtDirectory(context.directory, addOp(args)));
426
+ }
427
+ };
428
+ const noteEditTool = {
429
+ description: "Update an existing note by id (unique prefixes work). Ordinary fields (title, type, tags, body, pinned, author) are replaced when passed and preserved when omitted. The six lifecycle fields (status, supersedes, reviewAfter, expires, sourceType, sourceRef) are three-state: a concrete value replaces, null clears, omission preserves. related is three-state the same way: an array replaces the whole list with exact same-scope ids, null clears it, omission preserves; links are directional and may dangle with a warning. aliases is three-state too: an array replaces the whole set, null clears it, omission preserves. Use this to correct a title or tags, change a type, pin or unpin, or clear a lifecycle field after acting on it. Scope defaults to project inside a project and personal outside one.",
430
+ args: {
431
+ id: z.string().describe("Note id or unique prefix, e.g. \"0012\" or \"12\". Required."),
432
+ scope: z.enum(["project", "personal"]).optional().describe("Where to edit. Default: project inside a project, personal otherwise."),
433
+ title: z.string().optional().describe("New title. Omit to preserve."),
434
+ type: z.enum(noteTypes).optional().describe("Replace entry kind. Omit to preserve."),
435
+ tags: z.array(z.string()).optional().describe("Replace the whole tag set, e.g. [\"auth\", \"deps\"]. Omit to preserve."),
436
+ body: z.string().optional().describe("New body content. Omit to preserve."),
437
+ pinned: z.boolean().optional().describe("True pins, false unpins. Omit to preserve."),
438
+ author: z.string().optional().describe("Replace author. Omit to preserve."),
439
+ status: z.enum(noteStatuses).nullable().optional().describe("Lifecycle status: active | superseded | archived. Null clears; omit to preserve."),
440
+ supersedes: z.string().nullable().optional().describe("Id of the older entry this one replaces. Null clears; omit to preserve. Validated when saved."),
441
+ reviewAfter: z.string().nullable().optional().describe("ISO 8601 timestamp with an explicit zone, e.g. 2027-01-01T00:00:00.000Z. Null clears; omit to preserve. Validated when saved."),
442
+ expires: z.string().nullable().optional().describe("ISO 8601 timestamp with an explicit zone, e.g. 2027-06-01T00:00:00.000Z. Null clears; omit to preserve. Validated when saved."),
443
+ sourceType: z.enum(sourceTypes).nullable().optional().describe("Provenance shape: conversation | file | url | command | other. Null clears; omit to preserve."),
444
+ sourceRef: z.string().nullable().optional().describe("Source reference: path, URL, command, or conversation note. Null clears; omit to preserve. Validated when saved."),
445
+ related: z.array(z.string()).nullable().optional().describe("Replace the whole related list with exact same-scope ids in this order. Null clears; omit to preserve. Missing targets are advisory (a warning on check, not an error)."),
446
+ aliases: z.array(z.string().max(80)).max(20).nullable().optional().describe("Replace the whole alias set with these alternate names. The store trims, lowercases, and deduplicates them. Null clears; omit to preserve."),
447
+ confirmWrite: z.boolean().optional().describe("Proceed after the user reviews and accepts a write advisory."),
448
+ allowSecrets: z.boolean().optional().describe("Write even if the secret scanner flags the resulting entry (project writes block by default). Optional.")
449
+ },
450
+ async execute(args, context) {
451
+ return toOpencodeResult("Note Edit", await runOpAtDirectory(context.directory, editOp(args)));
452
+ }
453
+ };
454
+ //#endregion
455
+ //#region ../harnesses/src/opencode/index.ts
456
+ const notePlugin = async (input) => {
457
+ const autoContext = createContextTransform(resolveActiveRequest(input.client));
458
+ const capture = createCaptureCommand(input, autoContext.invalidate);
459
+ const writeToolWithRefresh = (base) => ({
460
+ ...base,
461
+ async execute(args, context) {
462
+ const result = await base.execute(args, context);
463
+ if (result.metadata?.isError === false) autoContext.invalidate();
464
+ return result;
465
+ }
466
+ });
467
+ return {
468
+ tool: {
469
+ foretext_context: noteContextTool,
470
+ foretext_search: noteSearchTool,
471
+ foretext_show: noteShowTool,
472
+ foretext_add: writeToolWithRefresh(noteAddTool),
473
+ foretext_edit: writeToolWithRefresh(noteEditTool)
474
+ },
475
+ config: capture.config,
476
+ "chat.message": capture.observe,
477
+ "command.execute.before": capture.command,
478
+ "experimental.chat.system.transform": autoContext.transform,
479
+ event: async ({ event }) => {
480
+ if (event.type === "session.deleted") {
481
+ autoContext.dropSession(event.properties.info.id);
482
+ capture.dropSession(event.properties.info.id);
483
+ }
484
+ }
485
+ };
486
+ };
487
+ //#endregion
488
+ export { notePlugin as default };