piroboros 0.2.0 → 0.3.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/NOTICE +12 -0
  3. package/README.md +11 -8
  4. package/dist/chat/log.js +1 -1
  5. package/dist/chat/turn.js +0 -15
  6. package/dist/conclave/pipeline.js +216 -13
  7. package/dist/config.js +121 -12
  8. package/dist/diff.js +90 -0
  9. package/dist/durable.js +1 -1
  10. package/dist/guard.js +169 -13
  11. package/dist/learn.js +938 -0
  12. package/dist/memory/akashic/tools.js +25 -28
  13. package/dist/memory/mnemosia/conflicts.js +0 -4
  14. package/dist/memory/mnemosia/orchestrator.js +1 -11
  15. package/dist/memory/mnemosia/policy.js +0 -3
  16. package/dist/memory/mnemosia/rank.js +0 -4
  17. package/dist/memory/mnemosia/rerank.js +3 -30
  18. package/dist/memory/mnemosia/rollback.js +1 -149
  19. package/dist/memory/mnemosia/tokens.js +1 -11
  20. package/dist/memory/mnemosia/tools.js +0 -10
  21. package/dist/memory/mnemosia/types.js +0 -2
  22. package/dist/runtime.js +51 -6
  23. package/dist/search.js +25 -12
  24. package/dist/shell.js +2 -2
  25. package/dist/tui/app.js +15 -3
  26. package/dist/tui/commands.js +5 -2
  27. package/dist/tui/settings.js +4 -1
  28. package/dist/tui/thinking/parse.js +0 -3
  29. package/dist/ws/apply.js +817 -0
  30. package/dist/ws/cas.js +144 -0
  31. package/dist/ws/confine.js +194 -0
  32. package/dist/ws/docker.js +151 -0
  33. package/dist/ws/git.js +162 -0
  34. package/dist/ws/lww.js +48 -0
  35. package/dist/ws/merge.js +129 -0
  36. package/dist/ws/workspace.js +1596 -0
  37. package/dist/ws/wsl.js +259 -0
  38. package/docs/conclave.md +14 -0
  39. package/docs/configuration.md +10 -4
  40. package/docs/privacy.md +3 -1
  41. package/docs/tools.md +43 -1
  42. package/package.json +1 -2
  43. package/settings.json.example +3 -1
