@blackbelt-technology/pi-dashboard-sim-plugin 0.0.0-stage → 0.12.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,27 @@
1
+ /**
2
+ * sim-plugin · SERVER entry: mounts `/api/sim/*` and the observation job.
3
+ * cwd validation consumes `host.knownFolderCwds` (session cwds ∪ pinned
4
+ * dirs), falling back to session cwds. See change: add-self-improvement-memory.
5
+ */
6
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
7
+ import type { IndeterminateInfo } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
8
+ import { agentDir, loadGlobalConfig } from "@blackbelt-technology/pi-dashboard-sim-extension/core";
9
+ import { SimObserver } from "./observer.js";
10
+ import { mountSimRoutes } from "./sim-routes.js";
11
+
12
+ export default async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
13
+ const agent = agentDir();
14
+ const hostKnown = ctx.consume<() => string[]>("host.knownFolderCwds");
15
+ const knownCwds = (): string[] =>
16
+ hostKnown
17
+ ? hostKnown()
18
+ : (ctx.sessionManager.listAll() as Array<{ cwd?: string }>).map((s) => s.cwd).filter((c): c is string => typeof c === "string" && c.length > 0);
19
+ const onIndeterminate = ctx.consume<(info: IndeterminateInfo) => void>("host.cwdAdmissionOnIndeterminate");
20
+ const observer = new SimObserver({ agentDir: agent, windowN: () => loadGlobalConfig(agent).windowN, logger: ctx.logger });
21
+ mountSimRoutes(ctx.fastify, { agentDir: agent, knownCwds, admitOptions: { onIndeterminate }, observer });
22
+ observer.schedule(() => loadGlobalConfig(agent).autoObserve);
23
+ ctx.fastify.addHook("onClose", async () => {
24
+ await observer.shutdown();
25
+ });
26
+ ctx.logger.info("sim-plugin server entry activated");
27
+ }
@@ -0,0 +1,4 @@
1
+ // Plugin-side worker bootstrap: the observation worker lives in sim-extension
2
+ // (`./observe-worker` export) so `pi-sim observe` and the plugin share one entry
3
+ // (test-plan E34). See change: add-self-improvement-memory.
4
+ import "@blackbelt-technology/pi-dashboard-sim-extension/observe-worker";
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Observation job (design D7): runs `runObservation` in a worker thread so the
3
+ * dashboard event loop stays responsive (test-plan P3). Hourly when
4
+ * auto-observe is on; one run at a time; cancellable; progress + last-run
5
+ * counts reported to the routes and the server log.
6
+ */
7
+ import { Worker } from "node:worker_threads";
8
+ import type { SimObserverStatus } from "../shared/types.js";
9
+
10
+ interface ObserverLogger {
11
+ info(msg: string): void;
12
+ warn(msg: string): void;
13
+ error(msg: string): void;
14
+ }
15
+
16
+ export interface ObserverOptions {
17
+ agentDir: string;
18
+ windowN: () => number;
19
+ logger: ObserverLogger;
20
+ /** Test seam: worker module URL. */
21
+ workerUrl?: URL;
22
+ }
23
+
24
+ const HOURLY_MS = 60 * 60 * 1000;
25
+
26
+ function defaultWorkerUrl(): URL {
27
+ return new URL("./observe-worker.mjs", import.meta.url);
28
+ }
29
+
30
+ export class SimObserver {
31
+ private worker: Worker | null = null;
32
+ private timer: NodeJS.Timeout | null = null;
33
+ private status: SimObserverStatus = { running: false };
34
+ private waiters: Array<() => void> = [];
35
+ private readonly opts: ObserverOptions;
36
+ constructor(opts: ObserverOptions) {
37
+ this.opts = opts;
38
+ }
39
+
40
+ getStatus(): SimObserverStatus {
41
+ return { ...this.status };
42
+ }
43
+
44
+ isRunning(): boolean {
45
+ return this.worker !== null;
46
+ }
47
+
48
+ /** Start a run; false when one is already running. */
49
+ start(redo = false): boolean {
50
+ if (this.worker) return false;
51
+ const t0 = Date.now();
52
+ const worker = new Worker(this.opts.workerUrl ?? defaultWorkerUrl(), {
53
+ execArgv: [],
54
+ // The worker inherits process.env; only the fields the run needs are passed.
55
+ workerData: { agentDir: this.opts.agentDir, windowN: this.opts.windowN(), redo },
56
+ });
57
+ this.worker = worker;
58
+ this.status = { running: true, lastRun: this.status.lastRun };
59
+ this.opts.logger.info("[sim-plugin] observation started");
60
+ let ended = false;
61
+ const finish = (lastRun: NonNullable<SimObserverStatus["lastRun"]>) => {
62
+ if (ended) return;
63
+ ended = true;
64
+ this.worker = null;
65
+ this.status = { running: false, lastRun };
66
+ for (const w of this.waiters.splice(0)) w();
67
+ };
68
+ worker.on("message", (m: { kind: string; progress?: SimObserverStatus["progress"]; result?: { changed: number; sessions: number; filesRead: number }; message?: string }) => {
69
+ if (m.kind === "progress") this.status = { ...this.status, progress: m.progress };
70
+ else if (m.kind === "result" && m.result) {
71
+ const r = m.result;
72
+ this.opts.logger.info(`[sim-plugin] observation done: ${r.sessions} sessions (${r.filesRead} read), ${r.changed} predictions changed in ${Date.now() - t0} ms`);
73
+ finish({ at: new Date().toISOString(), changed: r.changed, sessions: r.sessions, filesRead: r.filesRead, durationMs: Date.now() - t0 });
74
+ } else if (m.kind === "error" || m.kind === "load-failed" || m.kind === "cancelled") {
75
+ const error = m.kind === "cancelled" ? "cancelled" : (m.message ?? m.kind);
76
+ if (m.kind !== "cancelled") this.opts.logger.error(`[sim-plugin] observation failed: ${error}`);
77
+ finish({ at: new Date().toISOString(), changed: 0, sessions: 0, filesRead: 0, durationMs: Date.now() - t0, error });
78
+ }
79
+ });
80
+ worker.on("error", (err: unknown) => {
81
+ const message = err instanceof Error ? err.message : String(err);
82
+ this.opts.logger.error(`[sim-plugin] observation worker error: ${message}`);
83
+ finish({ at: new Date().toISOString(), changed: 0, sessions: 0, filesRead: 0, durationMs: Date.now() - t0, error: message });
84
+ });
85
+ worker.on("exit", () => finish({ at: new Date().toISOString(), changed: 0, sessions: 0, filesRead: 0, durationMs: Date.now() - t0, error: "worker exited" }));
86
+ return true;
87
+ }
88
+
89
+ /** Resolve when the current run (if any) ends. */
90
+ whenIdle(): Promise<void> {
91
+ return this.worker ? new Promise((r) => this.waiters.push(r)) : Promise.resolve();
92
+ }
93
+
94
+ cancel(): void {
95
+ this.worker?.postMessage({ kind: "cancel" });
96
+ }
97
+
98
+ schedule(enabled: () => boolean, everyMs = HOURLY_MS): void {
99
+ this.stopSchedule();
100
+ this.timer = setInterval(() => {
101
+ if (enabled()) this.start();
102
+ }, everyMs);
103
+ this.timer.unref?.();
104
+ }
105
+
106
+ stopSchedule(): void {
107
+ if (this.timer) clearInterval(this.timer);
108
+ this.timer = null;
109
+ }
110
+
111
+ async shutdown(): Promise<void> {
112
+ this.stopSchedule();
113
+ if (this.worker) {
114
+ const w = this.worker;
115
+ await w.terminate();
116
+ }
117
+ }
118
+ }
119
+
@@ -0,0 +1,381 @@
1
+ /**
2
+ * `/api/sim/*` routes (design D9). Every route with a `cwd` admits it with
3
+ * the shared tri-state `admitCwd` + `admissionAllows` (400 / 503 / 403).
4
+ * Ids must match `^[pade]-[0-9a-z]{8,32}$` (400 otherwise) and are only ever
5
+ * joined to a scope root's fixed subdirectory. Mutations go through the sim
6
+ * core (`writeEvent`, `linkDraft`, `writeConfigPatch`), so every validation
7
+ * and the D8 content screen apply.
8
+ */
9
+ import { homedir } from "node:os";
10
+ import {
11
+ type Admission,
12
+ type AdmitCwdOptions,
13
+ admissionAllows,
14
+ admitCwd,
15
+ releaseAdmission,
16
+ } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
17
+ import {
18
+ type AttemptView,
19
+ checkGlobalGlobs,
20
+ checkProjectGlobs,
21
+ DEFAULT_GLOBAL_GLOBS,
22
+ DEFAULT_PROJECT_GLOBS,
23
+ dismissDraft,
24
+ gitInfo,
25
+ globalConfigPath,
26
+ ID_RE,
27
+ linkDraft,
28
+ listDraftsFor,
29
+ loadGlobalConfig,
30
+ loadProjectConfig,
31
+ loadScope,
32
+ type LoadedScope,
33
+ type Prediction,
34
+ type ProblemView,
35
+ PROBLEM_ID_RE,
36
+ projectConfigPath,
37
+ readRawConfig,
38
+ type SimEventInput,
39
+ writeConfigPatch,
40
+ writeEvent,
41
+ } from "@blackbelt-technology/pi-dashboard-sim-extension/core";
42
+ import type { FastifyInstance, FastifyReply } from "fastify";
43
+ import type {
44
+ SimAttempt,
45
+ SimDraft,
46
+ SimPrediction,
47
+ SimProblemDetail,
48
+ SimProblemSummary,
49
+ SimProblemsResponse,
50
+ SimScope,
51
+ } from "../shared/types.js";
52
+ import type { SimObserver } from "./observer.js";
53
+
54
+ export interface SimRouteDeps {
55
+ agentDir: string;
56
+ knownCwds: () => string[];
57
+ admitOptions?: AdmitCwdOptions;
58
+ observer?: Pick<SimObserver, "start" | "getStatus" | "isRunning">;
59
+ homeDir?: string;
60
+ }
61
+
62
+ type Q = { cwd?: string; scope?: string };
63
+
64
+ function deny(reply: FastifyReply, cwd: string | undefined, admission: Admission | { kind: "refuse" }): void {
65
+ if (!cwd) {
66
+ reply.code(400).send({ error: "Missing cwd" });
67
+ return;
68
+ }
69
+ if (admission.kind === "indeterminate") {
70
+ reply.code(503).header("Retry-After", "1").send({ error: "cwd-admission-unavailable", retryAfterMs: 1000 });
71
+ return;
72
+ }
73
+ reply.code(403).send({ error: "cwd not allowed", reason: "cwd is not a known session or pinned directory." });
74
+ }
75
+
76
+ async function admit(deps: SimRouteDeps, reply: FastifyReply, cwd: string | undefined): Promise<Admission | { kind: "refuse" }> {
77
+ if (typeof cwd !== "string" || !cwd) return { kind: "refuse" };
78
+ const a = await admitCwd(cwd, deps.knownCwds, deps.admitOptions);
79
+ if (a.kind === "admit") reply.raw.once("close", () => releaseAdmission((a as Extract<Admission, { kind: "admit" }>).token));
80
+ return a;
81
+ }
82
+
83
+ const scopeOf = (s: string | undefined): SimScope | null => (s === undefined || s === "project" ? "project" : s === "global" ? "global" : null);
84
+
85
+ function toPrediction(a: AttemptView, i: number): SimPrediction {
86
+ const p = a.attempt.predicted[i];
87
+ const o = a.outcomes[i];
88
+ return {
89
+ kind: p.kind,
90
+ value: p.value,
91
+ result: o.result,
92
+ source: o.source,
93
+ localEvidence: o.source === "recurrence" || o.source === "oracle",
94
+ ...(o.auto?.counts ? { counts: { nb: o.auto.counts.nb, cb: o.auto.counts.cb, na: o.auto.counts.na, ca: o.auto.counts.ca } } : {}),
95
+ ...(o.auto?.run ? { run: o.auto.run } : {}),
96
+ ...(o.source === "manual" && o.auto ? { autoResult: o.auto.result } : {}),
97
+ };
98
+ }
99
+
100
+ /**
101
+ * An attempt withheld by the CONTENT SCREEN (secret, injection marker, machine
102
+ * path, over-long) is redacted for every client: the reason is shown, the text
103
+ * is not. Unreviewed web-derived attempts stay readable — a human must read them
104
+ * to approve them.
105
+ */
106
+ const redacted = (a: AttemptView): boolean => !a.deliverable && a.withheldReason !== "unreviewed web-derived content";
107
+ const REDACTED = "[withheld]";
108
+
109
+ function toAttempt(a: AttemptView): SimAttempt {
110
+ const x = a.attempt;
111
+ const hide = redacted(a);
112
+ return {
113
+ id: x.id,
114
+ problemId: x.problemId,
115
+ at: x.at,
116
+ what: hide ? REDACTED : x.what,
117
+ rationale: hide ? REDACTED : x.rationale,
118
+ files: hide ? [] : x.files,
119
+ trust: x.trust,
120
+ status: a.status,
121
+ reviewed: a.reviewed,
122
+ deliverable: a.deliverable,
123
+ ...(a.withheldReason ? { withheldReason: a.withheldReason } : {}),
124
+ provenance: {
125
+ projectName: x.provenance.projectName,
126
+ model: x.provenance.model,
127
+ provider: x.provenance.provider,
128
+ branch: x.provenance.branch,
129
+ headSha: x.provenance.headSha,
130
+ },
131
+ predictions: x.predicted.map((_, i) => (hide ? { ...toPrediction(a, i), value: REDACTED, run: undefined } : toPrediction(a, i))),
132
+ };
133
+ }
134
+
135
+ function summary(p: ProblemView): SimProblemSummary {
136
+ const last = p.attempts[p.attempts.length - 1];
137
+ // Header fallback only from an attempt that is not content-screened out.
138
+ const readable = p.attempts.find((a) => !redacted(a));
139
+ return {
140
+ id: p.id,
141
+ name: p.name ?? readable?.attempt.problemName ?? p.id,
142
+ description: p.description ?? readable?.attempt.problemDescription,
143
+ withheld: p.withheld,
144
+ attempts: p.attempts.length,
145
+ pending: p.attempts.filter((a) => a.status === "pending").length,
146
+ hitRate: p.hitRate,
147
+ latestAt: p.latestAt,
148
+ latestOutcome: last ? last.outcomes.map((o) => o.result).join("/") : "n/a",
149
+ };
150
+ }
151
+
152
+ export function mountSimRoutes(fastify: FastifyInstance, deps: SimRouteDeps): void {
153
+ const home = deps.homeDir ?? homedir();
154
+ const agent = deps.agentDir;
155
+
156
+ /** Resolve the scope for a request; sends the error reply and returns null on refusal. */
157
+ const resolveScope = async (q: Q, reply: FastifyReply): Promise<{ scope: SimScope; toplevel?: string; cwd?: string } | null> => {
158
+ const scope = scopeOf(q.scope);
159
+ if (!scope) {
160
+ reply.code(400).send({ error: "scope must be project or global" });
161
+ return null;
162
+ }
163
+ if (scope === "global" && !q.cwd) return { scope };
164
+ const admission = await admit(deps, reply, q.cwd);
165
+ if (!admissionAllows(admission as Admission, q.cwd)) {
166
+ deny(reply, q.cwd, admission);
167
+ return null;
168
+ }
169
+ if (scope === "global") return { scope, cwd: q.cwd };
170
+ const g = gitInfo(q.cwd);
171
+ if (!g) {
172
+ reply.code(400).send({ error: "project scope needs a git repository", code: "not-a-repo" });
173
+ return null;
174
+ }
175
+ return { scope, toplevel: g.toplevel, cwd: q.cwd };
176
+ };
177
+
178
+ const load = (s: { scope: SimScope; toplevel?: string }): LoadedScope =>
179
+ loadScope(s.scope, { agentDir: agent, toplevel: s.toplevel, homeDir: home });
180
+
181
+ fastify.get<{ Querystring: Q }>("/api/sim/problems", async (req, reply) => {
182
+ const s = await resolveScope(req.query, reply);
183
+ if (!s) return;
184
+ const l = load(s);
185
+ const views = l.problems.flatMap((p) => p.attempts);
186
+ const unlinked = s.cwd ? listDraftsFor(agent, s.cwd).filter((d) => d.scope === s.scope).length : 0;
187
+ const body: SimProblemsResponse = {
188
+ scope: s.scope,
189
+ problems: l.problems.map(summary),
190
+ pendingQueue: views
191
+ .filter((a) => a.status === "pending")
192
+ .map((a) => ({ attempt: a.attempt.id, problemId: a.resolvedProblemId, at: a.attempt.at, what: redacted(a) ? REDACTED : a.attempt.what })),
193
+ withheldQueue: views
194
+ .filter((a) => !a.deliverable)
195
+ .map((a) => ({ attempt: a.attempt.id, problemId: a.resolvedProblemId, at: a.attempt.at, reason: a.withheldReason ?? "withheld", trust: a.attempt.trust })),
196
+ summary: { problems: l.problems.length, pending: views.filter((a) => a.status === "pending").length, unlinked },
197
+ unreadable: l.data.malformed.length,
198
+ observer: deps.observer?.getStatus() ?? { running: false },
199
+ };
200
+ return body;
201
+ });
202
+
203
+ fastify.get<{ Querystring: Q; Params: { id: string } }>("/api/sim/problems/:id", async (req, reply) => {
204
+ const { id } = req.params;
205
+ if (!PROBLEM_ID_RE.test(id)) {
206
+ reply.code(400).send({ error: "invalid id" });
207
+ return;
208
+ }
209
+ const s = await resolveScope(req.query, reply);
210
+ if (!s) return;
211
+ const p = load(s).problems.find((x) => x.id === id);
212
+ if (!p) {
213
+ reply.code(404).send({ error: "unknown problem" });
214
+ return;
215
+ }
216
+ const detail: SimProblemDetail = { ...summary(p), timeline: p.attempts.map(toAttempt) };
217
+ return { problem: detail };
218
+ });
219
+
220
+ fastify.get<{ Querystring: Q }>("/api/sim/unlinked", async (req, reply) => {
221
+ const { cwd } = req.query;
222
+ const admission = await admit(deps, reply, cwd);
223
+ if (!admissionAllows(admission as Admission, cwd)) {
224
+ deny(reply, cwd, admission);
225
+ return;
226
+ }
227
+ const drafts: SimDraft[] = listDraftsFor(agent, cwd).map((d) => ({
228
+ id: d.id,
229
+ path: d.path,
230
+ scope: d.scope,
231
+ tool: d.tool,
232
+ at: d.at,
233
+ ...(d.provenance.model ? { model: d.provenance.model } : {}),
234
+ }));
235
+ return { drafts };
236
+ });
237
+
238
+ fastify.post<{
239
+ Querystring: Q;
240
+ Params: { id: string };
241
+ Body: { problem?: { name?: string; description?: string; id?: string }; rationale?: string; what?: string; predicted?: Prediction[] };
242
+ }>("/api/sim/unlinked/:id/link", async (req, reply) => {
243
+ const { id } = req.params;
244
+ if (!ID_RE.test(id) || !id.startsWith("d-")) {
245
+ reply.code(400).send({ error: "invalid id" });
246
+ return;
247
+ }
248
+ const { cwd } = req.query;
249
+ const admission = await admit(deps, reply, cwd);
250
+ if (!admissionAllows(admission as Admission, cwd)) {
251
+ deny(reply, cwd, admission);
252
+ return;
253
+ }
254
+ const b = req.body ?? {};
255
+ try {
256
+ const res = linkDraft(
257
+ agent,
258
+ cwd,
259
+ id,
260
+ { problem: b.problem ?? {}, rationale: String(b.rationale ?? ""), what: b.what, predicted: Array.isArray(b.predicted) ? b.predicted : [] },
261
+ { homeDir: home },
262
+ );
263
+ reply.code(201);
264
+ return { attempt: res.attempt.id, problemId: res.attempt.problemId, scope: res.scope };
265
+ } catch (err) {
266
+ const msg = err instanceof Error ? err.message : String(err);
267
+ reply.code(/unknown draft/.test(msg) ? 404 : 400).send({ error: msg });
268
+ }
269
+ });
270
+
271
+ fastify.delete<{ Querystring: Q; Params: { id: string } }>("/api/sim/unlinked/:id", async (req, reply) => {
272
+ const { id } = req.params;
273
+ if (!ID_RE.test(id) || !id.startsWith("d-")) {
274
+ reply.code(400).send({ error: "invalid id" });
275
+ return;
276
+ }
277
+ const { cwd } = req.query;
278
+ const admission = await admit(deps, reply, cwd);
279
+ if (!admissionAllows(admission as Admission, cwd)) {
280
+ deny(reply, cwd, admission);
281
+ return;
282
+ }
283
+ if (!dismissDraft(agent, cwd, id)) {
284
+ reply.code(404).send({ error: "unknown draft" });
285
+ return;
286
+ }
287
+ reply.code(204).send();
288
+ });
289
+
290
+ fastify.post<{ Querystring: Q; Body: SimEventInput }>("/api/sim/events", async (req, reply) => {
291
+ const s = await resolveScope(req.query, reply);
292
+ if (!s) return;
293
+ const b = (req.body ?? {}) as SimEventInput & Record<string, unknown>;
294
+ for (const k of ["attempt", "from", "into"] as const) {
295
+ const v = b[k];
296
+ if (v !== undefined && (typeof v !== "string" || !ID_RE.test(v))) {
297
+ reply.code(400).send({ error: `invalid ${k}` });
298
+ return;
299
+ }
300
+ }
301
+ try {
302
+ const l = load(s);
303
+ const e = writeEvent(l.root, b, l.data);
304
+ reply.code(201);
305
+ return { event: e };
306
+ } catch (err) {
307
+ reply.code(400).send({ error: err instanceof Error ? err.message : String(err) });
308
+ }
309
+ });
310
+
311
+ fastify.post<{ Body: { redo?: boolean } }>("/api/sim/observe", async (req, reply) => {
312
+ if (!deps.observer) {
313
+ reply.code(503).send({ error: "observer unavailable" });
314
+ return;
315
+ }
316
+ if (!deps.observer.start(req.body?.redo === true)) {
317
+ reply.code(409).send({ error: "observation already running", observer: deps.observer.getStatus() });
318
+ return;
319
+ }
320
+ reply.code(202);
321
+ return { started: true, observer: deps.observer.getStatus() };
322
+ });
323
+
324
+ fastify.get<{ Querystring: Q }>("/api/sim/config", async (req, reply) => {
325
+ const s = await resolveScope(req.query, reply);
326
+ if (!s) return;
327
+ if (s.scope === "global") {
328
+ const c = loadGlobalConfig(agent);
329
+ const raw = readRawConfig(globalConfigPath(agent));
330
+ // `harnessGlobs` = the user's own globs (editable); defaults are listed apart, so a save never copies them.
331
+ const custom = checkGlobalGlobs(Array.isArray(raw.harnessGlobs) ? raw.harnessGlobs : []).valid;
332
+ return { scope: "global", config: { ...c, harnessGlobs: custom, defaults: [...DEFAULT_GLOBAL_GLOBS] }, raw };
333
+ }
334
+ const c = loadProjectConfig(s.toplevel as string);
335
+ const raw = readRawConfig(projectConfigPath(s.toplevel as string));
336
+ const custom = checkProjectGlobs(Array.isArray(raw.harnessGlobs) ? raw.harnessGlobs : []);
337
+ return { scope: "project", config: { harnessGlobs: custom.valid, invalid: c.invalid, defaults: [...DEFAULT_PROJECT_GLOBS] }, raw };
338
+ });
339
+
340
+ fastify.put<{ Querystring: Q; Body: Record<string, unknown> }>("/api/sim/config", async (req, reply) => {
341
+ const s = await resolveScope(req.query, reply);
342
+ if (!s) return;
343
+ const body = req.body;
344
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
345
+ reply.code(400).send({ error: "body must be an object" });
346
+ return;
347
+ }
348
+ const picked = s.scope === "global" ? pickGlobal(body) : { patch: body };
349
+ if ("error" in picked) {
350
+ reply.code(400).send({ error: picked.error });
351
+ return;
352
+ }
353
+ const patch = picked.patch;
354
+ const file = s.scope === "global" ? globalConfigPath(agent) : projectConfigPath(s.toplevel as string);
355
+ const res = writeConfigPatch(file, patch, s.scope);
356
+ if (!res.ok) {
357
+ reply.code(400).send({ error: res.error });
358
+ return;
359
+ }
360
+ return { ok: true, config: res.config };
361
+ });
362
+ }
363
+
364
+ const num = (v: unknown, lo: number, hi: number): boolean => typeof v === "number" && Number.isInteger(v) && v >= lo && v <= hi;
365
+ const GLOBAL_RULES: Record<string, [check: (v: unknown) => boolean, expect: string]> = {
366
+ harnessGlobs: [(v) => Array.isArray(v) && v.length <= 100, "an array of at most 100 globs"],
367
+ deliveryBudget: [(v) => num(v, 1024, 64 * 1024), "an integer from 1024 to 65536"],
368
+ windowN: [(v) => num(v, 1, 200), "an integer from 1 to 200"],
369
+ autoObserve: [(v) => typeof v === "boolean", "a boolean"],
370
+ webTools: [(v) => Array.isArray(v) && v.length <= 50 && v.every((x) => typeof x === "string" && x.length > 0 && x.length <= 128), "at most 50 tool names"],
371
+ };
372
+
373
+ /** Validate a global-config patch: unknown keys refused, every value in range (no silent drops). */
374
+ function pickGlobal(body: Record<string, unknown>): { patch: Record<string, unknown> } | { error: string } {
375
+ for (const [k, v] of Object.entries(body)) {
376
+ const rule = GLOBAL_RULES[k];
377
+ if (!rule) return { error: `unknown global setting ${k}` };
378
+ if (!rule[0](v)) return { error: `${k} must be ${rule[1]}` };
379
+ }
380
+ return { patch: body };
381
+ }
@@ -0,0 +1,95 @@
1
+ /** Wire types of the `/api/sim/*` routes (server ↔ client). See change: add-self-improvement-memory. */
2
+
3
+ export type SimScope = "project" | "global";
4
+ export type OutcomeResult = "fixed" | "reduced" | "missed" | "inconclusive";
5
+
6
+ export interface SimPrediction {
7
+ kind: "signature" | "oracle";
8
+ value: string;
9
+ result: OutcomeResult | "pending";
10
+ /** manual | recurrence | oracle | none */
11
+ source: string;
12
+ /** Automatic outcomes are machine-local evidence. */
13
+ localEvidence: boolean;
14
+ counts?: { nb: number; cb: number; na: number; ca: number };
15
+ run?: { sessionFile: string; at: string; ok: boolean; command: string };
16
+ /** The automatic result kept underneath a manual override. */
17
+ autoResult?: OutcomeResult | "pending";
18
+ }
19
+
20
+ export interface SimAttempt {
21
+ id: string;
22
+ problemId: string;
23
+ at: string;
24
+ what: string;
25
+ rationale: string;
26
+ files: string[];
27
+ trust: "agent" | "web-derived" | "user";
28
+ status: "pending" | "observed" | "reverted";
29
+ reviewed: boolean;
30
+ deliverable: boolean;
31
+ withheldReason?: string;
32
+ provenance: { projectName: string; model?: string; provider?: string; branch?: string; headSha?: string };
33
+ predictions: SimPrediction[];
34
+ }
35
+
36
+ export interface SimProblemSummary {
37
+ id: string;
38
+ name: string;
39
+ description?: string;
40
+ withheld: boolean;
41
+ attempts: number;
42
+ pending: number;
43
+ hitRate: number | null;
44
+ latestAt: string;
45
+ latestOutcome: string;
46
+ }
47
+
48
+ export interface SimProblemDetail extends SimProblemSummary {
49
+ timeline: SimAttempt[];
50
+ }
51
+
52
+ export interface SimDraft {
53
+ id: string;
54
+ path: string;
55
+ scope: SimScope;
56
+ tool: string;
57
+ at: string;
58
+ model?: string;
59
+ }
60
+
61
+ export interface SimObserverStatus {
62
+ running: boolean;
63
+ progress?: { phase: string; done: number; total: number };
64
+ lastRun?: { at: string; changed: number; sessions: number; filesRead: number; durationMs: number; error?: string };
65
+ }
66
+
67
+ export interface SimProblemsResponse {
68
+ scope: SimScope;
69
+ problems: SimProblemSummary[];
70
+ /** Attempts waiting for an outcome. */
71
+ pendingQueue: Array<{ attempt: string; problemId: string; at: string; what: string }>;
72
+ /** Attempts withheld from delivery (content screen / unreviewed web-derived). */
73
+ withheldQueue: Array<{ attempt: string; problemId: string; at: string; reason: string; trust: string }>;
74
+ summary: { problems: number; pending: number; unlinked: number };
75
+ /** Record files this server could not read (malformed / hand-broken). */
76
+ unreadable?: number;
77
+ observer: SimObserverStatus;
78
+ }
79
+
80
+ export interface SimGlobalConfig {
81
+ /** The user's own global globs (defaults are in `defaults`). */
82
+ harnessGlobs: string[];
83
+ defaults?: string[];
84
+ deliveryBudget: number;
85
+ windowN: number;
86
+ autoObserve: boolean;
87
+ webTools: string[];
88
+ invalid: Array<{ glob: string; reason: string }>;
89
+ }
90
+
91
+ export interface SimProjectConfig {
92
+ harnessGlobs: string[];
93
+ invalid: Array<{ glob: string; reason: string }>;
94
+ defaults: string[];
95
+ }