diff --git a/agents.md b/agents.md index 76306f341..99937d6b0 100644 --- a/agents.md +++ b/agents.md @@ -42,7 +42,7 @@ A push that fails with tangled's `too many concurrent operations from your addre - **`src/albedo/daemon/`** — session actors and durable state: submission/run/turn plumbing (`session_*.gleam`), the append-only transcript and conversation store (SQLite via sqlight), the event bus, projections, the family (agents, mail, bus), folders, quota, usage, the reaper, persisted settings, the image store, and `server.gleam`, the HTTP entry point. - **`src/albedo/daemon/migrations/`** — existing SQLite upgrades, with ordered startup data steps in `daemon/migrations.gleam`; schema additions remain called from owning initialisers (see `robot-docs/migrations.md`). - **`src/albedo/harness/`** — the model-facing half: `loop.gleam` (the tool loop), `tool.gleam`, `extension.gleam` and `extensions.gleam` (plugin interfaces and composition), `compaction.gleam`, `runtime.gleam` (boots the built-ins), plus credentials, oauth, rotation, session settings mutations, shared settings persistence, extension settings, and the usage feed. -- **`src/albedo/harness/extensions/`** — one directory per extension. Enabled by default: `python`, `run`, `work`, `mail`, `agents`, `schedule`, `paperclips`, `files`, `memory`, `instructions`, `commands`, `skills`, `models`, `openai`, `codex`, `antigravity`, `alibaba`, `claude`, `rolling`, `snapcompact-memory`, `lcm-memory`, `notes`, `remote`, `browser`. Installed but off until enabled: `mcp`, `view`, `proxy`, `webhooks`, `warm`, `snapcompact`, `lcm`. The provider extensions are ordered before `models` on purpose (their own model lists win), and the memory/compaction pairs are ordered so archives cover past folds. +- **`src/albedo/harness/extensions/`** — one directory per extension. Enabled by default: `python`, `run`, `work`, `mail`, `agents`, `schedule`, `paperclips`, `files`, `memory`, `links`, `instructions`, `commands`, `skills`, `models`, `openai`, `codex`, `antigravity`, `alibaba`, `claude`, `rolling`, `snapcompact-memory`, `lcm-memory`, `notes`, `remote`, `browser`. Installed but off until enabled: `mcp`, `view`, `proxy`, `webhooks`, `warm`, `snapcompact`, `lcm`. The provider extensions are ordered before `models` on purpose (their own model lists win), and the memory/compaction pairs are ordered so archives cover past folds. - **`src/albedo/openai_api/`** — the provider transport every extension shares: request/turn types, SSE framing, stream reducers, replay after restarts, chat/responses encodings. A provider with a foreign wire format encodes an `openai_api.Exchange` and supplies only its own reducer (antigravity does this); HTTP, retries, limits, and callbacks stay shared. The extension record is the core abstraction everything composes through: diff --git a/priv/python/albedo_api.py b/priv/python/albedo_api.py index 9be7ea2f2..e69e4167c 100644 --- a/priv/python/albedo_api.py +++ b/priv/python/albedo_api.py @@ -136,6 +136,9 @@ class PythonApi: # Local shell admission, shared across the daemon's kernels. Completion # releases it through the existing verified `job` cleanup frame. job_slot: Callable[[str, Callable[[], None]], Awaitable[None]] | None = None + # A host call that blocks until its answer, for synchronous APIs over + # routes that answer at once. Absent when the host pre-dates it. + host_now: Callable[[str, dict[str, object]], object] | None = None class PythonPlugin(Protocol): diff --git a/priv/python/albedo_gather.py b/priv/python/albedo_gather.py index ecc4c561f..7973a84af 100644 --- a/priv/python/albedo_gather.py +++ b/priv/python/albedo_gather.py @@ -10,7 +10,8 @@ commands the daemon planned, file sizes, and project files. Everything comes back in one ssh round trip per question. Request: `{route, dir, plans, separators, deadline, counted}`, `dir` absolute -and normalised. `route` is list, repo, preview or project. +and normalised. `route` is list, repo, preview or project, or exists, which +answers `directory` alone. Snapshot: `{directory, entries: {dir: [[name, dir, modified]]}, exists: [path], outputs: {key: stdout}, sizes: {path: bytes}, files: {relative: @@ -148,7 +149,7 @@ def project(directory: str) -> dict[str, str]: def gather(request: dict) -> dict[str, object]: route, directory = request["route"], request["dir"] snapshot: dict[str, object] = {"directory": os.path.isdir(directory)} - if not snapshot["directory"]: + if not snapshot["directory"] or route == "exists": return snapshot if route == "project": snapshot["files"] = project(directory) diff --git a/priv/python/albedo_kernel.py b/priv/python/albedo_kernel.py index f46da5769..9be839fe8 100644 --- a/priv/python/albedo_kernel.py +++ b/priv/python/albedo_kernel.py @@ -59,6 +59,10 @@ asyncio.set_event_loop(LOOP) albedo_proc.reap_stopped_safely(LOOP) QUEUE: asyncio.Queue[albedo_api.Execute | albedo_api.State] = asyncio.Queue() PENDING: dict[str, asyncio.Future[albedo_api.HostReply]] = {} +# Host calls a synchronous API waits for; the reader thread hands their reply +# over directly, since the loop it would go through is the one waiting. +WAITING: dict[str, tuple[threading.Event, list[albedo_api.HostReply]]] = {} +HOST_NOW_TIMEOUT = 30.0 JOB_SLOTS: dict[str, tuple[asyncio.Future[None], Callable[[], None]]] = {} HOST_SLOTS = asyncio.Semaphore(32) OWNER_CALLS = asyncio.Semaphore(32) # concurrent tool calls from the connection owner @@ -179,6 +183,10 @@ def receive(frame: object) -> None: task = OWNER_TASKS.get(message["id"]) if task is not None: LOOP.call_soon_threadsafe(task.cancel) + elif message["type"] == "reply" and message["id"] in WAITING: + arrived, answer = WAITING[message["id"]] + answer.append(message["value"]) + arrived.set() else: _ = LOOP.call_soon_threadsafe(deliver, message) @@ -307,6 +315,28 @@ async def _host(method: str, args: dict[str, object]) -> object: raise WorkError(answer["code"], answer["message"]) +def host_now(method: str, args: dict[str, object]) -> object: + """A host call for a synchronous API: blocks the calling thread, the + loop's included, until the reply. Only for calls the host answers at + once; an interrupt still ends the wait.""" + key = uuid.uuid4().hex + arrived = threading.Event() + answers: list[albedo_api.HostReply] = [] + WAITING[key] = (arrived, answers) + send({"type": "call", "id": key, "method": method, "args": args}) + try: + if not arrived.wait(HOST_NOW_TIMEOUT): + raise WorkError( + "timeout", f"{method} had no answer within {HOST_NOW_TIMEOUT:.0f}s" + ) + finally: + _ = WAITING.pop(key, None) + answer = answers[0] + if answer["ok"]: + return answer["value"] + raise WorkError(answer["code"], answer["message"]) + + class Capture: def __init__( self, id: str, kind: str = "cell", max_edge: int | None = None @@ -1594,6 +1624,7 @@ def main(): version=2, loop=LOOP, host=host, + host_now=host_now, HostError=WorkError, forget_output=forget_output, capture=background_capture, diff --git a/priv/python/albedo_plugins/memory.py b/priv/python/albedo_plugins/memory.py index 591e8ff52..92b28885d 100644 --- a/priv/python/albedo_plugins/memory.py +++ b/priv/python/albedo_plugins/memory.py @@ -1,33 +1,30 @@ -"""Project-scoped Markdown memory with literal and full-text recall.""" +"""Project-scoped Markdown memory with literal and full-text recall. + +The files live on the daemon's machine, wherever this kernel runs, and every +call goes through the memory host route. Reads of a linked workspace's memory +come back with it; writes always land in this workspace's own. +""" from __future__ import annotations -from contextlib import contextmanager +from collections.abc import Callable from datetime import date -import fcntl -import os -from pathlib import Path import re import sqlite3 -import tempfile -from typing import Iterator +from typing import cast from albedo_api import PythonApi, Text from albedo_plugins.files import Rows class Memory: - def __init__(self, root: Path) -> None: - self.root = root - - @property - def path(self) -> Path: - return self.root / "memory.md" + def __init__(self, host: Callable[[str, dict[str, object]], object]) -> None: + self._host = host def read(self, max_chars: int = 16000) -> Text: if not 0 < max_chars <= 200_000: raise ValueError("0 < max_chars <= 200000") - content = self.path.read_text() if self.path.exists() else "" + content = cast(str, self._host("memory.read", {})) suffix = ( "\n[truncated; raise max_chars to read more]" if len(content) > max_chars @@ -35,90 +32,64 @@ class Memory: ) return Text(content[:max_chars] + suffix) - @contextmanager - def _locked(self) -> Iterator[None]: - self.root.mkdir(parents=True, exist_ok=True) - with (self.root / ".lock").open("a+b") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) - yield - def save(self, text: str) -> Text: - """Atomically replace curated memory, serializing with append.""" - if len(text.encode("utf-8")) > 1_048_576: - raise ValueError("memory.md cannot exceed 1 MiB") - with self._locked(): - fd, name = tempfile.mkstemp(dir=self.root, prefix=".memory-") - try: - with os.fdopen(fd, "w", encoding="utf-8") as file: - file.write(text) - os.replace(name, self.path) - finally: - if os.path.exists(name): - os.unlink(name) - return Text(str(self.path)) + """Atomically replace curated memory.""" + return Text(cast(str, self._host("memory.save", {"text": text}))) def append(self, text: str) -> Text: - with self._locked(): - size = self.path.stat().st_size if self.path.exists() else 0 - extra = len(text.rstrip("\n").encode("utf-8")) + 1 + (size > 0) - if size + extra > 1_048_576: - raise ValueError("memory.md cannot exceed 1 MiB") - self._append(self.path, text) - return Text(str(self.path)) + return Text(cast(str, self._host("memory.append", {"text": text}))) def journal(self, text: str) -> Text: - target = self.root / "journal" / f"{date.today().isoformat()}.md" - with self._locked(): - target.parent.mkdir(exist_ok=True) - self._append(target, text) - return Text(str(target)) - - @staticmethod - def _append(path: Path, text: str) -> None: - with path.open("a", encoding="utf-8") as file: - if path.stat().st_size: - file.write("\n") - file.write(text.rstrip("\n") + "\n") + day = date.today().isoformat() + return Text( + cast(str, self._host("memory.journal", {"date": day, "text": text})) + ) - def _documents(self) -> list[Path]: - paths = [self.path, *sorted((self.root / "journal").glob("*.md"))] - return [path for path in paths if path.is_file()] + def _documents(self) -> tuple[list[tuple[str, str]], bool]: + """(name, text) for every memory and journal file this workspace + reads; a linked workspace's names lead with it.""" + answer = cast(dict, self._host("memory.documents", {})) + named = [ + ( + document["path"] + if document["workspace"] == answer["own"] + else f"[{document['workspace']}] {document['path']}", + document["text"], + ) + for document in answer["documents"] + ] + return named, bool(answer["truncated"]) def grep(self, term: str, limit: int = 20) -> Rows: if not term or not 1 <= limit <= 100: raise ValueError("term must be nonempty and 1 <= limit <= 100") + documents, cut = self._documents() matches = [] - for path in self._documents(): - for number, line in enumerate(path.read_text().splitlines(), 1): + for name, content in documents: + for number, line in enumerate(content.splitlines(), 1): if term.casefold() in line.casefold(): - matches.append( - f"{path.relative_to(self.root)}:{number}: {line[:500]}" - ) + matches.append(f"{name}:{number}: {line[:500]}") if len(matches) == limit: return Rows(matches, truncated=True) - return Rows(matches) + return Rows(matches, truncated=cut) def search(self, query: str, limit: int = 20) -> Rows: """FTS5 ranks paragraphs, including multiline entries, without a stale index.""" if not query.strip() or not 1 <= limit <= 100: raise ValueError("query must be nonempty and 1 <= limit <= 100") + documents, cut = self._documents() with sqlite3.connect(":memory:") as db: db.execute( "CREATE VIRTUAL TABLE notes USING fts5(path UNINDEXED, line UNINDEXED, body)" ) - for path in self._documents(): - content = path.read_text() + for name, content in documents: for match in re.finditer( r"(?s)\S.*?(?=\n[ \t]*\n|\s*\Z)", content, re.S ): line = content.count("\n", 0, match.start()) + 1 db.execute( "INSERT INTO notes VALUES (?, ?, ?)", - ( - str(path.relative_to(self.root)), - line, - match.group()[:100_000], - ), + (name, line, match.group()[:100_000]), ) try: rows = db.execute( @@ -129,15 +100,15 @@ class Memory: except sqlite3.OperationalError as exc: raise ValueError(f"invalid full-text query: {exc}") from exc return Rows( - f"{path}:{line}: {snippet.replace(chr(10), ' ')[:500]}" - for path, line, snippet in rows + ( + f"{path}:{line}: {snippet.replace(chr(10), ' ')[:500]}" + for path, line, snippet in rows + ), + truncated=cut, ) -async def setup(api: PythonApi) -> dict[str, object]: - workspace = await api.host("session.cwd", {}) - if not isinstance(workspace, str): - raise ValueError("session.cwd did not return a workspace path") - home = Path(os.environ.get("ALBEDO_HOME") or Path.home() / ".albedo") - slug = re.sub(r"[^A-Za-z0-9]", "-", workspace) - return {"memory": Memory(home / "memories" / slug)} +def setup(api: PythonApi) -> dict[str, object]: + if api.host_now is None: + raise RuntimeError("this host cannot answer synchronous memory calls") + return {"memory": Memory(api.host_now)} diff --git a/priv/python/albedo_plugins/work.py b/priv/python/albedo_plugins/work.py index 76a6836b4..abb85b2a2 100644 --- a/priv/python/albedo_plugins/work.py +++ b/priv/python/albedo_plugins/work.py @@ -16,6 +16,7 @@ class WorkItem(Record): session: str | None run: str | None revision: int + workspace: str # where it was filed: this workspace or a linked one host: Host diff --git a/robot-docs/commands.md b/robot-docs/commands.md index 33396a2b5..5b2aa8835 100644 --- a/robot-docs/commands.md +++ b/robot-docs/commands.md @@ -45,6 +45,8 @@ argument parsing is shared: leading arguments take one whitespace token each, th the python extension contributes `/kernel [upgrade]` — whether the session's kernel runs older code than the daemon (bundle, module set, or protocol) and what keeps it, or, with `upgrade` (user only, between turns), swap it now past its live jobs (`KernelReport` / `KernelUpgrade` state ops). See [kernel](kernel.md#version-skew). +the links extension contributes `/link [add|remove] [workspace]` — the workspaces linked with this one, as a page (`here`, `gone` for a member whose folder is missing, checked on its host for a remote one, or why the host can't say), or, user only, link one or unlink one; every open session in the workspaces it touches gets a note either way. See [workspaces](workspaces.md#linked-workspaces). + skills contributes one command per cataloged skill; `/tree`, `/fork`, `/login`, and the other picker-style entries stay presentation-only in the CLI. ## CLI page lifecycle diff --git a/robot-docs/extensions.md b/robot-docs/extensions.md index 3e0d42a05..d476a1df0 100644 --- a/robot-docs/extensions.md +++ b/robot-docs/extensions.md @@ -3,7 +3,7 @@ Persisted preferences are owned by the daemon and changed through the [settings API](settings.md). The CLI refreshes them on use and never writes settings files. -an extension is a named bundle of plugins. it can contribute any number of context, tool, command, managed, models, provider, login, service, migration, compaction, notes, clean, or fold plugins. `python`, `run`, `work`, `mail`, `agents`, `schedule`, `paperclips`, `files`, `memory`, `instructions`, `commands`, `skills`, `models`, `openai`, `codex`, `antigravity`, `alibaba`, `claude`, `rolling`, `snapcompact-memory`, `lcm-memory`, `notes`, `remote`, and `browser` are enabled by default; `mcp`, `view`, [`proxy`](proxy.md), `webhooks`, [`warm`](cache-warming.md), and the `snapcompact` and `lcm` compaction strategies are installed and disabled until enabled. plugin contributions compose inside them. +an extension is a named bundle of plugins. it can contribute any number of context, tool, command, managed, models, provider, login, service, migration, compaction, notes, clean, or fold plugins. `python`, `run`, `work`, `mail`, `agents`, `schedule`, `paperclips`, `files`, `memory`, `links`, `instructions`, `commands`, `skills`, `models`, `openai`, `codex`, `antigravity`, `alibaba`, `claude`, `rolling`, `snapcompact-memory`, `lcm-memory`, `notes`, `remote`, and `browser` are enabled by default; `mcp`, `view`, [`proxy`](proxy.md), `webhooks`, [`warm`](cache-warming.md), and the `snapcompact` and `lcm` compaction strategies are installed and disabled until enabled. plugin contributions compose inside them. ## select extensions diff --git a/robot-docs/migrations.md b/robot-docs/migrations.md index 0d02eb7c5..fa75e02a5 100644 --- a/robot-docs/migrations.md +++ b/robot-docs/migrations.md @@ -21,7 +21,7 @@ deleted if later deletion or vacuum fails. for each installed extension, `extension.install` first calls its table initialiser, then applies its contributed `SchemaMigration` callbacks on the store-owned SQLite connection, in plugin order. work contributes `cwd.apply`; -paperclips contributes `title.apply`, `scope.apply`, and `reply.apply`; python contributes `kernel_links.apply`, the detached kernel's link tables (see [kernel](kernel.md)), which `link.create` also ensures for embedded runtimes that boot kernels without the extension. their ledgers create tables but do not run +paperclips contributes `title.apply`, `scope.apply`, and `reply.apply`; the links extension's initialiser creates `workspace_links` (see [workspaces](workspaces.md#linked-workspaces)), which `links.link` also ensures; python contributes `kernel_links.apply`, the detached kernel's link tables (see [kernel](kernel.md)), which `link.create` also ensures for embedded runtimes that boot kernels without the extension. their ledgers create tables but do not run upgrades themselves. all installed owners upgrade, even when disabled for sessions; session selection and live reload never rerun migrations. diff --git a/robot-docs/workspaces.md b/robot-docs/workspaces.md index 1a35dd1d5..0cd9fa8ec 100644 --- a/robot-docs/workspaces.md +++ b/robot-docs/workspaces.md @@ -39,7 +39,7 @@ cached per host for the daemon's life. without ssh the user stays. a remote session's python kernel and `run` jobs run on its host (kernel.md, "remote kernels"). what is only a key works as it is: the work -ledger and paperclips scope, recent folders, session search by cwd, family +ledger and paperclips scope, workspace links, recent folders, session search by cwd, family moves. what the daemon itself reads from a workspace goes through the location, and never looks for a remote path on its own disk: @@ -56,7 +56,64 @@ location, and never looks for a remote path on its own disk: only the home directories count, and the instructions warn and the skills catalog diagnoses `project … skipped: can't reach chernobog: …`. - memory is a daemon-side file keyed by the workspace string, so a remote - workspace gets its own. + workspace gets its own. the kernel's `memory` object reaches it through the + `memory` host route wherever the kernel runs (`memory.read`, `.save`, + `.append`, `.journal`, `.documents`; synchronous over the kernel's + `host_now`), so a remote session's notes land in the daemon's + `$ALBEDO_HOME/memories`, never the host's. + +## linked workspaces + +a workspace can be linked with others that hold the same project, such as one +repository checked out here and on chernobog (`src/albedo/harness/links.gleam`, +the `links` extension). links are peers: every member keeps writing its own +memory and work items, and reads cover the whole group. + +- storage: `workspace_links(workspace, grp)` in the daemon's sqlite. linking + two workspaces merges their groups; unlinking one takes only that row out, + and a group left with one member is dropped. nothing else changes, so + unlinking (or linking again) loses and repeats nothing. +- memory: the snapshot a session opens with shows its own memory, then each + linked member's under `## linked workspace `, within the same + 8000-character budget. `memory.read()` is this workspace's file only; + `grep` and `search` cover the group, a linked file named + `[] memory.md`. `save`, `append` and `journal` write here. +- work ledger: `list`, `get`, `update` and `delete` reach every member's + items, an update or delete stays in the item's own workspace, and `create` + files under this one. each item carries `workspace`; the `/work` page says + where an item from another member was filed. +- vents are one ledger for every workspace already, so links change nothing + there. +- the model is told it is linked (the `links` context, naming each member, + and marking one whose folder is gone). +- linking or unlinking queues a note in every open session of every + workspace it touches, worded for that side ("linked this workspace with + X" / "unlinked X" / "unlinked this workspace from Y, Z"). a link note + carries the newly linked members' memory as a new session's snapshot holds + it (`albedo_memory:linked`), so a session that opened before the link + reads the same text without rebuilding its prompt and losing its prompt + cache; its snapshot catches up at the next rebuild. open means the session + has a live actor (and so a cached composition); any other session composes + its snapshot afresh when it opens. live reads (`grep`, `search`, the work + ledger) follow the group on every call anyway. +- a member's folder is checked where it is: a local one on the daemon's + disk, a remote one with one `exists` gather on its host over the shared + ControlMaster (`folders.exists`). a host that does not answer is never + read as a gone folder. every member is checked at once, so slow hosts + wait side by side. the `/link` page waits up to 5 s for a host and + then says why (`connecting`, `sign in`, `unreachable`, with ssh's words); + the session-start context takes only a recent probe, starting one in the + background, so opening a session never waits on a host. +- `/link` (user only for changes) lists the members: this one `here`, a + member whose folder no longer exists `gone`, a remote one whose host can't + say as above. `add ` takes what a session can be created in (an + existing local directory, or `host:/abs` / `host:~/x`) and refuses this + workspace and one already linked; `remove ` takes a listed one, + this one included (leaving the group). a gone member stays, read as before, + until it is removed. + +a worktree or jj workspace of the same repository is not linked by itself +yet; that and suggesting links from shared history are later work. the tui shows a remote workspace as `label:path`, the path folded under that host's own home once a listing or probe reported it: the chat header diff --git a/src/albedo/daemon/folders.gleam b/src/albedo/daemon/folders.gleam index f490db979..ec1125db9 100644 --- a/src/albedo/daemon/folders.gleam +++ b/src/albedo/daemon/folders.gleam @@ -245,6 +245,43 @@ fn remote(path: String, route: Route) -> Result(#(Machine, String), Failure) { /// The vcs commands' own deadline on the host, plus the ssh round trip. const gather_ms = 20_000 +/// Whether a workspace's folder exists. A remote one is asked on its host +/// over the shared ControlMaster; a host not ready within `wait_ms` answers +/// why instead (0 takes only a recent probe, starting one in the background), +/// so an unreachable folder never reads as a missing one. +pub fn exists( + workspace: location.Location, + wait_ms: Int, +) -> Result(Bool, ssh.Failure) { + case workspace, location.ssh_target(workspace) { + location.Local(path), _ -> Ok(is_directory(path)) + location.Remote(path:, ..), Ok(target) -> { + use host <- result.try(case wait_ms { + 0 -> ssh.known(target) + _ -> ssh.ready(target, wait_ms) + }) + let request = + json.object([ + #("route", json.string("exists")), + #("dir", json.string(path)), + ]) + ssh.gather(host, request, exists_ms) + |> result.try(fn(answer) { + json.parse( + answer, + decode.field("directory", decode.bool, decode.success), + ) + |> result.replace_error("the gather on " <> target <> " answered badly") + }) + |> result.map_error(ssh.Unreachable) + } + location.Remote(..), Error(Nil) -> Error(ssh.Unreachable("not a host")) + } +} + +/// One stat on a host that already answered its probe. +pub const exists_ms = 5000 + fn route_name(route: Route) -> String { case route { Listing -> "list" diff --git a/src/albedo/harness/extensions.gleam b/src/albedo/harness/extensions.gleam index 7423e24ff..5bf3dfb33 100644 --- a/src/albedo/harness/extensions.gleam +++ b/src/albedo/harness/extensions.gleam @@ -10,6 +10,7 @@ import albedo/harness/extensions/files/extension as files import albedo/harness/extensions/instructions/extension as instructions import albedo/harness/extensions/lcm/extension as lcm import albedo/harness/extensions/lcm/memory as lcm_memory +import albedo/harness/extensions/links/extension as links import albedo/harness/extensions/mail/extension as mail import albedo/harness/extensions/mcp/extension as mcp import albedo/harness/extensions/memory/extension as memory @@ -46,6 +47,7 @@ pub fn defaults() -> Config { paperclips.extension(), files.extension(), memory.extension(), + links.extension(), instructions.extension(), commands.extension(), skills.extension(), @@ -77,8 +79,8 @@ pub fn defaults() -> Config { ], [ "python", "run", "work", "mail", "agents", "schedule", "files", "memory", - "instructions", "commands", "skills", "paperclips", "models", "openai", - "codex", "antigravity", "alibaba", "claude", "rolling", + "links", "instructions", "commands", "skills", "paperclips", "models", + "openai", "codex", "antigravity", "alibaba", "claude", "rolling", "snapcompact-memory", "lcm-memory", "notes", "remote", "browser", ], ) diff --git a/src/albedo/harness/extensions/links/extension.gleam b/src/albedo/harness/extensions/links/extension.gleam new file mode 100644 index 000000000..05b45beda --- /dev/null +++ b/src/albedo/harness/extensions/links/extension.gleam @@ -0,0 +1,339 @@ +//// `/link`: tie this workspace to others that hold the same project, such as +//// one repository checked out on two hosts. Linked workspaces read each +//// other's memory and work items; each keeps writing its own, so a member +//// whose folder is gone loses nothing and unlinking undoes nothing. + +import albedo/daemon/conversation +import albedo/daemon/folders +import albedo/daemon/store +import albedo/harness/command.{ + type Command, type StateOp, Argument, Command, Data, Note, UserCall, +} +import albedo/harness/extension +import albedo/harness/links +import albedo/harness/location +import albedo/harness/page +import albedo/harness/ssh +import gleam/erlang/process +import gleam/int +import gleam/json +import gleam/list +import gleam/option.{None} +import gleam/result +import gleam/string + +pub fn extension() -> extension.Extension { + extension.Extension( + "links", + "Workspaces linked into one project share memory and work items.", + [], + [ + extension.ManagedPlugin(fn(storage, _, workspace) { + Ok( + extension.Managed( + ..extension.empty(), + context: context(links.group(storage, workspace)), + commands: [command(storage, workspace)], + ), + ) + }), + ], + fn(storage) { store.query(storage, links.apply) }, + ) +} + +/// What the model is told about the group it works in; nothing alone. A +/// session opening must not wait on a host, so only a recent probe tells +/// whether a remote member's folder is gone. +fn context(group: List(String)) -> String { + case group { + [_] | [] -> "" + [_, ..linked] -> + "This workspace is linked with " + <> string.join(list.map2(linked, presences(linked, 0), describe), ", ") + <> ": the same project in other places. memory and the work ledger " + <> "read across all of them, and what you write is filed in this " + <> "workspace. A work item says where it was filed (its workspace field)." + } +} + +fn describe(member: String, presence: Presence) -> String { + case presence { + Gone -> member <> " (its folder is gone)" + _ -> member + } +} + +/// What albedo can tell about a member's folder. +type Presence { + Here + Gone + /// Its host did not answer, so whether the folder exists is unknown. + Unknown(target: String, why: ssh.Failure) +} + +/// A remote member is asked on its host; `wait_ms` bounds the wait for a +/// host that is not ready yet. +fn presence(member: String, wait_ms: Int) -> Presence { + case location.parse(member) { + Error(_) -> Here + Ok(at) -> + case folders.exists(at, wait_ms) { + Ok(True) -> Here + Ok(False) -> Gone + Error(why) -> + Unknown(location.ssh_target(at) |> result.unwrap(member), why) + } + } +} + +/// Every member's presence at once, so members whose hosts are slow to answer +/// wait side by side rather than one after another. A check still running at +/// the deadline (it crashed, or the machine is starved) is ended, so no late +/// answer lands in the caller's mailbox, and reads as unreachable. +fn presences(members: List(String), wait_ms: Int) -> List(Presence) { + let started = + list.map(members, fn(member) { + let answer = process.new_subject() + let check = + process.spawn_unlinked(fn() { + process.send(answer, presence(member, wait_ms)) + }) + #(member, answer, check) + }) + let deadline = now_ms() + wait_ms + folders.exists_ms + 1000 + list.map(started, fn(started) { + let #(member, answer, check) = started + process.receive(answer, int.max(0, deadline - now_ms())) + |> result.lazy_unwrap(fn() { + process.kill(check) + Unknown(member, ssh.Unreachable("the check did not answer in time")) + }) + }) +} + +fn now_ms() -> Int { + monotonic_time(Millisecond) +} + +type TimeUnit { + Millisecond +} + +@external(erlang, "erlang", "monotonic_time") +fn monotonic_time(unit: TimeUnit) -> Int + +/// How long the page waits for a remote member's host to answer. +const page_wait_ms = 5000 + +fn command(storage: store.Store, workspace: String) -> Command { + Command( + "/link", + "Show the workspaces linked with this one, or change them: add , remove . Linked workspaces share memory and work items; each keeps its own, so removing one loses nothing.", + [ + Argument("action", "what to change; omit to list the links", False, [ + "add", "remove", + ]), + Argument( + "details", + "add: · remove: ", + False, + [], + ), + ], + False, + False, + True, + None, + fn(_, caller, args) { + let #(action, details) = page.args(args, "") + case action, caller { + "", _ -> Ok(listing(links.group(storage, workspace))) + _, UserCall -> change(storage, workspace, action, details) + _, _ -> Error("only a user links workspaces") + } + }, + ) +} + +fn listing(group: List(String)) -> command.Outcome { + let rows = case group { + [_] | [] -> [] + [own, ..linked] -> [ + page.detail_row(own, own, "here", page.Active, ""), + ..list.map2(linked, presences(linked, page_wait_ms), row) + ] + } + Data( + page.to_json(page.Document( + "links", + case list.length(group) { + n if n > 1 -> int.to_string(n - 1) <> " linked" + _ -> "" + }, + "not linked · a links a workspace holding the same project", + rows, + [ + page.Action( + "a", + "link", + "add", + False, + page.Text("workspace", False), + False, + ), + page.Action("x", "unlink", "remove", True, page.NoInput, True), + ], + None, + )), + ) +} + +/// A linked member as the page shows it. A host that does not answer is not +/// a gone folder: the row says why, and nothing suggests removing it. +fn row(member: String, presence: Presence) -> page.Row { + case presence { + Here -> page.detail_row(member, member, "", page.Plain, "") + Gone -> + page.detail_row( + member, + member, + "gone", + page.Muted, + "its folder no longer exists; its memory and work items stay until you remove it", + ) + Unknown(target, why) -> { + let #(badge, tone) = case why { + ssh.Warming -> #("connecting", page.Muted) + ssh.NeedsAuth(..) -> #("sign in", page.Warning) + ssh.Unreachable(_) | ssh.Unsupported(_) -> #("unreachable", page.Muted) + } + page.detail_row( + member, + member, + badge, + tone, + ssh.describe(target, why) + <> "; its memory and work items are still read", + ) + } + } +} + +fn change( + storage: store.Store, + workspace: String, + action: String, + details: String, +) -> Result(command.Outcome, String) { + let group = links.group(storage, workspace) + use #(message, notes) <- result.try(case action { + "add" -> { + use other <- result.try( + location.workspace(details) |> result.map(location.to_string), + ) + use _ <- result.try(case other == workspace, list.contains(group, other) { + True, _ -> Error("that is this workspace") + _, True -> Error("already linked with " <> other) + False, False -> Ok(Nil) + }) + let theirs = links.group(storage, other) + use _ <- result.try(links.link(storage, workspace, other)) + Ok(#( + "linked with " <> other, + list.append(joined(group, theirs), joined(theirs, group)), + )) + } + "remove" -> { + use _ <- result.try(case group, list.contains(group, details) { + [_, _, ..], True -> Ok(Nil) + _, _ -> Error(details <> " is not linked with this workspace") + }) + use _ <- result.try(links.unlink(storage, details)) + let rest = list.filter(group, fn(member) { member != details }) + Ok( + #( + case details == workspace { + True -> "left the group" + False -> "unlinked " <> details + }, + [ + #(details, left(rest)), + ..list.map(rest, fn(member) { #(member, unlinked(details)) }) + ], + ), + ) + } + _ -> Error("unknown action " <> action <> "; use add or remove") + }) + let told = case tell(storage, notes) { + 0 -> "; no session was open to tell" + 1 -> "; told 1 open session" + n -> "; told " <> int.to_string(n) <> " open sessions" + } + Ok(Data(json.object([#("message", json.string(message <> told))]))) +} + +/// The note for every workspace in `members` that now reads `others`. It +/// carries their memory as a new session's snapshot holds it, so a session +/// that opened before the link sees the same text without rebuilding its +/// prompt (and losing its prompt cache). +fn joined( + members: List(String), + others: List(String), +) -> List(#(String, StateOp)) { + let names = string.join(others, ", ") + let snapshot = case linked_memory(others) { + "" -> "" + memory -> " Their memory, as a new session's snapshot holds it:\n" <> memory + } + let note = + note( + "linked with " <> names, + "The user linked this workspace with " + <> names + <> ": memory and the work ledger now also read their notes and items. What you write stays in this workspace." + <> snapshot, + ) + list.map(members, fn(member) { #(member, note) }) +} + +fn left(rest: List(String)) -> StateOp { + let names = string.join(rest, ", ") + note( + "unlinked from " <> names, + "The user unlinked this workspace from " + <> names + <> ": memory and the work ledger cover only this workspace again. Their notes in this session's memory snapshot are left over from before; nothing was deleted.", + ) +} + +fn unlinked(member: String) -> StateOp { + note( + "unlinked " <> member, + "The user unlinked " + <> member + <> " from this workspace's group: its memory and work items are no longer read here, and its notes in this session's memory snapshot are left over from before; nothing was deleted.", + ) +} + +fn note(display: String, text: String) -> StateOp { + Note("links", display, "" <> text <> "") +} + +/// Queue each workspace's note in every open session there, answering how +/// many took it. A closed session needs none: it composes its snapshot +/// afresh when it opens. +fn tell(storage: store.Store, notes: List(#(String, StateOp))) -> Int { + conversation.list(storage) + |> result.unwrap([]) + |> list.count(fn(info) { + case list.key_find(notes, info.cwd) { + Ok(note) -> result.is_ok(command.context(info.id).state(note)) + Error(Nil) -> False + } + }) +} + +@external(erlang, "albedo_memory", "linked") +fn linked_memory(workspaces: List(String)) -> String diff --git a/src/albedo/harness/extensions/memory/albedo_memory.erl b/src/albedo/harness/extensions/memory/albedo_memory.erl index b31b3b9ee..20812ee54 100644 --- a/src/albedo/harness/extensions/memory/albedo_memory.erl +++ b/src/albedo/harness/extensions/memory/albedo_memory.erl @@ -1,28 +1,152 @@ +%% Project memory on the daemon's disk: one directory per workspace under +%% $ALBEDO_HOME/memories, `memory.md` plus `journal/.md`. The kernel +%% reaches it through the memory host route wherever the kernel runs, so a +%% remote session's memory lives here too. Writes to one workspace are +%% serialized through a global lock; reads span a workspace's link group. -module(albedo_memory). --export([load/1]). +-export([load/1, linked/1, read/1, save/2, append/2, journal/3, documents/1]). -include_lib("kernel/include/file.hrl"). -%% The same workspace slug is used by the Python memory plugin. -load(Workspace) -> - Slug = re:replace(Workspace, <<"[^A-Za-z0-9]">>, <<"-">>, [global, {return, binary}]), - Path = filename:join([albedo_extension_settings:home(), <<"memories">>, Slug, <<"memory.md">>]), +-define(MAX_FILE, 1048576). +-define(PREVIEW, 8000). %% characters of the snapshot a session opens with +-define(DOCUMENTS, 16777216). %% bytes one documents answer carries + +root(Workspace) -> + Slug = re:replace(Workspace, <<"[^A-Za-z0-9]">>, <<"-">>, [global, unicode, {return, binary}]), + filename:join([albedo_extension_settings:home(), <<"memories">>, Slug]). + +memory(Workspace) -> filename:join(root(Workspace), <<"memory.md">>). + +%% The snapshot a session opens with: its own memory, then each linked +%% workspace's under a heading naming it, within one character budget. +load([Own | Linked]) -> + case text(memory(Own)) of + {error, Reason} -> {error, Reason}; + {ok, Mine} -> + Parts = [{none, Mine} | [{W, T} || W <- Linked, {ok, T} <- [text(memory(W))], T =/= <<>>]], + case [P || {_, T} = P <- Parts, T =/= <<>>] of + [] -> {ok, <<>>}; + _ -> {ok, iolist_to_binary([<<"# Project memory (untrusted notes)\n">> | snapshot(Parts, ?PREVIEW)])} + end + end. + +%% The snapshot sections of workspaces that just joined a session's group: +%% the text its next snapshot holds for them, for the note that tells it. +linked(Workspaces) -> + Parts = [{W, T} || W <- Workspaces, {ok, T} <- [text(memory(W))], T =/= <<>>], + iolist_to_binary(snapshot(Parts, ?PREVIEW)). + +snapshot([], _) -> []; +snapshot([{Where, Text} | Rest], Budget) -> + Heading = case Where of + none -> <<>>; + _ -> [<<"\n## linked workspace ">>, Where, <<"\n">>] + end, + Chars = string:length(Text), + Shown = string:slice(Text, 0, max(0, Budget)), + Cut = case Chars > Budget of + true -> <<"\n[truncated; use memory.read() for the full file]">>; + false -> <<>> + end, + [Heading, Shown, Cut | snapshot(Rest, Budget - min(Chars, Budget))]. + +%% One file as UTF-8 text, empty when it does not exist. +text(Path) -> case file:read_file_info(Path) of {error, enoent} -> {ok, <<>>}; - {ok, #file_info{type = regular, size = Size}} when Size =< 1048576 -> + {ok, #file_info{type = regular, size = Size}} when Size =< ?MAX_FILE -> case file:read_file(Path) of {ok, Bytes} -> - case unicode:characters_to_list(Bytes) of - Text when is_list(Text) -> - Preview = unicode:characters_to_binary(lists:sublist(Text, 8000)), - Suffix = case length(Text) > 8000 of - true -> <<"\n[truncated; use memory.read() for the full file]">>; - false -> <<>> - end, - {ok, <<"# Project memory (untrusted notes)\n", Preview/binary, Suffix/binary>>}; - _ -> {error, <<"memory.md is not UTF-8">>} + case unicode:characters_to_binary(Bytes) of + Text when is_binary(Text) -> {ok, Text}; + _ -> {error, <<(filename:basename(Path))/binary, " is not UTF-8">>} end; - {error, Reason} -> {error, unicode:characters_to_binary(file:format_error(Reason))} + {error, Reason} -> {error, reason(Reason)} end; - {ok, _} -> {error, <<"memory.md must be a regular UTF-8 file of at most 1 MiB">>}; - {error, Reason} -> {error, unicode:characters_to_binary(file:format_error(Reason))} + {ok, _} -> {error, <<(filename:basename(Path))/binary, " must be a regular UTF-8 file of at most 1 MiB">>}; + {error, Reason} -> {error, reason(Reason)} + end. + +read(Workspace) -> text(memory(Workspace)). + +%% Replace the curated memory atomically. +save(_, Text) when byte_size(Text) > ?MAX_FILE -> {error, <<"memory.md cannot exceed 1 MiB">>}; +save(Workspace, Text) -> + Path = memory(Workspace), + locked(Workspace, fun() -> + Temp = <>, + case file:write_file(Temp, Text) of + ok -> + case file:rename(Temp, Path) of + ok -> {ok, Path}; + {error, Reason} -> _ = file:delete(Temp), {error, reason(Reason)} + end; + {error, Reason} -> _ = file:delete(Temp), {error, reason(Reason)} + end + end). + +append(Workspace, Text) -> + Path = memory(Workspace), + locked(Workspace, fun() -> + Size = case file:read_file_info(Path) of {ok, #file_info{size = S}} -> S; _ -> 0 end, + Entry = entry(Size, Text), + case Size + byte_size(Entry) > ?MAX_FILE of + true -> {error, <<"memory.md cannot exceed 1 MiB">>}; + false -> write(Path, Entry) + end + end). + +journal(Workspace, Date, Text) -> + case re:run(Date, <<"^[0-9]{4}-[0-9]{2}-[0-9]{2}$">>, [{capture, none}]) of + nomatch -> {error, <<"journal date must be YYYY-MM-DD">>}; + match -> + Path = filename:join([root(Workspace), <<"journal">>, <>]), + locked(Workspace, fun() -> + Size = case file:read_file_info(Path) of {ok, #file_info{size = S}} -> S; _ -> 0 end, + write(Path, entry(Size, Text)) + end) end. + +%% A note on its own line, a blank line from the one before it. +entry(Size, Text) -> + Body = string:trim(Text, trailing, "\n"), + Gap = case Size > 0 of true -> <<"\n">>; false -> <<>> end, + iolist_to_binary([Gap, Body, <<"\n">>]). + +write(Path, Entry) -> + case file:write_file(Path, Entry, [append]) of + ok -> {ok, Path}; + {error, Reason} -> {error, reason(Reason)} + end. + +locked(Workspace, Fun) -> + case filelib:ensure_path(filename:join(root(Workspace), <<"journal">>)) of + ok -> global:trans({{?MODULE, root(Workspace)}, self()}, Fun); + {error, Reason} -> {error, reason(Reason)} + end. + +%% Every memory and journal file of the given workspaces, for grep and +%% search: [{Workspace, Relative, Text}] and whether the byte budget cut the +%% list short. Unreadable files are left out. +documents(Workspaces) -> documents(Workspaces, ?DOCUMENTS, []). + +documents([], _, Acc) -> {lists:reverse(Acc), false}; +documents([Workspace | Rest], Budget, Acc) -> + Root = root(Workspace), + Journals = lists:sort(filelib:wildcard("journal/*.md", binary_to_list(Root))), + Files = [<<"memory.md">> | [unicode:characters_to_binary(J) || J <- Journals]], + case collect(Workspace, Root, Files, Budget, Acc) of + {full, Acc1} -> {lists:reverse(Acc1), true}; + {Left, Acc1} -> documents(Rest, Left, Acc1) + end. + +collect(_, _, [], Budget, Acc) -> {Budget, Acc}; +collect(Workspace, Root, [Relative | Rest], Budget, Acc) -> + case text(filename:join(Root, Relative)) of + {ok, <<>>} -> collect(Workspace, Root, Rest, Budget, Acc); + {ok, Text} when byte_size(Text) > Budget -> {full, Acc}; + {ok, Text} -> collect(Workspace, Root, Rest, Budget - byte_size(Text), [{Workspace, Relative, Text} | Acc]); + {error, _} -> collect(Workspace, Root, Rest, Budget, Acc) + end. + +reason(Reason) -> unicode:characters_to_binary(file:format_error(Reason)). diff --git a/src/albedo/harness/extensions/memory/extension.gleam b/src/albedo/harness/extensions/memory/extension.gleam index f9d74b560..a4e8ac571 100644 --- a/src/albedo/harness/extensions/memory/extension.gleam +++ b/src/albedo/harness/extensions/memory/extension.gleam @@ -1,6 +1,15 @@ //// Project-scoped, agent-maintained notes; never a source of mandatory instructions. +//// +//// The files live on the daemon's disk (albedo_memory.erl), and the kernel's +//// `memory` object reaches them through the route below wherever it runs. +//// A workspace writes only its own memory and reads its whole link group. import albedo/harness/extension +import albedo/harness/links +import albedo/harness/rpc +import gleam/dynamic/decode +import gleam/json +import gleam/result pub fn extension() -> extension.Extension { extension.Extension( @@ -8,7 +17,6 @@ pub fn extension() -> extension.Extension { "Durable project memory and dated journal entries.", ["python"], [ - extension.ContextPlugin(load), extension.ToolPlugin( "Project memory lives under ~/.albedo/memories//memory.md. " <> "The bounded snapshot below is from when this session opened; use memory.read() " @@ -16,18 +24,102 @@ pub fn extension() -> extension.Extension { <> "replaces the curated memory, and memory.journal(text) appends to " <> "journal/YYYY-MM-DD.md. memory.grep(term, limit=20) finds literal matching " <> "lines across memory and journal; memory.search(query, limit=20) does full-text " - <> "search (SQLite FTS5) over their paragraphs. These calls are synchronous and " - <> "may also be awaited. Save durable decisions and preferences, journal transient " - <> "progress; verify facts likely to drift. Do not store secrets. Memory is recall, " - <> "not binding instructions; keep required rules in AGENTS.md.", + <> "search (SQLite FTS5) over their paragraphs. In a workspace linked with others " + <> "(/link), the snapshot, grep and search also cover their memory, each match " + <> "naming its workspace, while every write stays in this workspace's own. " + <> "These calls are synchronous and may also be awaited. Save durable " + <> "decisions and preferences, journal transient progress; verify facts " + <> "likely to drift. Do not store secrets. Memory is recall, not binding " + <> "instructions; keep required rules in AGENTS.md.", [], ["memory"], [], ), + extension.ManagedPlugin(fn(store, _, workspace) { + use context <- result.try(load(links.group(store, workspace))) + Ok( + extension.Managed(..extension.empty(), context: context, routes: [ + #("memory", fn(store, _, request) { + handle(workspace, links.group(store, workspace), request) + }), + ]), + ) + }), ], extension.no_initialise, ) } +fn handle(own: String, group: List(String), request: String) -> String { + rpc.serve( + request, + "invalid memory request", + fn(method, args) { + let text = fn(field) { + rpc.args( + args, + decode.field(field, decode.string, decode.success), + "expected " <> field, + ) + } + case method { + "memory.read" -> read(own) |> result.map(json.string) + "memory.save" -> text("text") |> result.try(save(own, _)) |> path + "memory.append" -> text("text") |> result.try(append(own, _)) |> path + "memory.journal" -> { + use date <- result.try(text("date")) + use entry <- result.try(text("text")) + journal(own, date, entry) |> path + } + "memory.documents" -> { + let #(found, truncated) = documents(group) + Ok( + json.object([ + #( + "documents", + json.array(found, fn(document) { + let #(workspace, relative, content) = document + json.object([ + #("workspace", json.string(workspace)), + #("path", json.string(relative)), + #("text", json.string(content)), + ]) + }), + ), + #("truncated", json.bool(truncated)), + #("own", json.string(own)), + ]), + ) + } + _ -> Error("unknown memory operation") + } + }, + fn(message) { #("invalid", message) }, + ) +} + +fn path(written: Result(String, String)) -> Result(json.Json, String) { + result.map(written, json.string) +} + @external(erlang, "albedo_memory", "load") -fn load(workspace: String) -> Result(String, String) +fn load(group: List(String)) -> Result(String, String) + +@external(erlang, "albedo_memory", "read") +fn read(workspace: String) -> Result(String, String) + +@external(erlang, "albedo_memory", "save") +fn save(workspace: String, text: String) -> Result(String, String) + +@external(erlang, "albedo_memory", "append") +fn append(workspace: String, text: String) -> Result(String, String) + +@external(erlang, "albedo_memory", "journal") +fn journal( + workspace: String, + date: String, + text: String, +) -> Result(String, String) + +@external(erlang, "albedo_memory", "documents") +fn documents(group: List(String)) -> #(List(#(String, String, String)), Bool) diff --git a/src/albedo/harness/extensions/work/command.gleam b/src/albedo/harness/extensions/work/command.gleam index 33fa12687..b4a1a25e8 100644 --- a/src/albedo/harness/extensions/work/command.gleam +++ b/src/albedo/harness/extensions/work/command.gleam @@ -49,7 +49,7 @@ fn listing(store: work.Store, cwd: String) -> Result(command.Outcome, String) { work.list(store, cwd, 0, 200) |> result.map_error(describe), ) let ordered = list.sort(items, fn(a, b) { int.compare(rank(a), rank(b)) }) - let rows = list.map(ordered, row) + let rows = list.map(ordered, row(_, cwd)) let pending = list.filter(ordered, fn(item) { rank(item) < 3 }) Ok( Data( @@ -86,7 +86,7 @@ fn listing(store: work.Store, cwd: String) -> Result(command.Outcome, String) { ), page.Action("x", "remove", "remove", True, page.NoInput, True), ], - Some(page.Glance("pending work", list.map(pending, row))), + Some(page.Glance("pending work", list.map(pending, row(_, cwd)))), )), ), ) @@ -107,13 +107,18 @@ fn rank(item: work.Item) -> Int { status_style(item.status).0 } -fn row(item: work.Item) -> page.Row { +/// An item filed in a linked workspace says where. +fn row(item: work.Item, cwd: String) -> page.Row { + let detail = case item.workspace == cwd { + True -> item.notes + False -> string.trim(item.notes <> "\n\nfiled in " <> item.workspace) + } page.detail_row( int.to_string(item.id), item.title, work.status_name(item.status), status_style(item.status).1, - item.notes, + detail, ) } diff --git a/src/albedo/harness/extensions/work/ledger.gleam b/src/albedo/harness/extensions/work/ledger.gleam index 85454dbf4..7f2a6b14c 100644 --- a/src/albedo/harness/extensions/work/ledger.gleam +++ b/src/albedo/harness/extensions/work/ledger.gleam @@ -1,4 +1,5 @@ import albedo/daemon/store as storage +import albedo/harness/links import gleam/dynamic/decode import gleam/erlang/process import gleam/json @@ -27,6 +28,8 @@ pub type Item { session: Option(String), run: Option(String), revision: Int, + /// Where the item was filed: this workspace, or one linked with it. + workspace: String, ) } @@ -74,7 +77,7 @@ CREATE INDEX IF NOT EXISTS work_parent ON work(parent); CREATE INDEX IF NOT EXISTS work_session ON work(session); " -const columns = "id,title,notes,status,parent,session,run,revision" +const columns = "id,title,notes,status,parent,session,run,revision,cwd" const legacy_cwd = "__albedo_legacy__" @@ -128,7 +131,18 @@ fn decoder() -> decode.Decoder(Item) { use session <- decode.field(5, decode.optional(decode.string)) use run <- decode.field(6, decode.optional(decode.string)) use revision <- decode.field(7, decode.int) - decode.success(Item(id, title, notes, status, parent, session, run, revision)) + use workspace <- decode.field(8, decode.string) + decode.success(Item( + id, + title, + notes, + status, + parent, + session, + run, + revision, + workspace, + )) } fn rows( @@ -139,15 +153,31 @@ fn rows( storage.rows(db, sql, args, decoder()) |> result.map_error(Storage) } +/// `cwd IN (...)` over the workspace and the ones linked with it, and its +/// arguments: every read and change reaches the whole group, and only a new +/// item is filed under the workspace itself. +fn scope( + db: sqlight.Connection, + cwd: String, +) -> #(String, List(sqlight.Value)) { + let group = links.members(db, cwd) + #( + "cwd IN (" <> string.join(list.map(group, fn(_) { "?" }), ",") <> ")", + list.map(group, sqlight.text), + ) +} + fn find( db: sqlight.Connection, cwd: String, id: Int, ) -> Result(List(Item), Error) { - rows(db, "SELECT " <> columns <> " FROM work WHERE cwd=? AND id=?", [ - sqlight.text(cwd), - sqlight.int(id), - ]) + let #(within, group) = scope(db, cwd) + rows( + db, + "SELECT " <> columns <> " FROM work WHERE " <> within <> " AND id=?", + list.append(group, [sqlight.int(id)]), + ) } fn one(items: List(Item)) -> Result(Item, Error) { @@ -170,12 +200,15 @@ pub fn list( True -> Error(Invalid("after >= 0 and 1 <= limit <= 200 required")) False -> storage.query(store, fn(db) { + let #(within, group) = scope(db, cwd) rows( db, "SELECT " <> columns - <> " FROM work WHERE cwd=? AND id > ? ORDER BY id LIMIT ?", - [sqlight.text(cwd), sqlight.int(after), sqlight.int(limit)], + <> " FROM work WHERE " + <> within + <> " AND id > ? ORDER BY id LIMIT ?", + list.append(group, [sqlight.int(after), sqlight.int(limit)]), ) }) } @@ -225,7 +258,7 @@ pub fn update(store: Store, cwd: String, item: Item) -> Result(Item, Error) { [] -> Error(NotFound) [current, ..] if current.parent != item.parent -> Error(Invalid("parent cannot change")) - _ -> { + [current, ..] -> { use changed <- result.try( rows( db, @@ -237,7 +270,7 @@ pub fn update(store: Store, cwd: String, item: Item) -> Result(Item, Error) { sqlight.text(status_name(item.status)), sqlight.nullable(sqlight.text, item.session), sqlight.nullable(sqlight.text, item.run), - sqlight.text(cwd), + sqlight.text(current.workspace), sqlight.int(item.id), sqlight.int(item.revision), ], @@ -261,25 +294,24 @@ pub fn delete( storage.query(store, fn(db) { use existing <- result.try(find(db, cwd, id)) use children <- result.try( - rows( - db, - "SELECT " <> columns <> " FROM work WHERE cwd=? AND parent=? LIMIT 1", - [ - sqlight.text(cwd), - sqlight.int(id), - ], - ), + rows(db, "SELECT " <> columns <> " FROM work WHERE parent=? LIMIT 1", [ + sqlight.int(id), + ]), ) case existing, children { [], _ -> Error(NotFound) _, [_, ..] -> Error(Invalid("remove its sub-items first")) [current, ..], [] if current.revision != revision -> Error(Conflict) - _, [] -> + [current, ..], [] -> rows( db, "DELETE FROM work WHERE cwd=? AND id=? AND revision=? RETURNING " <> columns, - [sqlight.text(cwd), sqlight.int(id), sqlight.int(revision)], + [ + sqlight.text(current.workspace), + sqlight.int(id), + sqlight.int(revision), + ], ) |> result.try(one_or_conflict) } @@ -319,6 +351,7 @@ pub fn to_json(item: Item) -> json.Json { #("session", json.nullable(item.session, json.string)), #("run", json.nullable(item.run, json.string)), #("revision", json.int(item.revision)), + #("workspace", json.string(item.workspace)), ]) } diff --git a/src/albedo/harness/links.gleam b/src/albedo/harness/links.gleam new file mode 100644 index 000000000..30cb212f4 --- /dev/null +++ b/src/albedo/harness/links.gleam @@ -0,0 +1,107 @@ +//// Workspaces linked into one project: the same work in several places, such +//// as one repository checked out on two hosts. Each workspace keeps its own +//// memory and work items, written where it is; reads cover the whole group, +//// so nothing is ever merged and unlinking loses nothing. A member whose +//// folder is gone stays until someone removes it. robot-docs/workspaces.md +//// has the rules. + +import albedo/daemon/store +import gleam/dynamic/decode +import gleam/list +import gleam/result +import sqlight + +pub fn apply(db: sqlight.Connection) -> Result(Nil, String) { + store.exec( + db, + "CREATE TABLE IF NOT EXISTS workspace_links ( + workspace TEXT PRIMARY KEY, grp INTEGER NOT NULL, + linked_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))); + CREATE INDEX IF NOT EXISTS workspace_links_grp ON workspace_links(grp);", + ) +} + +/// The workspace and every workspace linked with it, the workspace first and +/// the rest in the order they joined. Alone, or with no links table (an +/// embedded runtime), it is just itself. +pub fn members(db: sqlight.Connection, workspace: String) -> List(String) { + let linked = + store.rows( + db, + "SELECT workspace FROM workspace_links WHERE workspace<>?1 AND grp=(SELECT grp FROM workspace_links WHERE workspace=?1) ORDER BY linked_at, workspace", + [sqlight.text(workspace)], + decode.field(0, decode.string, decode.success), + ) + [workspace, ..result.unwrap(linked, [])] +} + +pub fn group(storage: store.Store, workspace: String) -> List(String) { + store.query(storage, members(_, workspace)) +} + +/// Link two workspaces, and so their groups: everything `other` was linked +/// with joins `workspace`'s group. +pub fn link( + storage: store.Store, + workspace: String, + other: String, +) -> Result(Nil, String) { + store.query(storage, fn(db) { + store.transaction(db, fn() { + use _ <- result.try(apply(db)) + use groups <- result.try(store.rows( + db, + "SELECT grp FROM workspace_links WHERE workspace IN (?,?) ORDER BY workspace=? DESC", + [sqlight.text(workspace), sqlight.text(other), sqlight.text(workspace)], + decode.field(0, decode.int, decode.success), + )) + use target <- result.try(case groups { + [first, ..] -> Ok(first) + [] -> + store.rows( + db, + "SELECT coalesce(max(grp),0)+1 FROM workspace_links", + [], + decode.field(0, decode.int, decode.success), + ) + |> result.map(fn(next) { list.first(next) |> result.unwrap(1) }) + }) + use _ <- result.try( + list.try_each(list.drop(groups, 1), fn(old) { + store.run(db, "UPDATE workspace_links SET grp=? WHERE grp=?", [ + sqlight.int(target), + sqlight.int(old), + ]) + }), + ) + list.try_each([workspace, other], fn(member) { + store.run( + db, + "INSERT INTO workspace_links(workspace,grp) VALUES(?,?) ON CONFLICT(workspace) DO NOTHING", + [sqlight.text(member), sqlight.int(target)], + ) + }) + }) + }) +} + +/// Take one workspace out of its group. Its memory and work items stay +/// where they are; linking it again brings them back. A group left with one +/// member is no group. +pub fn unlink(storage: store.Store, workspace: String) -> Result(Nil, String) { + store.query(storage, fn(db) { + store.transaction(db, fn() { + use _ <- result.try(apply(db)) + use _ <- result.try( + store.run(db, "DELETE FROM workspace_links WHERE workspace=?", [ + sqlight.text(workspace), + ]), + ) + store.run( + db, + "DELETE FROM workspace_links WHERE grp IN (SELECT grp FROM workspace_links GROUP BY grp HAVING count(*)<2)", + [], + ) + }) + }) +} diff --git a/src/albedo/harness/ssh.gleam b/src/albedo/harness/ssh.gleam index e1706b9e0..5cff92626 100644 --- a/src/albedo/harness/ssh.gleam +++ b/src/albedo/harness/ssh.gleam @@ -56,6 +56,15 @@ pub fn ready(target: String, wait_ms: Int) -> Result(Host, Failure) { } } +/// The host as a recent probe found it, without waiting: a stale or missing +/// answer starts a probe in the background and reads as still warming. +pub fn known(target: String) -> Result(Host, Failure) { + case peek(target) { + Ok(answer) -> decoded(answer) + Error(Nil) -> Error(Warming) + } +} + /// The host's home directory, for resolving `host:~/x`. pub fn home(target: String) -> Result(String, String) { ready(target, 30_000) @@ -75,10 +84,7 @@ pub fn describe(target: String, failure: Failure) -> String { /// The `/hosts/:host` answer: the cached probe, or `warming` while one runs. pub fn status(target: String) -> Json { - case peek(target) { - Ok(answer) -> wire(target, decoded(answer)) - Error(Nil) -> wire(target, Error(Warming)) - } + wire(target, known(target)) } /// The state of a host's recent probe, without probing: `ready`, diff --git a/test/e2e/links_test.py b/test/e2e/links_test.py new file mode 100644 index 000000000..ff3039fb5 --- /dev/null +++ b/test/e2e/links_test.py @@ -0,0 +1,174 @@ +"""Linked workspaces: one project in several places. + +A workspace linked with another reads that one's memory and work items as +well as its own, while everything it writes is filed under itself. A member +whose folder is gone keeps what it had until the user removes it, and +unlinking deletes nothing. +""" + +import json +import re +import shutil +import unittest +import urllib.error + +from harness import Albedo, Provider, python, text + + +class LinkTests(unittest.TestCase): + def setUp(self): + self.cells = [] + + def script(request): + if request["input"][-1].get("role") == "user" and self.cells: + return python(self.cells.pop(0)) + return text("ok") + + self.provider = Provider(script) + self.addCleanup(self.provider.close) + self.app = Albedo(self.provider, protocol="responses") + self.app.__enter__() + self.addCleanup(self.app.__exit__, None, None, None) + + def cell(self, session, code): + self.cells.append(code) + self.app.prompt(session, "run it").close() + self.app.idle(session) + results = [ + json.loads(event["result"]) + for event in self.app.events(session) + if event.get("type") == "tool" and event.get("name") == "python" + ] + self.assertEqual(results[-1]["status"], "ok", results[-1]) + return results[-1] + + def link(self, session, **args): + with self.app.api( + f"/sessions/{session}/commands", {"name": "/link", "args": args} + ) as response: + return json.load(response)["result"] + + def memory_file(self, workspace): + slug = re.sub(r"[^A-Za-z0-9]", "-", str(workspace)) + return self.app.home / "memories" / slug / "memory.md" + + def test_linked_workspaces_read_each_other_and_write_their_own(self): + laptop, server = self.app.root / "laptop", self.app.root / "server" + laptop.mkdir() + server.mkdir() + first = self.app.session(laptop) + self.cell( + first, + "memory.append('the cache key is the prefix hash')\n" + "await work.create('ship the picker')", + ) + + here = self.app.session(server) + added = self.link(here, action="add", details=str(laptop)) + self.assertIn("linked with " + str(laptop), added["message"]) + rows = self.link(here)["page"]["rows"] + self.assertEqual( + [(row["id"], row["badge"]) for row in rows], + [(str(server), "here"), (str(laptop), "")], + ) + + # A session opened after the link starts with the linked memory and + # is told it is linked. + later = self.app.session(server) + read = self.cell( + later, + "memory.append('chernobog runs the gate')\n" + "await work.create('profile the gate')\n" + "print(memory.grep('cache key'))\n" + "print(sorted((i.title, i.workspace) for i in await work.list()))", + ) + self.assertIn( + "[" + str(laptop) + "] memory.md:1: the cache key", read["output"] + ) + self.assertIn(f"('ship the picker', '{laptop}')", read["output"]) + self.assertIn(f"('profile the gate', '{server}')", read["output"]) + instructions = self.provider.requests[-1]["request"]["instructions"] + self.assertIn("the cache key is the prefix hash", instructions) + self.assertIn("This workspace is linked with " + str(laptop), instructions) + # Writes stayed where they were made. + self.assertEqual( + self.memory_file(server).read_text(), "chernobog runs the gate\n" + ) + self.assertEqual( + self.memory_file(laptop).read_text(), "the cache key is the prefix hash\n" + ) + + # The laptop checkout goes away: it is shown as gone and still read. + shutil.rmtree(laptop) + rows = self.link(here)["page"]["rows"] + self.assertEqual(rows[1]["badge"], "gone") + kept = self.cell(later, "print(memory.grep('cache key'))") + self.assertIn("the cache key", kept["output"]) + + # Removing it stops the reads and deletes nothing. + self.link(here, action="remove", details=str(laptop)) + self.assertEqual(self.link(here)["page"]["rows"], []) + alone = self.cell( + later, + "print(memory.grep('cache key'))\n" + "print([i.title for i in await work.list()])", + ) + self.assertNotIn("the cache key", alone["output"]) + self.assertNotIn("ship the picker", alone["output"]) + self.assertTrue(self.memory_file(laptop).exists()) + + def test_open_sessions_in_the_group_are_told_with_the_memory_they_now_read(self): + laptop, server = self.app.root / "desk", self.app.root / "rack" + laptop.mkdir() + server.mkdir() + on_laptop = self.app.session(laptop) + self.cell(on_laptop, "memory.append('the cache key is the prefix hash')") + here, beside = self.app.session(server), self.app.session(server) + self.cell(beside, "1") + unopened = self.app.session(server) + + added = self.link(here, action="add", details=str(laptop)) + self.assertIn("told 3 open sessions", added["message"]) + + def next_request(session): + self.app.prompt(session, "hi").close() + self.app.idle(session) + request = self.provider.requests[-1]["request"] + return json.dumps(request["input"]), request["instructions"] + + # Sessions in this workspace opened before the link: the laptop's + # memory arrives in the note, not in a rebuilt prompt. + for session in (here, beside): + told, instructions = next_request(session) + self.assertIn("linked this workspace with " + str(laptop), told) + self.assertIn("the cache key is the prefix hash", told) + self.assertNotIn("the cache key", instructions) + told, _ = next_request(on_laptop) + self.assertIn("linked this workspace with " + str(server), told) + # One that never opened composes its snapshot when it does. + told, instructions = next_request(unopened) + self.assertNotIn("linked this workspace", told) + self.assertIn("the cache key is the prefix hash", instructions) + + self.link(here, action="remove", details=str(laptop)) + told, _ = next_request(on_laptop) + self.assertIn("unlinked this workspace from " + str(server), told) + told, _ = next_request(beside) + self.assertIn("The user unlinked " + str(laptop), told) + + def test_a_link_is_refused_for_this_workspace_and_missing_folders(self): + workspace = self.app.root / "alone" + workspace.mkdir() + session = self.app.session(workspace) + for details, reason in ( + (str(workspace), "that is this workspace"), + (str(self.app.root / "nowhere"), "must be an existing absolute directory"), + ): + with self.assertRaises(urllib.error.HTTPError) as refused: + self.link(session, action="add", details=details) + self.assertIn(reason, refused.exception.read().decode()) + self.assertEqual(self.link(session)["page"]["rows"], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/e2e/remote_kernels_test.py b/test/e2e/remote_kernels_test.py index d00a3234b..a22d26f36 100644 --- a/test/e2e/remote_kernels_test.py +++ b/test/e2e/remote_kernels_test.py @@ -9,6 +9,7 @@ person to sign in, and one that cannot be reached. import json import os +import re import shutil import signal import subprocess @@ -40,6 +41,7 @@ fi case "$target" in gone) echo "ssh: connect to host gone port 22: Connection refused" >&2; exit 255 ;; locked) echo "locked: Permission denied (publickey)." >&2; exit 255 ;; + slow-*) sleep 3; echo "ssh: connect to host $target port 22: Connection refused" >&2; exit 255 ;; esac path={bin}:/usr/bin:/bin [ "$target" = oldhost ] && path={old}:$path @@ -231,6 +233,85 @@ class RemoteKernelTests(unittest.TestCase): after = self.cell(session, "survivor += 1\n(survivor, os.getpid())") self.assertEqual(after["value"], f"(42, {first['value']})") + def test_a_remote_sessions_memory_is_the_daemons_and_links_with_a_local_one(self): + remote = f"fakehost:{self.project}" + session = self.create(remote)["id"] + self.cell(session, "memory.append('the gate runs on fakehost')") + slug = re.sub(r"[^A-Za-z0-9]", "-", remote) + written = self.app.home / "memories" / slug / "memory.md" + self.assertEqual(written.read_text(), "the gate runs on fakehost\n") + self.assertFalse((self.remote_home / ".albedo").exists()) + + # The same project checked out here, linked: it reads the remote one. + checkout = self.app.root / "checkout" + checkout.mkdir() + local = self.create(str(checkout))["id"] + with self.app.api( + f"/sessions/{local}/commands", + {"name": "/link", "args": {"action": "add", "details": remote}}, + ) as response: + self.assertIn("linked with", json.load(response)["result"]["message"]) + found = self.cell(local, "print(memory.grep('gate'))") + self.assertIn(f"[{remote}] memory.md:1: the gate runs", found["output"]) + + def test_a_linked_remote_folder_is_checked_on_its_host(self): + checkout = self.app.root / "checkout" + checkout.mkdir() + local = self.create(str(checkout))["id"] + + def link(**args): + with self.app.api( + f"/sessions/{local}/commands", {"name": "/link", "args": args} + ) as response: + return json.load(response)["result"] + + def badges(): + rows = link()["page"]["rows"][1:] + return {row["id"]: (row["badge"], row["detail"]) for row in rows} + + present = f"fakehost:{self.project}" + missing = f"fakehost:{self.remote_home}/missing" + for member in (present, missing, "gone:/srv/app"): + link(action="add", details=member) + found = badges() + self.assertEqual(found[present], ("", "")) + self.assertEqual(found[missing][0], "gone") + badge, detail = found["gone:/srv/app"] + self.assertEqual(badge, "unreachable") + self.assertIn("Connection refused", detail) + + # A host that stops answering is not a gone folder. + self.down.touch() + found = badges() + self.assertEqual(found[present][0], "unreachable") + self.assertEqual(found[missing][0], "unreachable") + self.down.unlink() + + # A session opening with the host's probe fresh is told what is gone. + self.cell(self.create(str(checkout))["id"], "1") + instructions = self.provider.requests[-1]["request"]["instructions"] + self.assertIn(f"{missing} (its folder is gone)", instructions) + self.assertNotIn(f"{present} (its folder is gone)", instructions) + + def test_linked_hosts_are_checked_side_by_side(self): + checkout = self.app.root / "slow-checkout" + checkout.mkdir() + local = self.create(str(checkout))["id"] + + def link(**args): + with self.app.api( + f"/sessions/{local}/commands", {"name": "/link", "args": args} + ) as response: + return json.load(response)["result"] + + for host in ("slow-a", "slow-b"): + link(action="add", details=f"{host}:/srv") + # Each host takes 3 s to refuse; one after the other would be 6. + began = time.monotonic() + rows = link()["page"]["rows"][1:] + self.assertLess(time.monotonic() - began, 5.5) + self.assertEqual([row["badge"] for row in rows], ["unreachable"] * 2) + def test_a_remote_home_is_resolved_and_stored_absolute(self): created = self.create("fakehost:~/proj") self.assertEqual(created["workspace"], f"fakehost:{self.project}")