package/dist/ws/git.js ADDED
@@ -0,0 +1,162 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { canonicalize } from "../paths.js";
5
+ // Host git for Workspaces. piroboros never runs git with a Workspace as the repository: every call here is against the live
6
+ // repository, carries SAFE_GIT, and gets an environment without any GIT_* name in any letter case, so nothing in the
7
+ // user's shell, a git hook parent or a Workspace config changes what it reads or runs.
8
+ /** A message for the user: the reason a Workspace cannot open or a mode cannot be resolved, with the way out. */
9
+ export class WsRefusal extends Error {
10
+ }
11
+ /** Options that stop the user's own fsmonitor, pager and hooks from running under piroboros. */
12
+ export const safeGit = (home) => ["-c", "core.fsmonitor=false", "-c", "core.pager=cat", "-c", `core.hooksPath=${join(home, "ws", "no-hooks")}`];
13
+ /**
14
+ * piroboros's environment without any GIT_* name (any case: Git for Windows honours a lower-case git_dir), then the fixed
15
+ * ones. check-ignore refuses GIT_LITERAL_PATHSPECS, so it runs without it and gets `./`-prefixed paths instead.
16
+ */
17
+ export function gitEnv(literal, source = process.env) {
18
+ const env = {};
19
+ for (const [name, value] of Object.entries(source))
20
+ if (!/^GIT_/iu.test(name))
21
+ env[name] = value;
22
+ env.GIT_TERMINAL_PROMPT = "0";
23
+ env.LC_ALL = "C";
24
+ if (literal)
25
+ env.GIT_LITERAL_PATHSPECS = "1";
26
+ return env;
27
+ }
28
+ const firstLine = (text) => text.trim().split(/\r?\n/u)[0] ?? "";
29
+ const dubious = (project) => ` piroboros ignores GIT_* variables, including GIT_CONFIG_GLOBAL; run git config --global --add safe.directory ${project} in a shell where GIT_CONFIG_GLOBAL is not set.`;
30
+ /** The config keys copied into a git Workspace; everything else (fsmonitor, hooksPath, filters, includes, credentials) is dropped. */
31
+ const CONFIG_KEYS = /^(?:core\.(?:repositoryformatversion|bare|filemode|symlinks|ignorecase|precomposeunicode|autocrlf|eol|safecrlf|logallrefupdates|quotepath)|extensions\.(?:objectformat|refstorage)|user\.(?:name|email)|remote\..+\.(?:url|fetch)|branch\..+\.(?:remote|merge))$/u;
32
+ export class HostGit {
33
+ home;
34
+ spy;
35
+ constructor(home, spy) {
36
+ this.home = home;
37
+ this.spy = spy;
38
+ }
39
+ run(cwd, args, options = {}) {
40
+ const env = gitEnv(options.literal ?? true);
41
+ const argv = [...safeGit(this.home), ...args];
42
+ this.spy?.({ args: argv, env, cwd });
43
+ return new Promise((resolve, reject) => {
44
+ const child = spawn("git", argv, { cwd, env, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
45
+ const out = [];
46
+ let err = "";
47
+ child.stdout.on("data", (chunk) => out.push(chunk));
48
+ child.stderr.setEncoding("utf8");
49
+ child.stderr.on("data", (text) => { if (err.length < 8_000)
50
+ err += text; });
51
+ child.stdin.on("error", () => { });
52
+ child.on("error", (error) => reject(error.code === "ENOENT" ? new WsRefusal("git is not installed or not on PATH, so a Workspace cannot be made; install git, or set workspace.enabled to false to run in place") : error));
53
+ child.on("close", (code) => resolve({ code, out: Buffer.concat(out), err }));
54
+ child.stdin.end(options.input);
55
+ });
56
+ }
57
+ fail(project, result, what) {
58
+ const detail = firstLine(result.err);
59
+ return new WsRefusal(`git failed in ${project} (${what}${detail === "" ? `, exit ${result.code}` : `: ${detail}`}); a Workspace needs a working git there, or set workspace.enabled to false to run in place.${/dubious ownership/iu.test(result.err) ? dubious(project) : ""}`);
60
+ }
61
+ /** none (no git at all), or the work tree it is in. A bare repository and a folder inside a git dir are refused. */
62
+ async state(project) {
63
+ const flags = await this.run(project, ["rev-parse", "--is-bare-repository", "--is-inside-git-dir", "--is-inside-work-tree"]);
64
+ if (flags.code === 128 && /not a git repository/iu.test(flags.err))
65
+ return { kind: "none" };
66
+ if (flags.code !== 0)
67
+ throw this.fail(project, flags, "rev-parse");
68
+ const [bare, inGitDir] = flags.out.toString("utf8").trim().split(/\r?\n/u);
69
+ if (bare === "true")
70
+ throw new WsRefusal(`${project} is a bare git repository, which has no files to work on; open a checkout of it instead`);
71
+ if (inGitDir === "true")
72
+ throw new WsRefusal(`${project} is inside a git dir; open the work tree instead`);
73
+ const both = await this.run(project, ["rev-parse", "--show-toplevel", "--absolute-git-dir"]);
74
+ const pair = both.code === 0 ? both.out.toString("utf8").trim().split(/\r?\n/u) : [];
75
+ // A failure, or an unexpected shape, repeats the two single calls so the refusal names the one that failed.
76
+ if (pair.length === 2)
77
+ return { kind: "tree", toplevel: canonicalize(pair[0]), gitDir: canonicalize(pair[1]) };
78
+ const top = await this.run(project, ["rev-parse", "--show-toplevel"]);
79
+ const dir = await this.run(project, ["rev-parse", "--absolute-git-dir"]);
80
+ if (top.code !== 0)
81
+ throw this.fail(project, top, "rev-parse --show-toplevel");
82
+ if (dir.code !== 0)
83
+ throw this.fail(project, dir, "rev-parse --absolute-git-dir");
84
+ return { kind: "tree", toplevel: canonicalize(top.out.toString("utf8").trim()), gitDir: canonicalize(dir.out.toString("utf8").trim()) };
85
+ }
86
+ /** "finish or abort the <operation>" when the live repository is in the middle of one; read from its own git dir. */
87
+ operationInProgress(gitDir) {
88
+ const marks = [["MERGE_HEAD", "merge"], ["CHERRY_PICK_HEAD", "cherry-pick"], ["REVERT_HEAD", "revert"], ["rebase-merge", "rebase"], ["rebase-apply", "rebase"]];
89
+ return marks.find(([name]) => existsSync(join(gitDir, name)))?.[1];
90
+ }
91
+ async lines(project, args, what) {
92
+ const r = await this.run(project, args);
93
+ if (r.code !== 0)
94
+ throw this.fail(project, r, what);
95
+ return r.out.toString("utf8").split("\0").filter((p) => p !== "");
96
+ }
97
+ /** Tracked plus untracked and not ignored paths under `project`, relative to it, deduplicated. */
98
+ async files(project) {
99
+ return [...new Set(await this.lines(project, ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], "ls-files"))];
100
+ }
101
+ /** Ignored directories under `project` (names end with a slash). */
102
+ ignoredDirs(project) {
103
+ return this.lines(project, ["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"], "ls-files --ignored");
104
+ }
105
+ /** The paths of `paths` that the repository's ignore rules match, read literally (a `./` prefix goes in and comes out). Throws on exit 128. */
106
+ async ignored(project, paths) {
107
+ if (paths.length === 0)
108
+ return new Set();
109
+ const r = await this.run(project, ["check-ignore", "--no-index", "-z", "--stdin"], { input: paths.map((p) => `./${p}\0`).join(""), literal: false });
110
+ if (r.code === 1)
111
+ return new Set();
112
+ if (r.code !== 0)
113
+ throw this.fail(project, r, "check-ignore");
114
+ return new Set(r.out.toString("utf8").split("\0").filter((p) => p !== "").map((p) => p.replace(/^\.[\\/]/u, "")));
115
+ }
116
+ async head(project) {
117
+ const r = await this.run(project, ["rev-parse", "HEAD"]);
118
+ return r.code === 0 ? r.out.toString("utf8").trim() : undefined;
119
+ }
120
+ /** The commit ids HEAD and every ref point at. `knownHead` is the caller's own `head()` ("" for none), to skip a second call. */
121
+ async refIds(project, knownHead) {
122
+ const refs = await this.run(project, ["for-each-ref", "--format=%(objectname)"]);
123
+ if (refs.code !== 0)
124
+ throw this.fail(project, refs, "for-each-ref");
125
+ const head = knownHead === undefined ? await this.head(project) : knownHead === "" ? undefined : knownHead;
126
+ return [...new Set([...(head === undefined ? [] : [head]), ...refs.out.toString("utf8").split(/\r?\n/u).filter((id) => id !== "")])];
127
+ }
128
+ /** The ids of the list the repository does not have. */
129
+ async missingObjects(project, ids) {
130
+ if (ids.length === 0)
131
+ return [];
132
+ const r = await this.run(project, ["cat-file", "--batch-check"], { input: `${ids.join("\n")}\n` });
133
+ if (r.code !== 0)
134
+ throw this.fail(project, r, "cat-file");
135
+ return r.out.toString("utf8").split(/\r?\n/u).filter((line) => /\bmissing$/u.test(line)).map((line) => line.split(" ")[0]);
136
+ }
137
+ /** The live repository's own config reduced to the allowed keys, as a fresh INI text. Every remote gets a push URL that fails. */
138
+ async copyConfig(gitDir) {
139
+ const r = await this.run(gitDir, ["config", "--file", join(gitDir, "config"), "--no-includes", "--list", "-z"]);
140
+ if (r.code !== 0)
141
+ throw this.fail(gitDir, r, "config --list");
142
+ const sections = new Map();
143
+ const add = (section, line) => { sections.set(section, [...(sections.get(section) ?? []), line]); };
144
+ const quote = (value) => `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n")}"`;
145
+ add("core", "bare = false");
146
+ for (const entry of r.out.toString("utf8").split("\0").filter((e) => e !== "")) {
147
+ const nl = entry.indexOf("\n");
148
+ const key = nl < 0 ? entry : entry.slice(0, nl);
149
+ if (key === "core.bare" || !CONFIG_KEYS.test(key))
150
+ continue;
151
+ const value = nl < 0 ? "true" : entry.slice(nl + 1);
152
+ const dots = key.split(".");
153
+ const variable = dots.pop();
154
+ const name = dots.shift();
155
+ add(dots.length === 0 ? name : `${name} "${dots.join(".").replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`, `${variable} = ${quote(value)}`);
156
+ }
157
+ for (const section of [...sections.keys()])
158
+ if (section.startsWith("remote "))
159
+ add(section, `pushurl = ${quote("piroboros-workspace-no-push")}`);
160
+ return [...sections].map(([section, lines]) => `[${section}]\n${lines.map((l) => `\t${l}`).join("\n")}\n`).join("");
161
+ }
162
+ }
package/dist/ws/lww.js ADDED
@@ -0,0 +1,48 @@
1
+ // The .lww rule file: gitignore-style rules that name the paths where the side modified later wins a merge.
2
+ // Ported from the LayerFS decision model (model.js lwwRules and lwwMatch, MIT; see NOTICE and merge.ts).
3
+ export const INCLUDE_MAX = 16;
4
+ /**
5
+ * Rules from the text of a .lww file, in order. `# comment` and blank lines are skipped; `!` negates; a `/` inside a
6
+ * pattern anchors it to the root; `*` and `?` stay inside one name, `**` crosses folders. `%include <file>` splices the
7
+ * rules of another file, read through `readInclude` (undefined when absent); a file already read is skipped, and at
8
+ * most INCLUDE_MAX files are included, the rest ignored. A path nothing matches stays a conflict, so a dropped include is safe.
9
+ */
10
+ export function lwwRules(text, readInclude) {
11
+ const seen = new Set();
12
+ const parse = (body) => {
13
+ const rules = [];
14
+ for (let line of body.split("\n")) {
15
+ line = line.trim();
16
+ if (!line || line.startsWith("#"))
17
+ continue;
18
+ const inc = /^%include\s+(\S+)$/u.exec(line);
19
+ if (inc) {
20
+ const file = inc[1].replace(/^\/+/u, "");
21
+ if (seen.has(file) || seen.size >= INCLUDE_MAX)
22
+ continue;
23
+ seen.add(file);
24
+ const included = readInclude(file);
25
+ if (included !== undefined)
26
+ rules.push(...parse(included));
27
+ continue;
28
+ }
29
+ const neg = line.startsWith("!");
30
+ let pat = (neg ? line.slice(1) : line).replace(/\/$/u, "");
31
+ const anchored = pat.includes("/");
32
+ pat = pat.replace(/^\//u, "");
33
+ const rx = pat.split("**").map((s) => s.replace(/[.+^${}()|[\]\\]/gu, "\\$&").replace(/\*/gu, "[^/]*").replace(/\?/gu, "[^/]")).join(".*");
34
+ rules.push({ pattern: line, neg, re: new RegExp(`${anchored ? "^" : "(^|/)"}${rx}($|/)`) });
35
+ }
36
+ return rules;
37
+ };
38
+ return parse(text);
39
+ }
40
+ /** The rule that decides `path`: the last matching rule, or null when it is a `!` rule or none matches. */
41
+ export function lwwMatch(rules, path) {
42
+ let hit = null;
43
+ const p = path.replace(/^\//u, "");
44
+ for (const r of rules)
45
+ if (r.re.test(p))
46
+ hit = r.neg ? null : r;
47
+ return hit;
48
+ }
@@ -0,0 +1,129 @@
1
+ // The merge decision model of a Workspace: per path, what the merge does with Vesperia's version (ours), the live version
2
+ // (theirs) and the version both started from (base). Ported from the LayerFS decision model (model.js merge3Lines and
3
+ // merge3Trees, MIT; credited in NOTICE), not its filesystem. Pure functions over bytes; nothing here touches disk.
4
+ import { diffChunks } from "../diff.js";
5
+ import { lwwMatch } from "./lww.js";
6
+ export const TEXT_MAX = 1024 * 1024;
7
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
8
+ /** Text for line merging: at most TEXT_MAX, no NUL in the first 8 KiB, valid UTF-8. A BOM stays in the text. */
9
+ export function isText(bytes) {
10
+ if (bytes.length > TEXT_MAX || bytes.subarray(0, 8192).includes(0))
11
+ return false;
12
+ try {
13
+ decoder.decode(bytes);
14
+ return true;
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ }
20
+ /** Lines that keep their terminators (`\r\n`, `\n`, or none on the last line); nothing is normalized. */
21
+ export function splitLines(text) {
22
+ return text.match(/[^\n]*\n|[^\n]+$/gu) ?? [];
23
+ }
24
+ // For each line of `a`, the index of the matching line of `b` (or -1); null when the diff is refused. The diff runs from
25
+ // `b` to `a`, so its tie-break between equal-length alignments is the one model.js's matchLines has.
26
+ function matchLines(a, b) {
27
+ const ops = diffChunks(b, a);
28
+ if (!ops)
29
+ return null;
30
+ const m = new Array(a.length).fill(-1);
31
+ let i = 0;
32
+ let j = 0;
33
+ for (const op of ops) {
34
+ if (op === " ") {
35
+ m[i] = j;
36
+ i += 1;
37
+ j += 1;
38
+ }
39
+ else if (op === "+")
40
+ i += 1;
41
+ else
42
+ j += 1;
43
+ }
44
+ return m;
45
+ }
46
+ /**
47
+ * Line merge: a chunk between lines unchanged on both sides takes the side that changed it, a chunk both sides changed
48
+ * identically is taken once, and both changing it differently is a conflict block with marker lines. Marker lines end
49
+ * with the dominant terminator of `ours`. Null when a diff is refused as too large (the caller makes a `content` conflict).
50
+ */
51
+ export function merge3Lines(base, ours, theirs, labels) {
52
+ const b = splitLines(base);
53
+ const o = splitLines(ours);
54
+ const t = splitLines(theirs);
55
+ const mo = matchLines(b, o);
56
+ const mt = matchLines(b, t);
57
+ if (!mo || !mt)
58
+ return null;
59
+ const crlf = o.filter((l) => l.endsWith("\r\n")).length;
60
+ const eol = crlf > o.filter((l) => l.endsWith("\n")).length - crlf ? "\r\n" : "\n";
61
+ const out = [];
62
+ const hunks = [];
63
+ let bi = 0;
64
+ let oi = 0;
65
+ let ti = 0;
66
+ const eq = (x, y) => x.length === y.length && x.every((v, k) => v === y[k]);
67
+ // A block's last line without a terminator gets one, so the next marker starts a line.
68
+ const closed = (ls) => (ls.length > 0 && !ls[ls.length - 1].endsWith("\n") ? [...ls.slice(0, -1), ls[ls.length - 1] + eol] : ls);
69
+ const chunk = (be, oe, te) => {
70
+ const cb = b.slice(bi, be);
71
+ const co = o.slice(oi, oe);
72
+ const ct = t.slice(ti, te);
73
+ if (eq(co, cb))
74
+ out.push(...ct);
75
+ else if (eq(ct, cb) || eq(co, ct))
76
+ out.push(...co);
77
+ else {
78
+ hunks.push({ line: out.length + 1, ours: co, theirs: ct });
79
+ out.push(`<<<<<<< ${labels[0]}${eol}`, ...closed(co), `=======${eol}`, ...closed(ct), `>>>>>>> ${labels[1]}${ct.length > 0 && !ct[ct.length - 1].endsWith("\n") ? "" : eol}`);
80
+ }
81
+ };
82
+ for (let k = 0; k < b.length; k += 1) {
83
+ if (mo[k] < 0 || mt[k] < 0 || mo[k] < oi || mt[k] < ti)
84
+ continue;
85
+ chunk(k, mo[k], mt[k]);
86
+ out.push(b[k]);
87
+ bi = k + 1;
88
+ oi = mo[k] + 1;
89
+ ti = mt[k] + 1;
90
+ }
91
+ chunk(b.length, o.length, t.length);
92
+ return { text: out.join(""), hunks };
93
+ }
94
+ /** Whether `text` still holds a marker line labelled with this Workspace's id (a half-removed block counts); another id is ordinary text. */
95
+ export function hasBlock(text, ws) {
96
+ return new RegExp(`^(?:<<<<<<< workspace ${ws}|>>>>>>> live ${ws})\\r?$`, "mu").test(text);
97
+ }
98
+ const same = (x, y) => x === y || (x instanceof Uint8Array && y instanceof Uint8Array && Buffer.compare(x, y) === 0);
99
+ /**
100
+ * The decision for one path that ours changed relative to base. In order: equal sides need nothing; live unchanged takes
101
+ * ours; a file against a directory is `type`; an `.lww` rule takes the side modified later (ours on a tie); a deletion
102
+ * against a modification is `modify/delete` or `delete/modify`; text within bounds is line merged (`add/add` when there
103
+ * is no base); anything else is `binary`.
104
+ */
105
+ export function decide(path, base, ours, theirs, opts) {
106
+ if (same(ours, theirs))
107
+ return { op: "skip" };
108
+ if (same(theirs, base))
109
+ return { op: "ours" };
110
+ const file = (s) => s instanceof Uint8Array;
111
+ if ((file(ours) && theirs === "dir") || (ours === "dir" && file(theirs)))
112
+ return { op: "conflict", kind: "type" };
113
+ const rule = opts.lww && lwwMatch(opts.lww.rules, path);
114
+ if (rule && opts.lww) {
115
+ return opts.lww.ours >= opts.lww.theirs ? { op: "ours", lww: { rule: rule.pattern, kept: "ours" } } : { op: "skip", lww: { rule: rule.pattern, kept: "theirs" } };
116
+ }
117
+ if (ours === undefined)
118
+ return { op: "conflict", kind: "delete/modify" };
119
+ if (theirs === undefined)
120
+ return { op: "conflict", kind: "modify/delete" };
121
+ if (file(ours) && file(theirs) && isText(ours) && isText(theirs) && (base === undefined || (file(base) && isText(base)))) {
122
+ const m = merge3Lines(base === undefined ? "" : decoder.decode(base), decoder.decode(ours), decoder.decode(theirs), opts.labels);
123
+ const kind = base === undefined ? "add/add" : "content";
124
+ if (!m)
125
+ return { op: "conflict", kind: "content" };
126
+ return m.hunks.length === 0 ? { op: "merged", text: m.text } : { op: "conflict", kind, text: m.text, hunks: m.hunks };
127
+ }
128
+ return { op: "conflict", kind: "binary" };
129
+ }