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,201 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { realpathSync, existsSync, readdirSync, statSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { execFileSync } from "node:child_process";
5
+ import { atomicWriteText, dumpFrontmatter, loadFrontmatter, SchemaError, withFileLock } from "./core.js";
6
+ const home = () => process.env.UNCAMP_HOME || path.join(process.env.HOME || process.env.USERPROFILE || ".", ".uncamp");
7
+ export const defaultIndexPath = (root = home()) => path.join(root, "index.md");
8
+ export function isEphemeralRoot(input) {
9
+ let resolved = path.resolve(input);
10
+ if (resolved.startsWith("/private/var/folders/"))
11
+ resolved = resolved.replace(/^\/private\/var\/folders\//, "/var/folders/");
12
+ return ["/tmp", "/private/tmp", "/var/folders"].some((prefix) => resolved === prefix || resolved.startsWith(prefix + path.sep));
13
+ }
14
+ export async function loadIndex(file = defaultIndexPath()) {
15
+ try {
16
+ const text = await readFile(file, "utf8");
17
+ if (file.endsWith(".json") || text.trimStart().startsWith("{"))
18
+ return JSON.parse(text);
19
+ const [meta, body] = loadFrontmatter(text);
20
+ let projects = meta.projects;
21
+ if (!projects) {
22
+ const m = body.match(/```json\s*([\s\S]*?)```/);
23
+ projects = m ? JSON.parse(m[1]) : [];
24
+ }
25
+ return { schema_version: Number(meta.schema_version || 1), projects };
26
+ }
27
+ catch (e) {
28
+ if (e?.code === "ENOENT")
29
+ return { schema_version: 1, projects: [] };
30
+ throw e;
31
+ }
32
+ }
33
+ export async function upsertProject(file, args) {
34
+ if (!args.allowEphemeral &&
35
+ args.roots.length &&
36
+ args.roots.every(isEphemeralRoot) &&
37
+ path.resolve(file) === path.resolve(defaultIndexPath()))
38
+ return loadIndex(file);
39
+ return withFileLock(file, async () => {
40
+ const doc = await loadIndex(file), memory = path.resolve(args.memory_dir), roots = args.roots.map((p) => path.resolve(p));
41
+ const next = {
42
+ id: args.project_id,
43
+ display_name: args.display_name || path.basename(args.roots[0] || args.project_id),
44
+ roots,
45
+ memory_dir: memory,
46
+ memory_log: memory,
47
+ opt_out: !!args.opt_out,
48
+ updated_at: new Date().toISOString(),
49
+ };
50
+ const rows = [...(doc.projects || [])];
51
+ const i = rows.findIndex((r) => r.id === args.project_id);
52
+ if (i >= 0)
53
+ rows[i] = { ...rows[i], ...next };
54
+ else
55
+ rows.push(next);
56
+ const key = (r) => (r.roots ?? [])
57
+ .map((p) => path.resolve(p))
58
+ .sort()
59
+ .join("\0"), ownKey = key(next), dups = rows.filter((r) => r.id !== args.project_id && key(r) === ownKey);
60
+ if (dups.length) {
61
+ let merged = { ...dups[0], ...next };
62
+ for (const d of dups)
63
+ for (const [k, v] of Object.entries(d))
64
+ if (!["id", "display_name", "roots", "memory_dir", "memory_log", "opt_out", "updated_at"].includes(k) &&
65
+ merged[k] === undefined)
66
+ merged[k] = v;
67
+ const grouped = [...dups, rows.find((r) => r.id === args.project_id)].filter(Boolean), first = Math.min(...grouped.map((d) => rows.indexOf(d)));
68
+ const filtered = rows.filter((r) => !grouped.includes(r));
69
+ filtered.splice(Math.min(first, filtered.length), 0, merged);
70
+ rows.splice(0, rows.length, ...filtered);
71
+ }
72
+ const meta = { schema_version: 1, projects: rows };
73
+ const body = `uncamp project index. Skills maintain this file. The app reads it; Home does not call a model to open.\n\n` +
74
+ `\`\`\`json\n${JSON.stringify(rows, null, 2)}\n\`\`\`\n`;
75
+ await atomicWriteText(file, dumpFrontmatter(meta, body));
76
+ return { schema_version: 1, projects: rows };
77
+ });
78
+ }
79
+ export async function removeProject(file, root) {
80
+ return withFileLock(file, async () => {
81
+ const doc = await loadIndex(file), resolved = path.resolve(root), rows = (doc.projects ?? []).filter((x) => !(x.roots ?? []).some((p) => path.resolve(p) === resolved));
82
+ const meta = { schema_version: 1, projects: rows }, body = `uncamp project index. Skills maintain this file.\n\n` +
83
+ `\`\`\`json\n${JSON.stringify(rows, null, 2)}\n\`\`\`\n`;
84
+ await atomicWriteText(file, dumpFrontmatter(meta, body));
85
+ return { schema_version: 1, projects: rows };
86
+ });
87
+ }
88
+ export function isProjectUncampDir(candidate) {
89
+ const root = path.resolve(candidate), state = path.join(root, ".uncamp");
90
+ try {
91
+ if (realpathSync(state) === realpathSync(path.join(process.env.HOME || "~", ".uncamp")))
92
+ return false;
93
+ }
94
+ catch { }
95
+ if (["preferences.json", "opt-out", "suppressed-items.json"].some((name) => existsSync(path.join(state, name))))
96
+ return true;
97
+ for (const name of ["hooks", "memory"]) {
98
+ const p = path.join(state, name);
99
+ try {
100
+ if (readdirSync(p).length > 0)
101
+ return true;
102
+ }
103
+ catch { }
104
+ }
105
+ return existsSync(path.join(state, "memory.jsonl")) && statSync(path.join(state, "memory.jsonl")).size > 0;
106
+ }
107
+ export function primaryWorktreePath(repo) {
108
+ try {
109
+ const out = execFileSync("git", ["-C", path.resolve(repo), "worktree", "list", "--porcelain"], {
110
+ encoding: "utf8",
111
+ });
112
+ const first = out.split("\n").find((x) => x.startsWith("worktree "));
113
+ return first ? path.resolve(first.slice(9)) : undefined;
114
+ }
115
+ catch {
116
+ return undefined;
117
+ }
118
+ }
119
+ export function traceProjectRoot(start = process.cwd()) {
120
+ let cur = path.resolve(start);
121
+ while (cur !== path.dirname(cur)) {
122
+ if (isProjectUncampDir(cur))
123
+ return cur;
124
+ cur = path.dirname(cur);
125
+ }
126
+ try {
127
+ const top = realpathSync(execFileSync("git", ["-C", path.resolve(start), "rev-parse", "--show-toplevel"], {
128
+ encoding: "utf8",
129
+ stdio: ["ignore", "pipe", "ignore"],
130
+ }).trim()), primary = primaryWorktreePath(top);
131
+ if (primary && isProjectUncampDir(primary))
132
+ return primary;
133
+ return primary || top;
134
+ }
135
+ catch {
136
+ return path.resolve(start);
137
+ }
138
+ }
139
+ export function isOptedOut(projectRoot) {
140
+ return existsSync(path.join(traceProjectRoot(projectRoot), ".uncamp", "opt-out"));
141
+ }
142
+ export async function projectInIndex(projectRoot, indexFile = defaultIndexPath()) {
143
+ const root = traceProjectRoot(projectRoot);
144
+ const doc = await loadIndex(indexFile);
145
+ return (doc.projects ?? []).some((row) => !row.opt_out &&
146
+ (row.roots ?? []).some((entry) => path.resolve(entry) === root || traceProjectRoot(entry) === root));
147
+ }
148
+ export async function isLocallyConfigured(projectRoot) {
149
+ const file = path.join(traceProjectRoot(projectRoot), ".uncamp", "preferences.json");
150
+ try {
151
+ return JSON.parse(await readFile(file, "utf8")).configured !== false;
152
+ }
153
+ catch {
154
+ return false;
155
+ }
156
+ }
157
+ export async function skillsMayAct(projectRoot, indexFile = defaultIndexPath()) {
158
+ const root = traceProjectRoot(projectRoot);
159
+ if (isOptedOut(root))
160
+ return false;
161
+ return (await isLocallyConfigured(root)) || (await projectInIndex(root, indexFile));
162
+ }
163
+ export async function configuredProject(input) {
164
+ const root = path.resolve(input);
165
+ const p = path.join(root, ".uncamp", "preferences.json");
166
+ let d;
167
+ try {
168
+ d = JSON.parse(await readFile(p, "utf8"));
169
+ }
170
+ catch {
171
+ throw new SchemaError(`project is not configured: ${root}`);
172
+ }
173
+ if (d.configured === false)
174
+ throw new SchemaError(`project is not configured: ${root}`);
175
+ return { root, entry: { id: path.basename(root), roots: [root] }, memory: path.join(root, ".uncamp", "memory") };
176
+ }
177
+ export async function projectRegister(input) {
178
+ let root = path.resolve(input);
179
+ try {
180
+ root = realpathSync(root);
181
+ await stat(root);
182
+ }
183
+ catch {
184
+ throw new SchemaError(`project path does not exist: ${root}`);
185
+ }
186
+ let id;
187
+ try {
188
+ id = realpathSync(execFileSync("git", ["-C", root, "rev-parse", "--show-toplevel"], { encoding: "utf8" }).trim());
189
+ }
190
+ catch {
191
+ id = root;
192
+ }
193
+ const idx = defaultIndexPath();
194
+ return upsertProject(idx, {
195
+ project_id: path.basename(id),
196
+ display_name: path.basename(root),
197
+ roots: [root],
198
+ memory_dir: path.join(root, ".uncamp", "memory"),
199
+ allowEphemeral: true,
200
+ });
201
+ }
@@ -0,0 +1,107 @@
1
+ import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ const root = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
5
+ const start = "<!-- uncamp-rule:start v=2.0 -->", end = "<!-- uncamp-rule:end -->";
6
+ const ruleBlock = (text) => `${start}\n${text.trim()}\n${end}`;
7
+ export function normalizeManagedBlocks(text, block) {
8
+ const re = /<!-- uncamp-rule:start(?: v=[^>]*)? -->[\s\S]*?<!-- uncamp-rule:end -->/g, matches = [...text.matchAll(re)];
9
+ if (!matches.length)
10
+ return `${text.trimEnd()}${text.trim() ? "\n\n" : ""}${block}\n`;
11
+ let out = text.replace(re, (_, ...args) => String(args.at(-2) ?? "")); // replaced below for duplicate-safe order
12
+ let inserted = false;
13
+ out = text.replace(re, () => {
14
+ if (inserted)
15
+ return "";
16
+ inserted = true;
17
+ return block;
18
+ });
19
+ return out.trimEnd() + "\n";
20
+ }
21
+ export async function syncRules(check = false) {
22
+ const base = root(), source = await readFile(path.join(base, "agent-rules/project-rule.md"), "utf8"), block = ruleBlock(source), files = [
23
+ "AGENTS.md",
24
+ "CLAUDE.md",
25
+ ".cursor/rules/uncamp.mdc",
26
+ "plugins/uncamp/hosts/rules-src/agents-plugin.md",
27
+ "plugins/uncamp/hosts/rules-src/project-cursor.mdc",
28
+ ];
29
+ const drift = [];
30
+ for (const rel of files) {
31
+ let expected = block + "\n";
32
+ if (rel.endsWith(".mdc") || rel.endsWith("project-cursor.mdc"))
33
+ expected = `---\ndescription: uncamp session-end workload pointer.\nalwaysApply: true\n---\n\n${block}\n`;
34
+ let current = "";
35
+ try {
36
+ current = await readFile(path.join(base, rel), "utf8");
37
+ }
38
+ catch { }
39
+ if (rel === "AGENTS.md" || rel === "CLAUDE.md" || rel === ".cursor/rules/uncamp.mdc") {
40
+ const managed = normalizeManagedBlocks(current, block);
41
+ expected =
42
+ rel.endsWith(".mdc") && !managed.startsWith("---\n")
43
+ ? `---\ndescription: uncamp session-end workload pointer.\nalwaysApply: true\n---\n\n${managed}`
44
+ : managed;
45
+ }
46
+ if (current !== expected) {
47
+ if (check)
48
+ drift.push(rel);
49
+ else {
50
+ await mkdir(path.dirname(path.join(base, rel)), { recursive: true });
51
+ await writeFile(path.join(base, rel), expected);
52
+ }
53
+ }
54
+ }
55
+ return drift;
56
+ }
57
+ export async function syncPlugins(output = path.join(root(), "build", "plugins")) {
58
+ const base = root(), skills = ["uncamp", "uncamp-session-end", "uncamp-memory-writer", "uncamp-hygienic-setup"];
59
+ await mkdir(output, { recursive: true });
60
+ const version = JSON.parse(await readFile(path.join(base, "package.json"), "utf8")).version;
61
+ const bundles = [
62
+ ["codex", ".codex-plugin/plugin.json"],
63
+ ["cursor", ".cursor-plugin/plugin.json"],
64
+ ["marketplaces/uncamp", ".claude-plugin/plugin.json"],
65
+ ];
66
+ for (const [folder, meta] of bundles) {
67
+ const dest = path.join(output, folder), plugin = path.join(dest, meta);
68
+ await mkdir(path.dirname(plugin), { recursive: true });
69
+ const payload = {
70
+ name: "uncamp",
71
+ version,
72
+ description: "uncamp: project resource memory and safe workload lifecycle for coding agents.",
73
+ };
74
+ // Cursor loads the plugin's rule only when the manifest points at its rules folder.
75
+ const manifest = folder === "cursor" ? { ...payload, displayName: "uncamp", rules: "./rules" } : payload;
76
+ await writeFile(plugin, JSON.stringify(manifest, null, 2) + "\n");
77
+ for (const s of skills)
78
+ await cp(path.join(base, "skills", s), path.join(dest, "skills", s), { recursive: true, force: true });
79
+ if (folder === "cursor") {
80
+ const rule = await readFile(path.join(base, "plugins/uncamp/hosts/rules-src/project-cursor.mdc"), "utf8");
81
+ await mkdir(path.join(dest, "rules"), { recursive: true });
82
+ await writeFile(path.join(dest, "rules/uncamp.mdc"), rule);
83
+ }
84
+ if (folder === "marketplaces/uncamp") {
85
+ await mkdir(path.join(dest, ".claude-plugin"), { recursive: true });
86
+ await mkdir(path.join(dest, ".codex-plugin"), { recursive: true });
87
+ await writeFile(path.join(dest, ".codex-plugin/plugin.json"), JSON.stringify(payload, null, 2) + "\n");
88
+ await writeFile(path.join(dest, ".claude-plugin/marketplace.json"), JSON.stringify({
89
+ name: "uncamp-local",
90
+ owner: { name: "uncamp" },
91
+ plugins: [{ name: "uncamp", source: "./", version }],
92
+ metadata: { description: "uncamp for Claude Code" },
93
+ }, null, 2) + "\n");
94
+ }
95
+ }
96
+ return output;
97
+ }
98
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
99
+ const check = process.argv.includes("--check");
100
+ const drift = await syncRules(check);
101
+ if (drift.length) {
102
+ console.error(drift.map((x) => `${x}: managed uncamp rule is stale`).join("\n"));
103
+ process.exitCode = 1;
104
+ }
105
+ else if (!check)
106
+ await syncRules(false);
107
+ }
@@ -0,0 +1,158 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { processFact, identityMatches, stopProcess } from "./workloads.js";
4
+ import { SchemaError } from "./core.js";
5
+ const safe = (id) => {
6
+ if (!id?.trim())
7
+ throw new SchemaError("session_id is required");
8
+ return id.replace(/[^\p{L}\p{N}_-]/gu, "_").slice(0, 120);
9
+ };
10
+ const file = (root, id) => path.join(root, ".uncamp", "sessions", `${safe(id)}.json`);
11
+ export function undecided(rows) {
12
+ return (rows ?? []).filter((row) => !row.decision);
13
+ }
14
+ export function decisionMessage(rows) {
15
+ const pending = undecided(rows);
16
+ if (!pending.length)
17
+ return "";
18
+ const labels = pending.map((row) => `${row.pid}${row.reason ? ` (${row.reason})` : ""}`).join(", ");
19
+ return `Before you finish, decide what should happen to each noted workload: ${labels}. Use uncamp_record_resource_decision with decision 'stop' or 'keep'. A keep requires the user's own words as a source starting with 'user:'; ask if unclear.`;
20
+ }
21
+ export async function readSession(root, id) {
22
+ try {
23
+ return JSON.parse(await readFile(file(root, id), "utf8"));
24
+ }
25
+ catch (e) {
26
+ if (e.code === "ENOENT")
27
+ throw new SchemaError(`no session file at ${file(root, id)}`);
28
+ throw e;
29
+ }
30
+ }
31
+ export async function writeSession(root, d) {
32
+ const f = file(root, d.session_id);
33
+ await mkdir(path.dirname(f), { recursive: true });
34
+ await writeFile(f, JSON.stringify(d, null, 2) + "\n");
35
+ return f;
36
+ }
37
+ export async function getSession(root, id) {
38
+ const sid = id ||
39
+ process.env.CODEX_THREAD_ID ||
40
+ process.env.CURSOR_SESSION_ID ||
41
+ process.env.CLAUDE_SESSION_ID ||
42
+ `local-${process.pid}`;
43
+ const f = file(root, sid);
44
+ try {
45
+ return {
46
+ session: JSON.parse(await readFile(f, "utf8")),
47
+ workloads: JSON.parse(await readFile(f, "utf8")).workloads ?? [],
48
+ session_id: sid,
49
+ };
50
+ }
51
+ catch {
52
+ return { session: null, workloads: [], session_id: sid };
53
+ }
54
+ }
55
+ export async function noteWorkload(root, args) {
56
+ const sid = args.session_id ||
57
+ process.env.CODEX_THREAD_ID ||
58
+ process.env.CURSOR_SESSION_ID ||
59
+ process.env.CLAUDE_SESSION_ID ||
60
+ `local-${process.pid}`, p = processFact(args.pid);
61
+ if (!p)
62
+ throw new SchemaError(`workload ${args.pid} is not a live process`);
63
+ let d;
64
+ try {
65
+ d = await readSession(root, sid);
66
+ }
67
+ catch {
68
+ d = {
69
+ schema_version: 1,
70
+ session_id: sid,
71
+ project_id: path.basename(root),
72
+ project_root: root,
73
+ agent: args.agent || "unknown",
74
+ started_at: new Date().toISOString(),
75
+ ended_at: null,
76
+ host_anchor: null,
77
+ workloads: [],
78
+ };
79
+ }
80
+ if (d.ended_at) {
81
+ d = { ...d, started_at: new Date().toISOString(), ended_at: null, workloads: [] };
82
+ }
83
+ const note = {
84
+ pid: p.pid,
85
+ ppid: p.ppid,
86
+ pgid: p.pgid,
87
+ started_at: p.started_at,
88
+ command: p.command,
89
+ kind: args.kind || "process",
90
+ noted_at: new Date().toISOString(),
91
+ };
92
+ if (args.reason?.trim())
93
+ note.reason = args.reason.trim();
94
+ if (args.port)
95
+ note.ports = [args.port];
96
+ const rows = (d.workloads ?? []).filter((x) => !(x.pid === note.pid && x.started_at === note.started_at));
97
+ d.workloads = [...rows, note];
98
+ await writeSession(root, d);
99
+ return { session_id: sid, workloads: d.workloads };
100
+ }
101
+ export async function decideWorkload(root, pid, decision, eventId, sid) {
102
+ const d = await readSession(root, sid);
103
+ const row = d.workloads?.find((x) => x.pid === pid);
104
+ if (!row)
105
+ throw new SchemaError(`resource ${pid} was not noted in this session; note it with uncamp_note_workload first`);
106
+ row.decision = { outcome: decision, event_id: eventId, at: new Date().toISOString() };
107
+ await writeSession(root, d);
108
+ return d.workloads;
109
+ }
110
+ export async function finishSession(root, sid) {
111
+ const s = await getSession(root, sid);
112
+ if (!s.session)
113
+ return { session_id: s.session_id, session: null };
114
+ const d = s.session;
115
+ if (d.ended_at)
116
+ return { session_id: s.session_id, session: d };
117
+ const missing = (d.workloads ?? []).filter((r) => !r.decision);
118
+ if (missing.length)
119
+ throw new SchemaError(`Not closed: no end-of-task decision is recorded for ${missing.map((r) => r.pid + (r.reason ? ` (${r.reason})` : "")).join(", ")}. For each one, call uncamp_record_resource_decision with decision 'stop' (then stop it) or 'keep'. A keep needs the user's own words, asking to leave it running after the task, as a source starting with 'user:' (if unsure, ask the user first), or memory_event_id of a memory entry the user confirmed. If an existing memory entry already covers it, pass that entry's memory_event_id. Then finish again.`);
120
+ d.workloads = await Promise.all((d.workloads ?? []).map(async (r) => ({
121
+ ...Object.fromEntries(["pid", "kind", "reason", "started_at", "command", "decision"]
122
+ .filter((k) => r[k] !== undefined)
123
+ .map((k) => [k, r[k]])),
124
+ running: (() => {
125
+ const p = processFact(r.pid);
126
+ return !!p && identityMatches(p, r);
127
+ })(),
128
+ })));
129
+ d.ended_at = new Date().toISOString();
130
+ await writeSession(root, d);
131
+ return { session_id: s.session_id, session: d };
132
+ }
133
+ export async function stopNoted(root, pid, sid, grace = 5) {
134
+ const s = await getSession(root, sid);
135
+ const row = s.workloads.find((x) => x.pid === pid);
136
+ if (!row)
137
+ throw new SchemaError(`workload ${pid} was not noted in this session; note it with uncamp_note_workload first`);
138
+ if (!row.started_at)
139
+ throw new SchemaError(`workload ${pid} has no verified identity; stop it with the project's native lifecycle`);
140
+ const live = processFact(pid);
141
+ if (!live || !identityMatches(live, row))
142
+ return {
143
+ pid,
144
+ session_id: s.session_id,
145
+ stopped: false,
146
+ gone: true,
147
+ detail: "The noted process is no longer running (or its PID now belongs to another process).",
148
+ };
149
+ const result = stopProcess(pid, grace);
150
+ return {
151
+ pid,
152
+ session_id: s.session_id,
153
+ ...result,
154
+ detail: result.gone
155
+ ? "Stopped and verified gone."
156
+ : "The process is still running after SIGKILL; check it natively.",
157
+ };
158
+ }