uncamp 0.0.0 → 0.1.2

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,399 @@
1
+ import { mkdir, readFile, writeFile, access } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { configuredProject } from "./projectRoot.js";
5
+ import { currentItems, readEvents, writeEventsMarkdown } from "./memory.js";
6
+ import { SchemaError } from "./core.js";
7
+ import { commandHash } from "./workloads.js";
8
+ import { getSession, decideWorkload } from "./session.js";
9
+ import { moveMemoryNoteToTrash } from "./trash.js";
10
+ export async function getProjectGuidance(projectPath, itemIds, prefix) {
11
+ const { root, entry, memory } = await configuredProject(projectPath);
12
+ let rows = await currentItems(await readEvents(memory), root);
13
+ if (prefix) {
14
+ const p = path.resolve(root, prefix);
15
+ rows = rows.filter((r) => r.location === p || r.location.startsWith(p + path.sep));
16
+ }
17
+ if (itemIds === undefined)
18
+ return {
19
+ project_id: entry.id,
20
+ project_path: root,
21
+ count: rows.length,
22
+ catalogue: rows.map((r) => ({
23
+ id: r.id,
24
+ name: r.name,
25
+ kind: r.kind,
26
+ location: r.location,
27
+ event_id: r.event_id,
28
+ situations: r.recommendations.map((x) => x.situation),
29
+ })),
30
+ items: [],
31
+ missing: [],
32
+ };
33
+ const map = new Map(rows.map((r) => [r.id, r]));
34
+ return {
35
+ project_id: entry.id,
36
+ project_path: root,
37
+ count: itemIds.filter((i) => map.has(i)).length,
38
+ catalogue: [],
39
+ items: itemIds.flatMap((i) => (map.has(i) ? [map.get(i)] : [])),
40
+ missing: itemIds.filter((i) => !map.has(i)),
41
+ };
42
+ }
43
+ export async function recordProjectGuidance(a) {
44
+ const { root, entry, memory } = await configuredProject(a.project_path);
45
+ const rows = await currentItems(await readEvents(memory), root), prev = rows.find((r) => r.id === a.item.id);
46
+ if (prev && a.base_event_id !== prev.event_id)
47
+ throw new SchemaError("guidance changed since it was read; retrieve the latest item and reconcile before recording");
48
+ if (!prev && a.base_event_id)
49
+ throw new SchemaError("base_event_id does not identify a current item");
50
+ if (prev && a.item.location !== prev.location)
51
+ throw new SchemaError("an item's location cannot change through guidance update; record and review identity explicitly");
52
+ const e = {
53
+ schema_version: 2,
54
+ event_id: `guidance-${randomUUID()}`,
55
+ event_type: "item_instruction",
56
+ what: { id: a.item.id, name: a.item.name, kind: a.item.kind, location: a.item.location },
57
+ recommendations: a.recommendations,
58
+ claim: a.claim,
59
+ agent: { harness: a.agent, session_id: a.session_id },
60
+ project: { id: entry.id, consumers: [] },
61
+ created: { at: new Date().toISOString(), source: a.claim === "verified" ? "discovered" : a.claim },
62
+ correction_of: a.base_event_id ?? null,
63
+ };
64
+ await writeEventsMarkdown(memory, [e]);
65
+ return {
66
+ ok: true,
67
+ project_id: entry.id,
68
+ item_id: a.item.id,
69
+ event_id: e.event_id,
70
+ revision_of: a.base_event_id ?? null,
71
+ };
72
+ }
73
+ const identityFile = (root) => path.join(root, ".uncamp", "resource-identities.json");
74
+ async function identities(root) {
75
+ try {
76
+ return JSON.parse(await readFile(identityFile(root), "utf8"));
77
+ }
78
+ catch {
79
+ return {};
80
+ }
81
+ }
82
+ async function writeIdentity(root, id, value) {
83
+ const data = await identities(root);
84
+ data[id] = { ...(data[id] ?? {}), ...value };
85
+ await mkdir(path.dirname(identityFile(root)), { recursive: true });
86
+ await writeFile(identityFile(root), JSON.stringify(data, null, 2) + "\n");
87
+ }
88
+ const slug = (s) => s
89
+ .toLowerCase()
90
+ .replace(/[^a-z0-9]+/g, "-")
91
+ .replace(/^-|-$/g, "")
92
+ .slice(0, 60) || "resource";
93
+ export const userConfirmed = (sources) => !!sources?.some((s) => typeof s === "string" && s.trim().toLowerCase().startsWith("user:"));
94
+ function confirmed(sources) {
95
+ return userConfirmed(sources);
96
+ }
97
+ export function entryDecision(item) {
98
+ let decision = null, user = false;
99
+ for (const r of item.recommendations ?? []) {
100
+ const t = String(r.recommendation || "")
101
+ .trim()
102
+ .toLowerCase();
103
+ if (t.startsWith("stop:") || t === "stop")
104
+ decision = "stop";
105
+ if (t.startsWith("keep:") || t === "keep")
106
+ decision = "keep";
107
+ user ||= confirmed(r.sources || []);
108
+ }
109
+ return [decision, user];
110
+ }
111
+ export function noteIdentity(n) {
112
+ const ports = new Set(n.ports ?? []);
113
+ if (Number.isFinite(n.pid))
114
+ for (const p of workloadsApi.listeningPorts(Number(n.pid)))
115
+ ports.add(p);
116
+ const kind = slug(n.kind || ""), parts = String(n.command || "")
117
+ .trim()
118
+ .split(/\s+/), partialExecutableOnly = parts.length === 2 && parts[1].startsWith("/");
119
+ return {
120
+ ports: [...ports].sort((a, b) => a - b),
121
+ kind: ["process", "resource", "workload", "server"].includes(kind) ? null : kind,
122
+ command: partialExecutableOnly ? null : commandHash(n.command),
123
+ };
124
+ }
125
+ export async function savedMemory(root, note, workloads = []) {
126
+ const events = await readEvents(path.join(root, ".uncamp", "memory"));
127
+ const rows = await currentItems(events, root);
128
+ const ids = await identities(root), now = noteIdentity(note), ambiguous = now.kind && workloads.some((x) => x.pid !== note.pid && noteIdentity(x).kind === now.kind), ports = new Set(note.ports ?? []);
129
+ return rows
130
+ .filter((r) => r.id.startsWith("resource:"))
131
+ .flatMap((r) => {
132
+ const i = ids[r.id] ?? {};
133
+ if (!(now.command && i.command && i.command === now.command) &&
134
+ !(now.kind && i.kind === now.kind && !ambiguous) &&
135
+ ![...(i.ports ?? [])].some((p) => ports.has(p)))
136
+ return [];
137
+ let [decision, user] = entryDecision(r);
138
+ decision ??= i.decision ?? null;
139
+ const date = String(events.find((e) => e.event_id === r.event_id)?.created?.at || "").slice(0, 10);
140
+ const text = String(r.recommendations[0]?.recommendation || "")
141
+ .replace(/\s+/g, " ")
142
+ .slice(0, 200);
143
+ const message = decision && user
144
+ ? `Saved memory: user confirmed ${decision} for this resource on ${date}; follow it unless the user says otherwise. Pass memory_event_id=${r.event_id} to uncamp_record_resource_decision.`
145
+ : `Saved memory: ${user ? "user confirmed" : "an earlier session recorded"} this guidance for this resource on ${date}: "${text}". ${user ? "Follow it unless the user says otherwise. " : "Check it before relying on it. "}memory_event_id=${r.event_id}.`;
146
+ return [
147
+ {
148
+ memory_event_id: r.event_id,
149
+ item_id: r.id,
150
+ resource: r.name,
151
+ decision,
152
+ user_confirmed: user,
153
+ date,
154
+ text,
155
+ message,
156
+ },
157
+ ];
158
+ });
159
+ }
160
+ export async function savedMemoryForPid(root, pid, sid) {
161
+ const s = await getSession(root, sid);
162
+ const n = [...s.workloads].reverse().find((r) => r.pid === pid);
163
+ return n ? savedMemory(root, n, s.workloads) : [];
164
+ }
165
+ export async function recordResourceDecision(a) {
166
+ if (!["stop", "keep"].includes(a.decision))
167
+ throw new SchemaError("decision must be 'stop' or 'keep'");
168
+ const { root, memory } = await configuredProject(a.project_path);
169
+ const s = await getSession(root, a.session_id), note = s.workloads.find((r) => r.pid === a.pid);
170
+ if (!note)
171
+ throw new SchemaError(`resource ${a.pid} was not noted in this session; note it with uncamp_note_workload first`);
172
+ const saved = await savedMemory(root, note, s.workloads), same = saved.find((x) => x.user_confirmed && x.decision === a.decision), conflict = saved.find((x) => x.user_confirmed && x.decision && x.decision !== a.decision), sources = a.sources ?? [];
173
+ if (a.decision === "keep" && !a.memory_event_id && !confirmed(sources) && !same)
174
+ throw new SchemaError("a keep needs the user's own words as a source starting with 'user:'; if the user has not clearly asked to leave it running after the task, ask them before recording a keep; otherwise the decision is 'stop'");
175
+ if (conflict && !confirmed(sources))
176
+ throw new SchemaError(`Not recorded: saved memory for this resource (${conflict.resource}, ${conflict.date}) says the user confirmed ${conflict.decision}, and this call says ${a.decision} without new words from the user. Follow the saved memory (call again with memory_event_id=${conflict.memory_event_id}). If the user has just told you otherwise, record their new words as a 'user:' source; that corrects the saved entry.`);
177
+ let itemId, eventId;
178
+ const selected = a.memory_event_id ? saved.find((x) => x.memory_event_id === a.memory_event_id) : same;
179
+ if (a.memory_event_id) {
180
+ const event = (await readEvents(memory)).find((e) => e.event_id === a.memory_event_id);
181
+ if (!event)
182
+ throw new SchemaError(`memory_event_id ${a.memory_event_id} is not in this project's memory`);
183
+ const userSource = (event.recommendations ?? [])
184
+ .flatMap((r) => r.sources ?? [])
185
+ .some((s) => s.trim().toLowerCase().startsWith("user:"));
186
+ if (a.decision === "keep" && !userSource)
187
+ throw new SchemaError("a keep needs a memory entry the user confirmed (a source starting with 'user:'); ask the user or record the decision with their words as a 'user:' source");
188
+ itemId = event.what.id;
189
+ eventId = a.memory_event_id;
190
+ }
191
+ else if (selected && !confirmed(sources)) {
192
+ itemId = selected.item_id;
193
+ eventId = selected.memory_event_id;
194
+ }
195
+ else {
196
+ if (!a.resource?.trim() || !a.reason?.trim())
197
+ throw new SchemaError("pass resource (what it is) and reason (why this decision), or memory_event_id");
198
+ if (!sources.length)
199
+ throw new SchemaError("pass at least one source: the user's words ('user: ...') or what you inspected");
200
+ itemId = saved[0]?.item_id ?? `resource:${slug(a.resource)}`;
201
+ const current = (await currentItems(await readEvents(memory), root)).find((x) => x.id === itemId);
202
+ const rr = await recordProjectGuidance({
203
+ project_path: root,
204
+ item: { id: itemId, name: saved[0]?.resource ?? a.resource, kind: "runtime resource", location: root },
205
+ recommendations: [
206
+ {
207
+ situation: `When ${a.resource} is started in this project and the task is finished`,
208
+ recommendation: `${a.decision}: ${a.reason}`,
209
+ scope: "this project",
210
+ conditions: [],
211
+ rechecks: ["the process is the one this session started"],
212
+ evidence: a.reason,
213
+ sources,
214
+ },
215
+ ],
216
+ claim: "observed",
217
+ agent: a.agent || "unknown",
218
+ session_id: s.session_id,
219
+ base_event_id: current?.event_id,
220
+ });
221
+ eventId = rr.event_id;
222
+ }
223
+ const workloads = await decideWorkload(root, a.pid, a.decision, eventId, s.session_id);
224
+ await writeIdentity(root, itemId, { ...noteIdentity(note), decision: a.decision });
225
+ const undecided = workloads.filter((x) => !x.decision).map((x) => x.pid);
226
+ return {
227
+ ok: true,
228
+ session_id: s.session_id,
229
+ pid: a.pid,
230
+ decision: a.decision,
231
+ event_id: eventId,
232
+ undecided,
233
+ saved_memory: saved,
234
+ detail: `Recorded.${same && !confirmed(sources) ? " Followed the saved memory." : ""} ${a.decision === "stop" ? "Stop it before your final answer." : "Leave it running and tell the user."}${undecided.length ? ` Still undecided: ${undecided.join(", ")}.` : ""}`,
235
+ };
236
+ }
237
+ export async function recordProjectOutcome(a) {
238
+ const { root, entry, memory } = await configuredProject(a.project_path);
239
+ if (!a.summary?.trim())
240
+ throw new SchemaError("summary must say what happened");
241
+ if (!a.evidence?.length)
242
+ throw new SchemaError("evidence must list at least one thing you checked, such as a command and its result");
243
+ const what = { ...a.item };
244
+ const cleanup = {
245
+ outcome: a.outcome,
246
+ operation_id: a.operation_id ||
247
+ `op-${createHash("sha256").update(`${a.item.id}\0${a.outcome}\0${a.session_id}`).digest("hex").slice(0, 16)}`,
248
+ };
249
+ if (a.outcome === "moved") {
250
+ if (!a.trash_destination)
251
+ throw new SchemaError("a moved outcome needs trash_destination, the path the item now has in the Trash");
252
+ try {
253
+ await access(what.location);
254
+ throw new SchemaError(`${what.location} still exists; record a moved outcome after the move`);
255
+ }
256
+ catch (e) {
257
+ if (e instanceof SchemaError)
258
+ throw e;
259
+ }
260
+ try {
261
+ await access(a.trash_destination);
262
+ }
263
+ catch {
264
+ throw new SchemaError(`trash_destination ${a.trash_destination} does not exist`);
265
+ }
266
+ cleanup.trash_destination = a.trash_destination;
267
+ }
268
+ if (["stopped", "stopped_default", "restarted"].includes(a.outcome)) {
269
+ const s = await getSession(root, a.session_id), n = s.workloads.find((x) => x.pid === a.workload_pid);
270
+ if (!n)
271
+ throw new SchemaError(`workload ${a.workload_pid} was not noted in this session; note it with uncamp_note_workload when the process starts`);
272
+ if (processHasIdentity(n))
273
+ throw new SchemaError(`process ${n.pid} started ${n.started_at} is still running; record the outcome after it has stopped`);
274
+ what.location = `runtime://process/${n.pid}`;
275
+ const executable = String(n.command || "")
276
+ .split(/\s+/)
277
+ .find((part) => part.startsWith("/")) || "/unknown";
278
+ what.runtime_identity = { kind: "process", id: String(n.pid), started_at: n.started_at, executable };
279
+ cleanup.runtime_identity = what.runtime_identity;
280
+ delete what.bytes;
281
+ }
282
+ const op = cleanup.operation_id, eventId = "mcp-outcome-" + createHash("sha256").update(`${entry.id}\0${a.item.id}\0${op}`).digest("hex").slice(0, 24);
283
+ const events = await readEvents(memory), old = events.find((x) => x.event_id === eventId);
284
+ if (old)
285
+ return {
286
+ ok: true,
287
+ already_recorded: true,
288
+ project_id: entry.id,
289
+ item_id: a.item.id,
290
+ event_id: eventId,
291
+ location: old.what.location,
292
+ };
293
+ const event = {
294
+ schema_version: 1,
295
+ event_id: eventId,
296
+ event_type: "cleanup_outcome",
297
+ what,
298
+ action: a.outcome,
299
+ why: a.summary,
300
+ cleanup,
301
+ claim: "verified",
302
+ agent: { harness: a.agent, session_id: a.session_id },
303
+ project: { id: entry.id, consumers: [] },
304
+ created: { at: new Date().toISOString(), source: "observed" },
305
+ can_go_when: a.can_go_when || "Nothing pending; this records a completed outcome.",
306
+ evidence_ids: a.evidence,
307
+ correction_of: null,
308
+ };
309
+ await writeEventsMarkdown(memory, [event]);
310
+ return {
311
+ ok: true,
312
+ already_recorded: false,
313
+ project_id: entry.id,
314
+ item_id: a.item.id,
315
+ event_id: eventId,
316
+ location: what.location,
317
+ };
318
+ }
319
+ function processHasIdentity(n) {
320
+ return awaitableFact(n.pid, n);
321
+ }
322
+ function awaitableFact(pid, n) {
323
+ const { processFact, identityMatches } = requireWorkloads();
324
+ const live = processFact(pid);
325
+ return !!live && identityMatches(live, n);
326
+ }
327
+ function requireWorkloads() {
328
+ return workloadsApi;
329
+ }
330
+ import * as workloadsApi from "./workloads.js";
331
+ export async function listMemory(root) {
332
+ const memory = path.join(root, ".uncamp", "memory"), events = await readEvents(memory), items = await currentItems(events, root), ids = await identities(root);
333
+ return {
334
+ count: items.length,
335
+ entries: items.map((item) => {
336
+ const [decision, user_confirmed] = entryDecision(item);
337
+ return {
338
+ ...item,
339
+ file: path.join(memory, `${item.event_id}.md`),
340
+ summary: item.recommendations[0].recommendation,
341
+ decision: decision ?? ids[item.id]?.decision ?? null,
342
+ user_confirmed,
343
+ };
344
+ }),
345
+ };
346
+ }
347
+ export async function viewMemory(root, id) {
348
+ const memory = path.join(root, ".uncamp", "memory"), events = await readEvents(memory), items = await currentItems(events, root), item = items.find((x) => x.id === id);
349
+ if (!item)
350
+ throw new SchemaError(`unknown item_id: ${id}`);
351
+ const revisions = events.filter((e) => e.what?.id === id && e.event_type === "item_instruction");
352
+ const chain = [item.event_id];
353
+ let cursor = revisions.find((e) => e.event_id === item.event_id);
354
+ while (cursor?.correction_of) {
355
+ chain.push(cursor.correction_of);
356
+ cursor = revisions.find((e) => e.event_id === cursor.correction_of);
357
+ }
358
+ const history = chain.reverse();
359
+ const f = path.join(memory, `${item.event_id}.md`);
360
+ return {
361
+ id,
362
+ event_id: item.event_id,
363
+ file: f,
364
+ markdown: await readFile(f, "utf8"),
365
+ history,
366
+ recommendations: item.recommendations,
367
+ };
368
+ }
369
+ export async function editMemory(root, a) {
370
+ if (!confirmed(a.sources || []))
371
+ throw new SchemaError("editing memory requires a source starting with 'user:'");
372
+ const v = await viewMemory(root, a.item_id);
373
+ if (v.event_id !== a.base_event_id)
374
+ throw new SchemaError("item changed since it was read; reload and reconcile the latest instruction");
375
+ const events = await readEvents(path.join(root, ".uncamp", "memory"));
376
+ const old = events.find((e) => e.event_id === v.event_id);
377
+ const e = {
378
+ ...old,
379
+ event_id: `guidance-${randomUUID()}`,
380
+ recommendations: a.recommendations,
381
+ correction_of: v.event_id,
382
+ created: { at: new Date().toISOString(), source: "observed" },
383
+ };
384
+ await writeEventsMarkdown(path.join(root, ".uncamp", "memory"), [e]);
385
+ return { status: "edited", event_id: e.event_id, revision_of: v.event_id, item_id: a.item_id };
386
+ }
387
+ export async function deleteMemory(root, a) {
388
+ if (!confirmed(a.sources || []))
389
+ throw new SchemaError("deleting memory requires a source starting with 'user:'");
390
+ const v = await viewMemory(root, a.item_id);
391
+ const files = v.history.map((id) => path.join(root, ".uncamp", "memory", `${id}.md`));
392
+ const destinations = [];
393
+ for (const f of files)
394
+ destinations.push(await moveMemoryNoteToTrash(root, f));
395
+ const ids = await identities(root);
396
+ delete ids[a.item_id];
397
+ await writeFile(identityFile(root), JSON.stringify(ids, null, 2) + "\n");
398
+ return { status: "moved_to_trash", item_id: a.item_id, files, trash_destinations: destinations };
399
+ }
@@ -0,0 +1,34 @@
1
+ import { copyFile, access, mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ export async function backupBeforeEdit(file) {
4
+ try {
5
+ await access(file);
6
+ }
7
+ catch {
8
+ return undefined;
9
+ }
10
+ const backup = `${file}.uncamp-backup-${Date.now()}`;
11
+ await copyFile(file, backup);
12
+ return backup;
13
+ }
14
+ export async function editJsonConfig(file, update) {
15
+ let data = {};
16
+ try {
17
+ data = JSON.parse(await readFile(file, "utf8"));
18
+ }
19
+ catch { }
20
+ const next = update(data);
21
+ if (JSON.stringify(next) === JSON.stringify(data))
22
+ return next;
23
+ await backupBeforeEdit(file);
24
+ await mkdir(path.dirname(file), { recursive: true });
25
+ await writeFile(file, JSON.stringify(next, null, 2) + "\n");
26
+ return next;
27
+ }
28
+ export function replaceTomlSections(text, sections) {
29
+ for (const header of sections) {
30
+ const escaped = header.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
31
+ text = text.replace(new RegExp(`(?:^|\\n)\\[${escaped}\\]\\n(?:(?!\\[)[^\\n]*(?:\\n|$))*`, "g"), "\n");
32
+ }
33
+ return text.trimEnd() + "\n";
34
+ }
@@ -0,0 +1,7 @@
1
+ export const SUPPORTED_HOSTS = ["codex", "claude", "cursor"];
2
+ export function validateHosts(hosts) {
3
+ for (const h of hosts)
4
+ if (!SUPPORTED_HOSTS.includes(h))
5
+ throw new Error(`unsupported host: ${h}`);
6
+ return hosts;
7
+ }
@@ -0,0 +1,16 @@
1
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+ export async function readManifest(home) {
4
+ try {
5
+ return JSON.parse(await readFile(path.join(home, ".uncamp", "install-manifest.json"), "utf8"));
6
+ }
7
+ catch {
8
+ return { hosts: [], created: [] };
9
+ }
10
+ }
11
+ export async function writeManifest(home, manifest) {
12
+ const file = path.join(home, ".uncamp", "install-manifest.json");
13
+ await mkdir(path.dirname(file), { recursive: true });
14
+ await writeFile(file, JSON.stringify(manifest, null, 2) + "\n");
15
+ return file;
16
+ }