From 109c267af77be2317f65e6feddde30e860173573 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 13 Oct 2026 16:37:37 -0700 Subject: [PATCH] clover: skills for cold reads and PR flow, jj copy-on-write checkouts, drop workspaces package Add the cold-read skill and a Cold Read section in AGENTS.md: anything that leaves the thread is reviewed by a reader with no context, with Sonnet at low effort as the reader and Terra as the fallback. Add the babysit-pr, file-pr, full-send, full-stop, leaving-pr-comments, orchestrate and sol-loop skills, patch jj for copy-on-write checkouts, and update agent-linear. Remove the workspaces package and the maintain-it skill. Keep origin's newer shale-issues skill over the local deletion. Assisted-by: claude-sonnet-5.5 Assisted-by: gpt-6.1-sol Assisted-by: gpt-6.1-terra --- flake.nix | 7 + .../jujutsu/copy-on-write-checkouts.patch | 828 +++++++++++++++ users/clover/agents/AGENTS.md | 33 +- users/clover/agents/skills/README.md | 65 -- .../clover/agents/skills/babysit-pr/SKILL.md | 117 +++ .../agents/skills/babysit-pr/scripts/pr-wait | 556 ++++++++++ users/clover/agents/skills/cold-read/SKILL.md | 112 ++ users/clover/agents/skills/file-pr/SKILL.md | 85 ++ users/clover/agents/skills/full-send/SKILL.md | 124 +++ users/clover/agents/skills/full-stop/SKILL.md | 48 + .../skills/full-stop/agents/openai.yaml | 4 + .../skills/leaving-pr-comments/SKILL.md | 138 +++ .../clover/agents/skills/maintain-it/SKILL.md | 247 ----- .../skills/maintain-it/references/gate.md | 45 - .../skills/maintain-it/references/release.md | 54 - .../maintain-it/references/state-file.md | 52 - .../AGENTS-orchestration-proposed.md | 39 + .../clover/agents/skills/orchestrate/NOTES.md | 36 + .../clover/agents/skills/orchestrate/SKILL.md | 380 +++++++ .../skills/orchestrate/references/accounts.md | 24 + .../skills/orchestrate/references/brief.md | 79 ++ .../skills/orchestrate/references/casebook.md | 132 +++ .../skills/orchestrate/references/jj.md | 76 ++ .../references/safety-checklist.md | 50 + users/clover/agents/skills/sol-loop/SKILL.md | 119 +++ .../agents/skills/ui-review-loop/SKILL.md | 2 +- users/clover/home.nix | 34 +- users/clover/jujutsu.nix | 10 + .../packages/agent-linear/agent-linear.js | 23 +- .../agent-linear/agent-linear.test.cjs | 125 +++ users/clover/packages/workspaces/README.md | 100 -- .../packages/workspaces/configure-hooks.py | 103 -- users/clover/packages/workspaces/default.nix | 29 - .../workspaces/extension/extension.js | 33 - .../workspaces/extension/package.json | 12 - users/clover/packages/workspaces/native.c | 39 - users/clover/packages/workspaces/shell.zsh | 15 - .../workspaces/workspaces-hooks.test.mjs | 144 --- .../clover/packages/workspaces/workspaces.mjs | 992 ------------------ .../packages/workspaces/workspaces.test.mjs | 834 --------------- users/clover/work/home.nix | 51 +- users/clover/zsh/init.zsh | 51 +- 42 files changed, 3214 insertions(+), 2833 deletions(-) create mode 100644 packages/jujutsu/copy-on-write-checkouts.patch delete mode 100644 users/clover/agents/skills/README.md create mode 100644 users/clover/agents/skills/babysit-pr/SKILL.md create mode 100755 users/clover/agents/skills/babysit-pr/scripts/pr-wait create mode 100644 users/clover/agents/skills/cold-read/SKILL.md create mode 100644 users/clover/agents/skills/file-pr/SKILL.md create mode 100644 users/clover/agents/skills/full-send/SKILL.md create mode 100644 users/clover/agents/skills/full-stop/SKILL.md create mode 100644 users/clover/agents/skills/full-stop/agents/openai.yaml create mode 100644 users/clover/agents/skills/leaving-pr-comments/SKILL.md delete mode 100644 users/clover/agents/skills/maintain-it/SKILL.md delete mode 100644 users/clover/agents/skills/maintain-it/references/gate.md delete mode 100644 users/clover/agents/skills/maintain-it/references/release.md delete mode 100644 users/clover/agents/skills/maintain-it/references/state-file.md create mode 100644 users/clover/agents/skills/orchestrate/AGENTS-orchestration-proposed.md create mode 100644 users/clover/agents/skills/orchestrate/NOTES.md create mode 100644 users/clover/agents/skills/orchestrate/SKILL.md create mode 100644 users/clover/agents/skills/orchestrate/references/accounts.md create mode 100644 users/clover/agents/skills/orchestrate/references/brief.md create mode 100644 users/clover/agents/skills/orchestrate/references/casebook.md create mode 100644 users/clover/agents/skills/orchestrate/references/jj.md create mode 100644 users/clover/agents/skills/orchestrate/references/safety-checklist.md create mode 100644 users/clover/agents/skills/sol-loop/SKILL.md create mode 100644 users/clover/packages/agent-linear/agent-linear.test.cjs delete mode 100644 users/clover/packages/workspaces/README.md delete mode 100644 users/clover/packages/workspaces/configure-hooks.py delete mode 100644 users/clover/packages/workspaces/default.nix delete mode 100644 users/clover/packages/workspaces/extension/extension.js delete mode 100644 users/clover/packages/workspaces/extension/package.json delete mode 100644 users/clover/packages/workspaces/native.c delete mode 100644 users/clover/packages/workspaces/shell.zsh delete mode 100644 users/clover/packages/workspaces/workspaces-hooks.test.mjs delete mode 100644 users/clover/packages/workspaces/workspaces.mjs delete mode 100644 users/clover/packages/workspaces/workspaces.test.mjs diff --git a/flake.nix b/flake.nix index 2969edcd8e464dd58a20a5609b25e01d4d8ef3e5..c9fe680496114a15a2724f12ef6df40471610a30 100644 --- a/flake.nix +++ b/flake.nix @@ -75,6 +75,13 @@ }); }) + # Copy-on-write checkouts; exported from ~/dev/jj change trunyqzm. + (_: prev: { + jujutsu = prev.jujutsu.overrideAttrs (old: { + patches = old.patches or [ ] ++ [ ./packages/jujutsu/copy-on-write-checkouts.patch ]; + }); + }) + # custom packages (_: pkgs: { autofmt = pkgs.callPackage ./packages/autofmt { }; diff --git a/packages/jujutsu/copy-on-write-checkouts.patch b/packages/jujutsu/copy-on-write-checkouts.patch new file mode 100644 index 0000000000000000000000000000000000000000..75dfd0d5398e1c77be77818c7d372d69efc086a8 --- /dev/null +++ b/packages/jujutsu/copy-on-write-checkouts.patch @@ -0,0 +1,828 @@ +diff --git a/lib/src/eol.rs b/lib/src/eol.rs +index bfb111d3de..5eacfa4133 100644 +--- a/lib/src/eol.rs ++++ b/lib/src/eol.rs +@@ -49,6 +49,11 @@ + } + } + ++ /// Whether [`Self::convert_eol_for_update()`] can change file content. ++ pub(crate) fn converts_on_update(&self) -> bool { ++ self.eol_conversion_mode == EolConversionMode::InputOutput ++ } ++ + /// The limit to probe for whether the file is binary is 8KB. + /// All files strictly smaller than the limit are always + /// evaluated correctly and in full. +diff --git a/lib/src/file_cache.rs b/lib/src/file_cache.rs +new file mode 100644 +index 0000000000..be03d9ca74 +--- /dev/null ++++ b/lib/src/file_cache.rs +@@ -0,0 +1,169 @@ ++// Copyright 2026 The Jujutsu Authors ++// ++// Licensed under the Apache License, Version 2.0 (the "License"); ++// you may not use this file except in compliance with the License. ++// You may obtain a copy of the License at ++// ++// https://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, software ++// distributed under the License is distributed on an "AS IS" BASIS, ++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++// See the License for the specific language governing permissions and ++// limitations under the License. ++ ++//! Content-addressed cache of materialized files, which checkouts clone ++//! instead of rewriting. ++ ++use std::collections::HashMap; ++use std::fs; ++use std::fs::File; ++use std::io; ++use std::io::Seek as _; ++use std::path::Path; ++use std::path::PathBuf; ++ ++use futures::AsyncRead; ++use tempfile::TempPath; ++ ++use crate::file_util::copy_async_to_sync; ++ ++/// Cache entries for one checkout. Entries it adds stay pending until ++/// [`Self::commit()`] makes them durable with a single device flush, as Git's ++/// `core.fsyncMethod=batch` does. ++pub(crate) struct FileCache { ++ dir: PathBuf, ++ pending: HashMap, ++} ++ ++impl FileCache { ++ /// Opens the cache of the repo at `repo_path`. Returns `None` where files ++ /// can't be cloned. ++ pub fn open(repo_path: &Path) -> Option { ++ let dir = repo_path.join("file_cache"); ++ let supported = cfg!(target_vendor = "apple") && fs::create_dir_all(&dir).is_ok(); ++ supported.then(|| Self { ++ dir, ++ pending: HashMap::new(), ++ }) ++ } ++ ++ /// Opens the entry `name`, adding it from `contents` if missing. ++ pub async fn entry(&mut self, name: String, contents: impl AsyncRead) -> io::Result { ++ let path = match self.pending.get(&name) { ++ Some(temp_path) => temp_path.to_path_buf(), ++ None => self.dir.join(&name), ++ }; ++ match File::open(path) { ++ Err(err) if err.kind() == io::ErrorKind::NotFound => {} ++ result => return result, ++ } ++ ++ let mut temp_file = platform::new_entry(&self.dir)?; ++ copy_async_to_sync(contents, temp_file.as_file_mut()).await?; ++ platform::write_out(temp_file.as_file())?; ++ let (mut file, temp_path) = temp_file.into_parts(); ++ file.rewind()?; ++ self.pending.insert(name, temp_path); ++ Ok(file) ++ } ++ ++ /// Publishes pending entries once they are durable. ++ pub fn commit(self) -> io::Result<()> { ++ if self.pending.is_empty() { ++ return Ok(()); ++ } ++ platform::flush_device(&File::open(&self.dir)?)?; ++ for (name, temp_path) in self.pending { ++ temp_path.persist(self.dir.join(name))?; ++ } ++ Ok(()) ++ } ++} ++ ++pub(crate) use platform::clone_dir; ++pub(crate) use platform::clone_file; ++ ++#[cfg(target_vendor = "apple")] ++mod platform { ++ use std::fs::File; ++ use std::fs::Permissions; ++ use std::io; ++ use std::os::unix::fs::PermissionsExt as _; ++ use std::path::Path; ++ ++ use rustix::fs::CloneFlags; ++ use rustix::fs::Mode; ++ use rustix::fs::OFlags; ++ use tempfile::NamedTempFile; ++ ++ /// Creates a temporary entry with the mode of a checked-out file, so ++ /// clones of it need no `chmod`. ++ pub fn new_entry(dir: &Path) -> io::Result { ++ tempfile::Builder::new() ++ .permissions(Permissions::from_mode(0o644)) ++ .tempfile_in(dir) ++ } ++ ++ /// Creates `dst` as a copy-on-write clone of `src`, failing if `dst` ++ /// exists. The clone keeps the mode and mtime of `src`. ++ pub fn clone_file(src: &File, dst: &Path) -> io::Result<()> { ++ Ok(rustix::fs::fclonefileat( ++ src, ++ rustix::fs::CWD, ++ dst, ++ CloneFlags::empty(), ++ )?) ++ } ++ ++ /// Like [`clone_file()`], but clones the directory hierarchy at `src` ++ /// without following a symlink there. ++ pub fn clone_dir(src: &Path, dst: &Path) -> io::Result<()> { ++ let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW; ++ let src = rustix::fs::open(src, flags, Mode::empty())?; ++ Ok(rustix::fs::fclonefileat( ++ src, ++ rustix::fs::CWD, ++ dst, ++ CloneFlags::empty(), ++ )?) ++ } ++ ++ /// Writes `file` to the device, but not through the device's own cache. ++ pub fn write_out(file: &File) -> io::Result<()> { ++ Ok(rustix::fs::fsync(file)?) ++ } ++ ++ pub fn flush_device(file: &File) -> io::Result<()> { ++ Ok(rustix::fs::fcntl_fullfsync(file)?) ++ } ++} ++ ++#[cfg(not(target_vendor = "apple"))] ++mod platform { ++ use std::fs::File; ++ use std::io; ++ use std::path::Path; ++ ++ use tempfile::NamedTempFile; ++ ++ pub fn new_entry(dir: &Path) -> io::Result { ++ NamedTempFile::new_in(dir) ++ } ++ ++ pub fn clone_file(_src: &File, _dst: &Path) -> io::Result<()> { ++ Err(io::ErrorKind::Unsupported.into()) ++ } ++ ++ pub fn clone_dir(_src: &Path, _dst: &Path) -> io::Result<()> { ++ Err(io::ErrorKind::Unsupported.into()) ++ } ++ ++ pub fn write_out(file: &File) -> io::Result<()> { ++ file.sync_data() ++ } ++ ++ pub fn flush_device(file: &File) -> io::Result<()> { ++ file.sync_all() ++ } ++} +diff --git a/lib/src/lib.rs b/lib/src/lib.rs +index c97831a80a..8466d009d1 100644 +--- a/lib/src/lib.rs ++++ b/lib/src/lib.rs +@@ -49,6 +49,7 @@ + pub(crate) mod eol; + pub mod evolution; + pub mod extensions_map; ++mod file_cache; + pub mod file_util; + pub mod files; + pub mod fileset; +diff --git a/lib/src/local_working_copy.rs b/lib/src/local_working_copy.rs +index d7da1716fc..7c1294ff6f 100644 +--- a/lib/src/local_working_copy.rs ++++ b/lib/src/local_working_copy.rs +@@ -53,6 +53,7 @@ + use pollster::FutureExt as _; + use prost::Message as _; + use rayon::iter::IntoParallelIterator as _; ++use rayon::iter::IntoParallelRefIterator as _; + use rayon::prelude::IndexedParallelIterator as _; + use rayon::prelude::ParallelIterator as _; + use tempfile::NamedTempFile; +@@ -80,6 +81,9 @@ + use crate::conflicts::materialize_tree_value; + pub use crate::eol::EolConversionMode; + use crate::eol::TargetEolStrategy; ++use crate::file_cache::FileCache; ++use crate::file_cache::clone_dir; ++use crate::file_cache::clone_file; + use crate::file_util::FileIdentity; + use crate::file_util::check_symlink_support; + use crate::file_util::copy_async_to_sync; +@@ -99,6 +103,7 @@ + use crate::matchers::Matcher; + use crate::matchers::PrefixMatcher; + use crate::matchers::UnionMatcher; ++use crate::matchers::Visit; + use crate::merge::Merge; + use crate::merge::MergeBuilder; + use crate::merge::MergedTreeValue; +@@ -127,6 +132,7 @@ + use crate::working_copy::WorkingCopy; + use crate::working_copy::WorkingCopyFactory; + use crate::working_copy::WorkingCopyStateError; ++use crate::workspace_store::SimpleWorkspaceStore; + + fn symlink_target_convert_to_store(path: &Path) -> Option> { + let path = path.to_str()?; +@@ -818,6 +824,14 @@ + + const RESERVED_DIR_NAMES: &[&str] = &[".git", ".jj"]; + ++/// Smaller files are written directly, since cloning a file costs more than ++/// writing a few blocks. ++const MIN_CACHED_FILE_SIZE: u64 = 16 << 10; ++ ++/// Untracked directories that tend to be huge, so their parents are never ++/// cloned from a sibling workspace whole. ++const UNCLONED_DIR_NAMES: &[&str] = &["node_modules", "target"]; ++ + fn file_identity_from_symlink_path(disk_path: &Path) -> io::Result> { + match FileIdentity::from_symlink_path(disk_path) { + Ok(identity) => Ok(Some(identity)), +@@ -2071,6 +2085,82 @@ + .map_err(|err| checkout_error_for_mtime_out_of_range(err, disk_path)) + } + ++ /// Like [`Self::write_file()`], but clones `disk_path` from `file_cache` ++ /// if the content is large enough to be worth it. Drops `file_cache` and ++ /// copies instead if the file system can't clone. `fresh` means the ++ /// working copy held nothing before this checkout. ++ async fn write_cached_file( ++ &self, ++ disk_path: &Path, ++ id: &FileId, ++ contents: impl AsyncRead + Send + Unpin, ++ exec_bit: ExecBit, ++ file_cache: &mut Option, ++ fresh: bool, ++ ) -> Result { ++ let Some(cache) = file_cache else { ++ return self.write_file(disk_path, contents, exec_bit, true).await; ++ }; ++ ++ let mut contents = self ++ .target_eol_strategy ++ .convert_eol_for_update(contents) ++ .await ++ .map_err(|err| CheckoutError::Other { ++ message: "Failed to convert the EOL for the content".to_string(), ++ err: err.into(), ++ })?; ++ let mut head = Vec::new(); ++ futures::AsyncReadExt::take(&mut contents, MIN_CACHED_FILE_SIZE) ++ .read_to_end(&mut head) ++ .await ++ .map_err(|err| CheckoutError::Other { ++ message: format!("Failed to read the content for {}", disk_path.display()), ++ err: err.into(), ++ })?; ++ let is_small = (head.len() as u64) < MIN_CACHED_FILE_SIZE; ++ let contents = futures::AsyncReadExt::chain(head.as_slice(), contents); ++ if is_small { ++ return self.write_file(disk_path, contents, exec_bit, false).await; ++ } ++ ++ let entry_name = if self.target_eol_strategy.converts_on_update() { ++ format!("{}.crlf", id.hex()) ++ } else { ++ id.hex() ++ }; ++ let entry = ++ cache ++ .entry(entry_name, contents) ++ .await ++ .map_err(|err| CheckoutError::Other { ++ message: format!("Failed to cache {}", disk_path.display()), ++ err: err.into(), ++ })?; ++ // A clone keeps the entry's mtime, which would look stale to build tools ++ // unless nothing in the working copy predates this checkout. ++ if !fresh { ++ entry ++ .set_modified(SystemTime::now()) ++ .map_err(|err| checkout_error_for_stat_error(err, disk_path))?; ++ } ++ let metadata = entry ++ .metadata() ++ .map_err(|err| checkout_error_for_stat_error(err, disk_path))?; ++ if clone_file(&entry, disk_path).is_err() { ++ *file_cache = None; ++ return self ++ .write_file(disk_path, AllowStdIo::new(entry), exec_bit, false) ++ .await; ++ } ++ if exec_bit.0 { ++ set_executable(exec_bit, disk_path) ++ .map_err(|err| checkout_error_for_stat_error(err, disk_path))?; ++ } ++ FileState::for_file(exec_bit, metadata.len(), &metadata) ++ .map_err(|err| checkout_error_for_mtime_out_of_range(err, disk_path)) ++ } ++ + fn write_symlink(&self, disk_path: &Path, target: String) -> Result { + let target = symlink_target_convert_to_disk(&target); + +@@ -2183,6 +2273,180 @@ + }) + } + ++ /// Loads the tree state of the sibling workspace whose tree differs least ++ /// from `new_tree`, along with the paths that differ. ++ async fn closest_sibling(&self, new_tree: &MergedTree) -> Option<(Self, HashSet)> { ++ let workspace_paths = SimpleWorkspaceStore::load(self.store.repo_path()) ++ .and_then(|store| store.workspace_paths()) ++ .ok()?; ++ let own_path = dunce::canonicalize(&self.working_copy_path).ok()?; ++ let settings = TreeStateSettings { ++ conflict_marker_style: self.conflict_marker_style, ++ eol_conversion_mode: EolConversionMode::None, ++ exec_change_setting: ExecChangeSetting::Auto, ++ fsmonitor_settings: FsmonitorSettings::None, ++ }; ++ ++ let mut closest: Option<(Self, HashSet)> = None; ++ for path in workspace_paths { ++ let state_path = path.join(".jj").join("working_copy"); ++ // Loading a missing tree state would create one in the sibling. ++ if !state_path.join("tree_state").is_file() ++ || dunce::canonicalize(&path).is_ok_and(|path| path == own_path) ++ { ++ continue; ++ } ++ let Ok(sibling) = Self::load(self.store.clone(), path, state_path, &settings) else { ++ continue; ++ }; ++ if sibling.sparse_patterns != [RepoPathBuf::root()] { ++ continue; ++ } ++ let limit = closest ++ .as_ref() ++ .map_or(usize::MAX, |(_, paths)| paths.len()); ++ let differing_paths: HashSet = sibling ++ .tree ++ .diff_stream(new_tree, &EverythingMatcher) ++ .map(|entry| entry.path) ++ .take(limit) ++ .collect() ++ .await; ++ if differing_paths.len() < limit { ++ closest = Some((sibling, differing_paths)); ++ } ++ } ++ closest ++ } ++ ++ /// Seeds a fresh working copy with directories cloned from the sibling ++ /// workspace closest to `new_tree`, then keeps only the cloned files whose ++ /// content the sibling's tree state vouches for. Returns their states. ++ async fn seed_from_sibling( ++ &self, ++ new_tree: &MergedTree, ++ matcher: &dyn Matcher, ++ ) -> Result, CheckoutError> { ++ let Some((sibling, differing_paths)) = self.closest_sibling(new_tree).await else { ++ return Ok(vec![]); ++ }; ++ let sibling_states = sibling.file_states(); ++ ++ let mut tracked_dirs: HashSet<&RepoPath> = HashSet::new(); ++ for path in sibling_states.paths() { ++ for dir in path.ancestors().skip(1) { ++ if !tracked_dirs.insert(dir) { ++ break; ++ } ++ } ++ } ++ let mut child_dirs: HashMap<&RepoPath, Vec<&RepoPath>> = HashMap::new(); ++ for &dir in &tracked_dirs { ++ if let Some(parent) = dir.parent() { ++ child_dirs.entry(parent).or_default().push(dir); ++ } ++ } ++ let dirs_holding_uncloned: Vec<&RepoPath> = tracked_dirs ++ .par_iter() ++ .copied() ++ .filter(|dir| { ++ let disk_dir = dir.to_fs_path_unchecked(&sibling.working_copy_path); ++ UNCLONED_DIR_NAMES.iter().any(|&name| { ++ let child = dir.join(RepoPathComponent::new(name).unwrap()); ++ !tracked_dirs.contains(&*child) ++ && disk_dir.join(name).symlink_metadata().is_ok() ++ }) ++ }) ++ .collect(); ++ let split_dirs: HashSet<&RepoPath> = dirs_holding_uncloned ++ .into_iter() ++ .chain(differing_paths.iter().filter_map(|path| path.parent())) ++ .flat_map(RepoPath::ancestors) ++ .collect(); ++ ++ // Never the root, which holds .jj and usually build output. ++ let mut clone_roots = vec![]; ++ let mut dirs_to_split = vec![RepoPath::root()]; ++ while let Some(dir) = dirs_to_split.pop() { ++ for &child in child_dirs.get(dir).into_iter().flatten() { ++ if !split_dirs.contains(child) && matcher.visit(child) == Visit::AllRecursively { ++ clone_roots.push(child); ++ } else { ++ dirs_to_split.push(child); ++ } ++ } ++ } ++ ++ // Clone roots hold the same tree in both workspaces, so a file is ++ // vouched for if the sibling would see it as unchanged. ++ let vouched_state = |path: &RepoPath, metadata: &Metadata| { ++ let old_state = sibling_states.get(path)?; ++ let new_state = file_state(metadata).ok()??; ++ let clean = old_state.materialized_conflict_data.is_none() ++ && new_state.is_clean(&old_state) ++ && old_state.mtime < sibling.own_mtime; ++ clean.then_some(new_state) ++ }; ++ let seed = |root: &RepoPath| -> Result, CheckoutError> { ++ let disk_root = root.to_fs_path(&self.working_copy_path)?; ++ let created_parent = fs::create_dir_all(disk_root.parent().unwrap()); ++ let source = root.to_fs_path(&sibling.working_copy_path)?; ++ if created_parent ++ .and_then(|()| clone_dir(&source, &disk_root)) ++ .is_err() ++ { ++ fs::remove_dir_all(&disk_root).ok(); ++ return Ok(vec![]); ++ } ++ ++ let mut seeded = vec![]; ++ let mut dirs_to_walk = vec![root.to_owned()]; ++ while let Some(dir) = dirs_to_walk.pop() { ++ let disk_dir = dir.to_fs_path(&self.working_copy_path)?; ++ let entries = fs::read_dir(&disk_dir) ++ .map_err(|err| checkout_error_for_stat_error(err, &disk_dir))?; ++ for entry in entries { ++ let entry = ++ entry.map_err(|err| checkout_error_for_stat_error(err, &disk_dir))?; ++ let disk_path = entry.path(); ++ let metadata = entry ++ .metadata() ++ .map_err(|err| checkout_error_for_stat_error(err, &disk_path))?; ++ let path = entry ++ .file_name() ++ .to_str() ++ .and_then(|name| RepoPathComponent::new(name).ok()) ++ .map(|name| dir.join(name)); ++ let removed = match path { ++ Some(path) if metadata.is_dir() && tracked_dirs.contains(&*path) => { ++ dirs_to_walk.push(path); ++ Ok(()) ++ } ++ _ if metadata.is_dir() => fs::remove_dir_all(&disk_path), ++ Some(path) => match vouched_state(&path, &metadata) { ++ Some(state) => { ++ seeded.push((path, state)); ++ Ok(()) ++ } ++ None => fs::remove_file(&disk_path), ++ }, ++ None => fs::remove_file(&disk_path), ++ }; ++ removed.map_err(|err| CheckoutError::Other { ++ message: format!("Failed to remove {}", disk_path.display()), ++ err: err.into(), ++ })?; ++ } ++ } ++ Ok(seeded) ++ }; ++ let seeded: Vec> = clone_roots ++ .into_par_iter() ++ .map(seed) ++ .collect::>()?; ++ Ok(seeded.into_iter().flatten().collect()) ++ } ++ + async fn update( + &mut self, + old_tree: &MergedTree, +@@ -2200,6 +2464,22 @@ + let mut changed_file_states = Vec::new(); + let mut deleted_files = HashSet::new(); + let mut prev_created_path: RepoPathBuf = RepoPathBuf::root(); ++ let mut file_cache = FileCache::open(self.store.repo_path()); ++ let fresh = *old_tree.tree_ids() == self.store.empty_merged_tree_id() ++ && fs::read_dir(&self.working_copy_path).is_ok_and(|mut entries| { ++ entries.all(|entry| entry.is_ok_and(|entry| entry.file_name() == ".jj")) ++ }); ++ let seeded = if fresh ++ && file_cache.is_some() ++ && *new_tree.tree_ids() != self.store.empty_merged_tree_id() ++ && !self.target_eol_strategy.converts_on_update() ++ { ++ self.seed_from_sibling(new_tree, matcher).await? ++ } else { ++ vec![] ++ }; ++ let seeded_matcher = FilesMatcher::new(seeded.iter().map(|(path, _)| path)); ++ let matcher: &dyn Matcher = &DifferenceMatcher::new(matcher, &seeded_matcher); + + let mut process_diff_entry = async |path: RepoPathBuf, + before: MergedTreeValue, +@@ -2336,8 +2616,15 @@ + MaterializedTreeValue::File(file) => { + let exec_bit = + ExecBit::new_from_repo(file.executable, self.exec_policy, get_prev_exec); +- self.write_file(&disk_path, file.reader, exec_bit, true) +- .await? ++ self.write_cached_file( ++ &disk_path, ++ &file.id, ++ file.reader, ++ exec_bit, ++ &mut file_cache, ++ fresh, ++ ) ++ .await? + } + MaterializedTreeValue::Symlink { id: _, target } => { + if self.symlink_support { +@@ -2451,6 +2738,16 @@ + changed_file_states.sort_unstable_by(|(path1, _), (path2, _)| path1.cmp(path2)); + } + ++ if !seeded.is_empty() { ++ stats.added_files += u32::try_from(seeded.len()).unwrap(); ++ changed_file_states.extend(seeded); ++ changed_file_states.sort_unstable_by(|(path1, _), (path2, _)| path1.cmp(path2)); ++ } ++ ++ // The files are in place; a cache that fails to update only costs speed. ++ if let Some(file_cache) = file_cache { ++ file_cache.commit().ok(); ++ } + self.file_states + .merge_in(changed_file_states, &deleted_files); + Ok(stats) +diff --git a/lib/src/repo.rs b/lib/src/repo.rs +index 61e5a6e093..b69a8ae85f 100644 +--- a/lib/src/repo.rs ++++ b/lib/src/repo.rs +@@ -223,7 +223,7 @@ + fs::write(&backend_path, backend.name()).context(&backend_path)?; + let merge_options = + MergeOptions::from_settings(settings).map_err(|err| BackendInitError(err.into()))?; +- let store = Store::new(backend, signer, merge_options); ++ let store = Store::new(backend, signer, merge_options, repo_path.clone()); + + let op_store_path = repo_path.join("op_store"); + fs::create_dir(&op_store_path).context(&op_store_path)?; +@@ -711,6 +711,7 @@ + store_factories.load_backend(settings, &repo_path.join("store"))?, + Signer::from_settings(settings)?, + merge_options, ++ repo_path.to_owned(), + ); + let root_op_data = RootOperationData { + root_commit_id: store.root_commit_id().clone(), +diff --git a/lib/src/store.rs b/lib/src/store.rs +index 813d1eef87..e812b6b701 100644 +--- a/lib/src/store.rs ++++ b/lib/src/store.rs +@@ -16,6 +16,8 @@ + + use std::fmt::Debug; + use std::fmt::Formatter; ++use std::path::Path; ++use std::path::PathBuf; + use std::pin::Pin; + use std::sync::Arc; + use std::sync::Mutex; +@@ -59,6 +61,7 @@ + commit_cache: Mutex>>, + tree_cache: Mutex>>, + merge_options: MergeOptions, ++ repo_path: PathBuf, + } + + impl Debug for Store { +@@ -74,6 +77,7 @@ + backend: Box, + signer: Signer, + merge_options: MergeOptions, ++ repo_path: PathBuf, + ) -> Arc { + Arc::new(Self { + backend, +@@ -81,6 +85,7 @@ + commit_cache: Mutex::new(CLruCache::new(COMMIT_CACHE_CAPACITY.try_into().unwrap())), + tree_cache: Mutex::new(CLruCache::new(TREE_CACHE_CAPACITY.try_into().unwrap())), + merge_options, ++ repo_path, + }) + } + +@@ -102,6 +107,11 @@ + &self.merge_options + } + ++ /// The repo directory, which holds state shared by its workspaces. ++ pub fn repo_path(&self) -> &Path { ++ &self.repo_path ++ } ++ + pub fn get_copy_records( + &self, + paths: Option<&[RepoPathBuf]>, +diff --git a/lib/src/workspace_store.rs b/lib/src/workspace_store.rs +index 32e6072b4b..a5ad1bf614 100644 +--- a/lib/src/workspace_store.rs ++++ b/lib/src/workspace_store.rs +@@ -127,6 +127,18 @@ + Ok(store) + } + ++ /// Returns the paths of all registered workspaces. ++ pub fn workspace_paths(&self) -> Result, WorkspaceStoreError> { ++ let paths = self ++ .read_store()? ++ .workspaces ++ .iter() ++ .map(|w| path_from_bytes(&w.path).map(|path| self.repo_path.join(path))) ++ .collect::>() ++ .map_err(SimpleWorkspaceStoreError::BadPathEncoding)?; ++ Ok(paths) ++ } ++ + fn lock(&self) -> Result { + Ok(FileLock::lock(self.lock_file.clone())?) + } +diff --git a/lib/tests/test_local_working_copy.rs b/lib/tests/test_local_working_copy.rs +index 55aaffd9c9..00a12f87bc 100644 +--- a/lib/tests/test_local_working_copy.rs ++++ b/lib/tests/test_local_working_copy.rs +@@ -51,8 +51,10 @@ + use jj_lib::merge::SameChange; + use jj_lib::merged_tree::MergedTree; + use jj_lib::merged_tree_builder::MergedTreeBuilder; ++use jj_lib::object_id::ObjectId as _; + use jj_lib::op_store::OperationId; + use jj_lib::ref_name::WorkspaceName; ++use jj_lib::ref_name::WorkspaceNameBuf; + use jj_lib::repo::ReadonlyRepo; + use jj_lib::repo::Repo as _; + use jj_lib::repo_path::RepoPath; +@@ -68,6 +70,7 @@ + use jj_lib::working_copy::WorkingCopy as _; + use jj_lib::workspace::Workspace; + use jj_lib::workspace::default_working_copy_factories; ++use jj_lib::workspace::default_working_copy_factory; + use pollster::FutureExt as _; + use test_case::test_case; + use testutils::CommitBuilderExt as _; +@@ -84,6 +87,7 @@ + use testutils::repo_path_buf; + use testutils::repo_path_component; + use testutils::write_random_commit; ++use testutils::write_working_copy_file; + + fn check_icase_fs(dir: &Path) -> bool { + let test_file = tempfile::Builder::new() +@@ -822,6 +826,125 @@ + } + + #[test] ++fn test_checkout_clones_large_files_from_file_cache() -> TestResult { ++ // Edits to a cloned file must not reach the cache entry or later checkouts. ++ let mut test_workspace = TestWorkspace::init(); ++ let repo = test_workspace.repo.clone(); ++ let workspace_root = test_workspace.workspace.workspace_root().to_owned(); ++ let cache_dir = repo.store().repo_path().join("file_cache"); ++ let clones = cfg!(target_vendor = "apple"); ++ ++ let large_path = repo_path("large"); ++ let small_path = repo_path("small"); ++ let large_contents = "large\n".repeat(16 << 10); ++ let tree = create_tree( ++ &repo, ++ &[(large_path, &large_contents), (small_path, "small")], ++ ); ++ let commit = commit_with_tree(repo.store(), tree.clone()); ++ let Ok(Some(TreeValue::File { id: large_id, .. })) = ++ tree.path_value(large_path).block_on()?.into_resolved() ++ else { ++ panic!("large file should be resolved"); ++ }; ++ let entry_path = cache_dir.join(large_id.hex()); ++ let large_disk_path = large_path.to_fs_path_unchecked(&workspace_root); ++ ++ test_workspace ++ .workspace ++ .check_out(repo.op_id().clone(), None, &commit) ++ .block_on()?; ++ assert_eq!(std::fs::read_to_string(&large_disk_path)?, large_contents); ++ if clones { ++ assert_eq!(std::fs::read_to_string(&entry_path)?, large_contents); ++ assert_eq!(std::fs::read_dir(&cache_dir)?.count(), 1); ++ } else { ++ assert!(!cache_dir.exists()); ++ } ++ ++ write_working_copy_file(&workspace_root, large_path, "edited"); ++ assert_ne!(test_workspace.snapshot()?.tree_ids(), tree.tree_ids()); ++ if clones { ++ assert_eq!(std::fs::read_to_string(&entry_path)?, large_contents); ++ File::open(&entry_path)?.set_modified(SystemTime::UNIX_EPOCH)?; ++ } ++ ++ test_workspace ++ .workspace ++ .check_out(repo.op_id().clone(), None, &commit) ++ .block_on()?; ++ assert_eq!(std::fs::read_to_string(&large_disk_path)?, large_contents); ++ let age = SystemTime::now().duration_since(large_disk_path.metadata()?.modified()?); ++ assert!(age.is_ok_and(|age| age < Duration::from_secs(60))); ++ assert_eq!(test_workspace.snapshot()?.tree_ids(), tree.tree_ids()); ++ Ok(()) ++} ++ ++#[test] ++fn test_checkout_fresh_workspace_seeds_from_sibling() -> TestResult { ++ // Unchanged directories come from the sibling, but not its unsnapshotted ++ // edits, untracked files, or node_modules. ++ let mut test_workspace = TestWorkspace::init(); ++ let repo = test_workspace.repo.clone(); ++ let root1 = test_workspace.workspace.workspace_root().to_owned(); ++ let tree = create_tree( ++ &repo, ++ &[ ++ (repo_path("dir/clean"), "clean"), ++ (repo_path("dir/edited"), "original"), ++ (repo_path("pkg/src/lib"), "lib"), ++ (repo_path("top"), "top"), ++ ], ++ ); ++ let commit = commit_with_tree(repo.store(), tree.clone()); ++ test_workspace ++ .workspace ++ .check_out(repo.op_id().clone(), None, &commit) ++ .block_on()?; ++ // Re-save the tree state so no file is racily clean. ++ std::thread::sleep(Duration::from_millis(10)); ++ test_workspace.snapshot()?; ++ std::fs::write(root1.join("dir/edited"), "edited")?; ++ std::fs::write(root1.join("dir/untracked"), "untracked")?; ++ std::fs::create_dir_all(root1.join("pkg/node_modules/dep"))?; ++ std::fs::write(root1.join("pkg/node_modules/dep/index.js"), "dep")?; ++ ++ let root2 = test_workspace.root_dir().join("ws2_root"); ++ std::fs::create_dir(&root2)?; ++ let (mut ws2, repo) = Workspace::init_workspace_with_existing_repo( ++ &root2, ++ test_workspace.repo_path(), ++ &repo, ++ &*default_working_copy_factory(), ++ WorkspaceNameBuf::from("ws2"), ++ ) ++ .block_on()?; ++ ws2.check_out(repo.op_id().clone(), None, &commit) ++ .block_on()?; ++ ++ assert_eq!(std::fs::read_to_string(root2.join("dir/clean"))?, "clean"); ++ assert_eq!( ++ std::fs::read_to_string(root2.join("dir/edited"))?, ++ "original" ++ ); ++ assert_eq!(std::fs::read_to_string(root2.join("pkg/src/lib"))?, "lib"); ++ assert!(!root2.join("dir/untracked").exists()); ++ assert!(!root2.join("pkg/node_modules").exists()); ++ let mtime = |path: PathBuf| path.metadata().and_then(|metadata| metadata.modified()); ++ let seeded = cfg!(target_vendor = "apple"); ++ for path in ["dir/clean", "pkg/src/lib"] { ++ assert_eq!(mtime(root2.join(path))? == mtime(root1.join(path))?, seeded); ++ } ++ let mut locked_ws = ws2.start_working_copy_mutation().block_on()?; ++ let (snapshot, _stats) = locked_ws ++ .locked_wc() ++ .snapshot(&empty_snapshot_options()) ++ .block_on()?; ++ assert_eq!(snapshot.tree_ids(), tree.tree_ids()); ++ Ok(()) ++} ++ ++#[test] + fn test_snapshot_file_directory_transition() -> TestResult { + let mut test_workspace = TestWorkspace::init(); + let repo = test_workspace.repo.clone(); diff --git a/users/clover/agents/AGENTS.md b/users/clover/agents/AGENTS.md index 0669ede99b3c1619554ba74056c58db724d20a6d..602b969879d8117bd67cce06e9c2d7669f1facfc 100644 --- a/users/clover/agents/AGENTS.md +++ b/users/clover/agents/AGENTS.md @@ -54,17 +54,24 @@ Keep an earned comment to a line, timeless, and rarely first person (no `I`, topology, and cross-file mechanism belong in the commit or the linked issue. Cut every clause a competent reader would already infer. +## alphaXiv + +I am testing a new patch for dev-tui. instead of starting it with pnpm dev run +`node ~/dev/dev-tui/boot.ts`. + ## Orchestration When asked to play orchestrator, you become a manager: the main thread holds the plan, which agent owns which files, and the integration seam; sub-agents hold the edits and the deep planning. Ignore this section when not explicitly asked -to be an orchestrator or the "Maintain It" skill. +to be an orchestrator. In that mode, these rules apply: -- After launching agents, omit launch commentary. Continue working or - wait_agent. Collect results, integrate, verify, and complete the authorized - task before ending the turn. Agent launch or completion alone is not a - stopping condition. +- After launching sub-agents, send no acknowledgement or recap. Keep the parent + run active and wait for results. +- Never send a final reply, including an empty one, while work required for this + request is pending. +- Review completed results, then report them. Surface questions needing my input + with their context. - The transcript is a record of work completed, never of work queued. A sub-agent starting and finishing already shows as its own item. Answer a question with zero output when work is queued and there is nothing to add. @@ -127,6 +134,20 @@ regret missing, never mere emphasis. Usually zero per message, never two. considered. One per message; pure negation earns no second clause. - You cannot judge visual taste. Ship screenshots and GIFs so I can. +## Cold Read + +Anything that leaves the thread -- a screenshot, chart, user-facing string, +error message, PR or commit body -- gets read by someone with no context before +it ships. Your own context fills every gap, so a self-check passes what I would +flag. Open the rendered artifact (the PNG, never the source), say what it shows, +and look for cut-off text, undefined terms, dead ends, and claims a reviewer +cannot judge. Anything past a one-liner goes to a fresh sub-agent that sees only +the artifact: use the `cold-read` skill. Fix findings before sending. + +A passing test or a clean screenshot script proves nothing about the image it +wrote. Never send or embed an image the same step that produced it; open it +first, every time. + ## Jujutsu - My repos use Jujutsu and usually don't have a visible `.git` folder. Never run @@ -170,6 +191,8 @@ regret missing, never mere emphasis. Usually zero per message, never two. models collaborate, be sure to credit all of them. - If the prompt mentions "ChatGPT Dot" or a task referred from a "Lilac" agent, add `Assisted-by: chatgpt-dot:lilac` as the last credit. +- Open every PR through the `file-pr` skill. PR bodies end in the same + `Assisted-by` trailers, never a "Generated with Claude Code" line. ## Personal diff --git a/users/clover/agents/skills/README.md b/users/clover/agents/skills/README.md deleted file mode 100644 index 6e198e9e41f0f1832e6dc5cf97233af881b29a5e..0000000000000000000000000000000000000000 --- a/users/clover/agents/skills/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# Skills for building apps with agents - -Eight skills for Claude Code and Codex, distilled from about 60 sessions in which -agents built three of Clover's apps: - -- **Snowbound**: a OneNote 2010 remake that one agent maintained for ten days; -- **Clover Chat**: a chat app whose clickable HTML prototype became the spec for - the real thing; -- **the snow globe**: a home-server dashboard. - -Quotes attributed to Clover are hers, kept for flavour and because they carry -the reasons. `ui-copy` quotes published design systems. - -| Skill | Use it for | -| --- | --- | -| `ui-copy` | Every word a person reads on screen | -| `ui-prototype` | A clickable HTML mock of the whole app before building the real UI, then building from it | -| `ux-flows` | How screens, menus, settings, onboarding and errors should behave | -| `ui-craft` | How it looks and moves: measured against the reference, nothing jumping | -| `ux-testing` | Finding problems the way a user would, before handing anything over | -| `accessibility` | Keyboard paths and the accessibility tree, tested without ever turning a screen reader on | -| `ui-review-loop` | Turning a batch of feedback into one round of fixes | -| `maintain-it` | Handing a solo repo to one agent that plans, ships to main, releases and keeps the tracker true | - -## Install - -Copy all eight folders into `~/.claude/skills/` for Claude Code, into -`~/.codex/skills/` for Codex, or into both. They refer to each other by name, -so install the set together. - -They work best with: - -- sub-agents; -- a tool for asking multiple-choice questions; -- a browser the agent can drive: the in-app browser, or Chrome plus Node 22 for - `ux-testing/scripts/drive.mjs`; -- for `maintain-it`, an issue tracker the agent can write to. - -## Your taste - -Taste is yours. Put it where agents read it, such as AGENTS.md, CLAUDE.md or -memory. Until you do, `ui-craft` uses Clover's taste as a worked example and -asks before leaning on it. - -## Prompting moves - -The skills make agents offer most of these. Asking for them directly gets you -there sooner. - -``` -start "mock this before we build it", plus a two-sentence pitch, the look to inherit, - 2–3 reference apps, and which surface is the hard custom one -answer the question round; free-text answers are followed literally -review use the mock-controls panel; send numbered screenshots with one-liners; - send small things as you go -name it "the way Discord does muting": naming the product that already solved it lands fastest -unstick "something's off" gets an A/B/C sheet; open-ended taste gets variants -before "run a fresh-eyes pass"; "sweep it" once nits pile up -handoff "match the mock literally", plus which sizes, fonts and materials are exact targets -maintain "you're the maintainer": then settle the contract it asks about (push, release, - tracker access, budget, what stays yours) -``` - -When a word could mean two things ("theme", "half", "tighter"), the agent is -supposed to restate it before building. If it doesn't, ask it to. diff --git a/users/clover/agents/skills/babysit-pr/SKILL.md b/users/clover/agents/skills/babysit-pr/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..7afd153f2b918b8768c895fe9dff0390da8d7d29 --- /dev/null +++ b/users/clover/agents/skills/babysit-pr/SKILL.md @@ -0,0 +1,117 @@ +--- +name: babysit-pr +description: Monitor a pull request through review and CI. Use when the user asks to monitor, watch, or babysit a PR. +--- + +# Babysit PR + +Many repos have AI review bots. They're helpful, even if they are not always +right. + +## Waiting + +Never write your own watcher, polling loop, or `sleep` loop. Use one watcher +per PR: `watch_pull_request` in T3 Code, `pr-wait` everywhere else. Never run +both on the same PR. Every watcher on a GitHub account shares one rate limit. + +### In T3 Code: `watch_pull_request` + +Handle the existing checks and comments first. Then call +`watch_pull_request` and end your turn. T3 Code wakes you with a message when +a check fails, the required checks pass, someone comments or reviews, or the +branch conflicts. + +- **Only the thread that owns the PR watches it.** If you are a delegated + child task (a reviewer, a Sol round, any `delegate_task` child), never call + `watch_pull_request`. The parent owns the PR. Do not watch PRs you are not + working on. +- **A wake is news, not a merge decision.** Check the merge gate yourself. +- **Unwatch when you hand off.** A watched thread stays in Working and out of + the user's inbox. When you stop (ready, blocked, or asking the user a question), + call `unwatch_pull_request` first. A merge or close ends the watch on its + own. +- **"Stopped watching, could not read it"** usually means GitHub's rate limit + is used up. Run `gh api rate_limit --jq .resources.graphql` before you + watch again. If `remaining` is near 0, wait for `reset` with one background + command, then watch again. Never watch again in a tight loop. + +### Everywhere else: `pr-wait` + +Wait with `scripts/pr-wait` from this skill's directory (use its absolute +path). + +```bash +pr-wait [--repo owner/name] [--until ready|green|any-change] +``` + +It prints one line per real event. It exits 0 when the `--until` condition is +met or the PR merges, 1 when it needs you (a required check failed, conflicts, +unresolved threads, PR closed), and 2 on bad input. + +- `ready` (default): required checks green, Greptile or Macroscope reviewed the + head, and no unresolved threads. Use this to babysit. +- `green`: required checks only. Use it when the repo has no Greptile or + Macroscope. +- `any-change`: exit on the first event. + +In Claude Code, run it with the Monitor tool (`timeout_ms: 3600000`), so each +line wakes you. Without a monitor, run it as one long command. It ends on its +own. + +Start it again after you push, after you handle an exit 1, and after a resume. +It remembers what it already reported, so nothing that arrived in between is +lost. If it says another pid already watches the PR, do not start a second one. +Kill the old one only if its events do not reach you. + +With either watcher: when an event needs no action, end your turn without a +message. Never post or say "still waiting". + +## GitHub rate limits + +`gh pr create`, `gh pr view`, and `gh pr checks` use GraphQL. When GraphQL is +used up, the REST limit is separate and usually still has room. Use +`gh api repos///pulls/` to read a PR, and +`gh api repos///commits//check-runs` for checks. + +## Reviews + +Only act on checks and comments newer than the latest push. Verify every bot +finding against the source before changing code. Fix real findings and CI +failures, distinguish repository failures from infrastructure flakes, and reply +with a written reason when dismissing false positives. + +If the repo has `.macroscope/check-run-agents/*.md`, read those rules before you +reply to a Macroscope finding. Its findings cite them. + +CodeRabbit is advisory. Treat its findings like any other finding, but never +wait for it and never hold a merge for it. + +If a review bot leaves feedback you believe is not worth addressing, reply with +a written reason and resolve the comment. Use the `leaving-pr-comments` skill +for every comment posted on the user's behalf. + +Screenshots and videos help as well, when you have a way to upload them. + +Keep the PR at the size the user's goal needs. Review loops tend to grow a +PR one cheap-looking fix at a time. Fix real bugs in the intended case. +Decline the rest with a written reason, and list them as follow-ups: +unneeded tests, guards for edge cases that do not matter, extra integration +or compatibility, and small performance costs. Prefer the fix that deletes or +narrows code. + +## Base branch and merging + +Keep an eye on changes to `main` and rebase when needed. `pr-wait` reports when +new base commits touch this PR's files, and when the PR becomes BEHIND or DIRTY. +`watch_pull_request` reports conflicts only, so check for BEHIND yourself +before you call the PR ready. +If an overlapping PR makes this one obsolete, stop monitoring, report it to the +user, and ask before closing the PR unless closure was explicitly authorized. + +If nothing has changed, stay quiet rather than posting filler comments. Stop +when `pr-wait` exits 0, or in T3 Code when the merge gate passes on the latest +head. Merge only when the user explicitly requested it; +otherwise report that the PR is ready. Right before a merge, run `git fetch` and +check the PR again. Never merge when it is BEHIND or DIRTY, or when base commits +that landed after the last green run touch this PR's files. Rebase, push, and +wait for green again. diff --git a/users/clover/agents/skills/babysit-pr/scripts/pr-wait b/users/clover/agents/skills/babysit-pr/scripts/pr-wait new file mode 100755 index 0000000000000000000000000000000000000000..33d45e5e3828e8dd9f159aee98b8974ebeb56098 --- /dev/null +++ b/users/clover/agents/skills/babysit-pr/scripts/pr-wait @@ -0,0 +1,556 @@ +#!/usr/bin/env python3 +"""pr-wait: watch one GitHub pull request and print one line per real event. + + pr-wait [--repo owner/name] [--until green|ready|any-change] [--interval 20] + + is a PR number or PR URL. Without --repo, the repo comes from the URL or +from the current checkout. Stdout carries only events, one line each, so a +monitor (Claude Code's Monitor tool) wakes the agent once per real event. +Progress and errors that do not end the run go to stderr. + +--until + green required checks passed on the current head (every CI check when + the base branch requires none) + ready green, Greptile or Macroscope reviewed the current head, and no + review thread is unresolved (default) + any-change stop after the first poll that prints an event + +Exit codes + 0 the --until condition is met, or the PR merged + 1 the condition cannot be met without action: a required check failed, the + branch conflicts with its base, the PR closed, `ready` is blocked by + unresolved threads or a BEHIND branch, or GitHub stayed unreachable + 2 bad arguments, unknown PR, or another pr-wait already watches this PR + +Events + - a required check failed (name and link) + - all checks finished on the head (one summary line) + - a new comment, review, thread, or thread reply from someone other than the + PR author or the gh user + - Greptile, Macroscope, or CodeRabbit finished on the head, or a Greptile or + Macroscope summary changed after that + - the base branch moved and the new commits touch files in this PR + - merge state became BEHIND or DIRTY + - the PR merged or closed + +CodeRabbit is advisory: pr-wait reports it but never waits for it. Comment +edits are never events, and top-level comments from CI and deploy bots +(github-actions, Vercel) are skipped, because checks already carry that news. + +State lives in ~/.local/state/pr-wait/. A lock makes a second watcher for the +same PR exit at once. A state file lets a restarted watcher report what arrived +while no watcher ran. The first run for a PR records what already exists and +reports only what comes after. +""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import html +import json +import os +import re +import subprocess +import sys +import time +from collections.abc import Sequence +from pathlib import Path +from typing import Any, NoReturn + +GATING_BOTS = ("greptile", "macroscope") +ADVISORY_BOTS = ("coderabbit",) +# CI and deploy bots report through checks. Their PR comments are status reports. +STATUS_BOTS = ("github-actions", "vercel", "netlify", "railway", "cloudflare") +STATE_DIR = Path.home() / ".local" / "state" / "pr-wait" +# A state file older than this describes an old session. Start a fresh baseline +# instead of replaying hours of comments as new events. +STALE_STATE_SECONDS = 6 * 3600 +MAX_FAILED_POLLS = 10 +TRANSIENT = re.compile( + r"HTTP (5\d\d|429)|rate limit|timed? ?out|connection (reset|refused)|EOF|" + r"temporar|could not resolve host|TLS handshake|Something went wrong", + re.IGNORECASE, +) +FAILED = ("fail", "cancel") +# gh pr checks buckets, worst first. Duplicate names (push and pull_request runs +# of one job) collapse to the worst bucket. +RANK = {"fail": 4, "cancel": 3, "pending": 2, "pass": 1, "skipping": 0} + +QUERY = """ +query($owner: String!, $name: String!, $number: Int!) { + viewer { login } + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + url state headRefOid baseRefName mergeStateStatus + author { login } + baseRef { target { oid } } + comments(last: 100) { nodes { id url body author { login __typename } } } + reviews(last: 100) { + nodes { id url state body commit { oid } author { login __typename } } + } + reviewThreads(last: 100) { + nodes { + isResolved path line + comments(first: 100) { nodes { id url body author { login __typename } } } + } + } + } + } +} +""" + +Json = dict[str, Any] + + +class GhError(Exception): + def __init__(self, message: str, transient: bool) -> None: + super().__init__(message) + self.transient = transient + + +def log(message: str) -> None: + print(f"pr-wait: {message}", file=sys.stderr, flush=True) + + +def fail(message: str, code: int = 2) -> NoReturn: + # Fatal messages go to stdout so a monitor shows the agent why it stopped. + print(f"pr-wait: {message}", flush=True) + sys.exit(code) + + +def gh(args: list[str], allow: tuple[int, ...] = (0,)) -> subprocess.CompletedProcess[str]: + """Run gh. Retries transient failures (HTTP 5xx or 429, network) with backoff.""" + delay = 2 + for attempt in range(5): + proc = subprocess.run(["gh", *args], capture_output=True, text=True) + transient = proc.returncode != 0 and bool(TRANSIENT.search(proc.stderr)) + if not transient and proc.returncode in allow: + return proc + lines = proc.stderr.strip().splitlines() + message = lines[-1] if lines else f"gh exited {proc.returncode}" + if not transient or attempt == 4: + raise GhError(message, transient) + log(f"gh {' '.join(args[:2])}: {message}; retry in {delay}s") + time.sleep(delay) + delay *= 2 + raise AssertionError("unreachable") + + +def gh_lines(args: list[str]) -> list[str]: + return [line for line in gh(args).stdout.splitlines() if line] + + +def bot_name(text: str | None) -> str | None: + """Which review bot a login or check name belongs to, if any.""" + lowered = (text or "").lower() + return next((bot for bot in GATING_BOTS + ADVISORY_BOTS if bot in lowered), None) + + +def who(node: Json) -> tuple[str, bool]: + author = node.get("author") or {} + return author.get("login") or "ghost", author.get("__typename") == "Bot" + + +def plain(body: str) -> str: + body = re.sub(r"", " ", body or "", flags=re.DOTALL) + return html.unescape(re.sub(r"<[^>]+>", " ", body)) + + +def snippet(body: str, limit: int = 100) -> str: + text = re.sub(r"\s+", " ", plain(body)).strip() + return text if len(text) <= limit else text[: limit - 3] + "..." + + +def verdict(body: str) -> str: + """The verdict line of a bot summary (Macroscope, Greptile), if it has one.""" + for line in plain(body).splitlines(): + if re.search(r"verdict|confidence score", line, re.IGNORECASE): + return snippet(line.replace("*", ""), 80) + return "" + + +def digest(body: str) -> str: + return hashlib.sha1(re.sub(r"\s+", " ", plain(body)).encode()).hexdigest()[:12] + + +def parse_target(raw: str | None, repo: str | None) -> tuple[str, int]: + if raw is None or not raw.strip(): + fail("missing PR number. Did a variable expand to nothing? Usage: pr-wait [--repo owner/name]") + url = re.fullmatch(r"https?://github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)(?:[/?#]\S*)?", raw.strip()) + number = re.fullmatch(r"#?(\d+)", raw.strip()) + if url: + repo = repo or url.group(1) + pr = int(url.group(2)) + elif number: + pr = int(number.group(1)) + else: + fail(f"'{raw}' is not a PR number or PR URL") + if pr <= 0: + fail(f"'{raw}' is not a valid PR number") + if not repo: + try: + repo = gh(["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"]).stdout.strip() + except GhError as error: + fail(f"no --repo given and the current directory has no GitHub repo ({error})") + if not re.fullmatch(r"[\w.-]+/[\w.-]+", repo): + fail(f"'{repo}' is not owner/name") + try: + gh(["pr", "view", str(pr), "-R", repo, "--json", "number"]) + except GhError as error: + if not error.transient: # a transient failure is retried by the poll loop + fail(f"cannot read {repo}#{pr}: {error}") + return repo, pr + + +def lock(repo: str, pr: int) -> Any: + """Hold a per-PR lock for the life of the process. The OS drops it on exit.""" + STATE_DIR.mkdir(parents=True, exist_ok=True) + handle = open(STATE_DIR / f"{repo.replace('/', '__')}__{pr}.lock", "a+") + try: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + handle.seek(0) + pid = handle.read().strip() or "unknown" + fail( + f"pid {pid} already watches {repo}#{pr}, so this watcher exits to avoid " + f"duplicate events. If no events reach you from it, run `kill {pid}` and start again." + ) + handle.seek(0) + handle.truncate() + handle.write(str(os.getpid())) + handle.flush() + return handle + + +def required_checks(repo: str, base: str) -> set[str]: + """Required check names for the base branch, from rulesets and classic branch + protection. Knowing them up front means a required check that has not started + yet counts as pending, instead of green by omission.""" + sources = ( + ( + f"repos/{repo}/rules/branches/{base}", + '.[] | select(.type == "required_status_checks") | .parameters.required_status_checks[].context', + ), + (f"repos/{repo}/branches/{base}/protection/required_status_checks", ".contexts[]?, .checks[]?.context"), + ) + names: set[str] = set() + for path, jq in sources: + try: + names.update(gh_lines(["api", path, "--jq", jq])) + except GhError as error: + if "HTTP 404" not in str(error): # 404 means no protection, which is normal + log(f"could not read required checks from {path}: {error}") + return names + + +class Watcher: + def __init__(self, repo: str, pr: int, until: str, interval: int) -> None: + self.repo, self.pr, self.until, self.interval = repo, pr, until, interval + self.owner, self.name = repo.split("/") + self.path = STATE_DIR / f"{repo.replace('/', '__')}__{pr}.json" + state = self.load() + # First run for this PR: record what exists and report nothing. + self.baseline = state is None + self.state: Json = state or {"reported": [], "summaries": {}, "base_oid": None, "merge_state": None} + self.reported: set[str] = set(self.state["reported"]) + self.printed: set[str] = set() + self.events = 0 + self.required: set[str] | None = None + self.prev_snapshot: list[tuple[str, str]] | None = None + self.pr_files: dict[str, set[str]] = {} + + def load(self) -> Json | None: + try: + if time.time() - self.path.stat().st_mtime > STALE_STATE_SECONDS: + return None + return json.loads(self.path.read_text()) + except (OSError, ValueError): + return None + + def save(self) -> None: + self.state["reported"] = sorted(self.reported) + tmp = self.path.with_suffix(".tmp") + tmp.write_text(json.dumps(self.state)) + tmp.replace(self.path) + + def say(self, line: str) -> None: + if line not in self.printed: + self.printed.add(line) + print(f"#{self.pr} {line}", flush=True) + + def emit(self, key: str, line: str) -> None: + """Print an event once per PR, across restarts.""" + if key in self.reported: + return + self.reported.add(key) + if not self.baseline: + self.events += 1 + self.say(line) + + def finish(self, code: int, lines: Sequence[str] = ()) -> NoReturn: + for line in lines: + self.say(line) + self.save() + sys.exit(code) + + def fetch_pr(self) -> Json: + proc = gh([ + "api", "graphql", "-f", f"query={QUERY}", + "-f", f"owner={self.owner}", "-f", f"name={self.name}", "-F", f"number={self.pr}", + ]) + data = json.loads(proc.stdout)["data"] + pr = data["repository"]["pullRequest"] + pr["viewer"] = data["viewer"]["login"] + return pr + + def fetch_checks(self) -> dict[str, Json]: + # gh pr checks exits 8 while checks are pending and 1 when one failed. + # Those are states, not errors: read the JSON and ignore the exit code. + proc = gh(["pr", "checks", str(self.pr), "-R", self.repo, "--json", "name,bucket,link,description"], allow=(0, 1, 8)) + if not proc.stdout.strip(): + if "no checks reported" in proc.stderr: + return {} + raise GhError(proc.stderr.strip() or f"gh pr checks exited {proc.returncode}", False) + checks: dict[str, Json] = {} + for row in json.loads(proc.stdout): + current = checks.get(row["name"]) + if current is None or RANK.get(row["bucket"], 2) > RANK.get(current["bucket"], 2): + checks[row["name"]] = row + return checks + + def base_overlap(self, head: str, old: str, new: str) -> list[str]: + """Files this PR touches that the new base commits also touch.""" + try: + if head not in self.pr_files: + self.pr_files[head] = set(gh_lines(["pr", "diff", str(self.pr), "-R", self.repo, "--name-only"])) + moved = gh_lines(["api", f"repos/{self.repo}/compare/{old}...{new}", "--jq", ".files[].filename"]) + except GhError as error: + log(f"could not compare base commits: {error}") + return [] + return sorted(self.pr_files[head].intersection(moved)) + + def behind(self, base: str, base_oid: str | None, head: str) -> str: + """How far the head is behind its base, for the green and ready lines.""" + if not base_oid: + return "" + try: + count = gh(["api", f"repos/{self.repo}/compare/{base_oid}...{head}", "--jq", ".behind_by"]).stdout.strip() + except GhError: + return "" + return f"; {count} commit{'' if count == '1' else 's'} behind {base}" + + def poll(self) -> None: + pr = self.fetch_pr() + if pr["state"] == "MERGED": + self.finish(0, [f"merged: {pr['url']}"]) + if pr["state"] == "CLOSED": + self.finish(1, [f"closed without merging: {pr['url']}"]) + + base = pr["baseRefName"] + if self.required is None: + self.required = required_checks(self.repo, base) + gate = ", ".join(sorted(self.required)) or "none set, so every CI check gates" + log(f"watching {self.repo}#{self.pr} until {self.until}; required checks: {gate}") + checks = self.fetch_checks() + head = pr["headRefOid"] + short = head[:7] + mine = {who(pr)[0], pr["viewer"]} + comments = pr["comments"]["nodes"] + reviews = pr["reviews"]["nodes"] + threads = pr["reviewThreads"]["nodes"] + self.events = 0 + + # Required checks. With no required checks configured, every CI check + # gates except the review bots' own checks. + gate = self.required or {name for name in checks if not bot_name(name)} + label = "required check" if self.required else "check" + + def bucket(name: str) -> str: + return checks[name]["bucket"] if name in checks else "pending" + + fail_lines: list[str] = [] + for name in sorted(gate): + if bucket(name) in FAILED: + link = checks[name]["link"] + fail_lines.append(f"{label} failed: {name} {link}") + self.emit(f"fail:{head}:{name}:{link}", fail_lines[-1]) + watched = {name: c for name, c in checks.items() if bot_name(name) not in ADVISORY_BOTS} + gate_done = bool(gate) and all(bucket(n) != "pending" for n in gate) + all_done = gate_done and all(c["bucket"] != "pending" for c in watched.values()) + # Checks appear a few seconds after a push. Two identical polls in a row + # guard against calling a half-registered set of checks finished. + snapshot = sorted((name, c["bucket"]) for name, c in watched.items()) + stable = snapshot == self.prev_snapshot + self.prev_snapshot = snapshot + green = gate_done and stable and not fail_lines + + # People and bots talking. Edits are never events. + for comment in comments: + login, is_bot = who(comment) + if login in mine or bot_name(login) or (is_bot and any(b in login for b in STATUS_BOTS)): + continue + self.emit(f"c:{comment['id']}", f"comment from {login}: {snippet(comment['body'])} {comment['url']}") + for review in reviews: + login, is_bot = who(review) + if login in mine or is_bot: + continue + if review["state"] in ("APPROVED", "CHANGES_REQUESTED") or review["body"].strip(): + state = review["state"].lower().replace("_", " ") + self.emit(f"c:{review['id']}", f"review from {login} ({state}): {snippet(review['body'])} {review['url']}") + unresolved: list[str] = [] + for thread in threads: + nodes = thread["comments"]["nodes"] + if not thread["isResolved"] and nodes: + unresolved.append(nodes[0]["url"]) + where = f"{thread['path']}:{thread['line']}" if thread["line"] else thread["path"] + for index, comment in enumerate(nodes): + login, _ = who(comment) + if login in mine: + continue + kind = "new thread" if index == 0 else "thread reply" + self.emit(f"c:{comment['id']}", f"{kind} from {login} on {where}: {snippet(comment['body'])} {comment['url']}") + + # Review bots on the current head. A bot with checks is done when they + # finish. Otherwise it is done once it reviews the head commit or its + # summary names the head. + bot_status: dict[str, str] = {} + reviewed: list[str] = [] + for bot in GATING_BOTS + ADVISORY_BOTS: + own_checks = {name: c for name, c in checks.items() if bot_name(name) == bot} + summaries = [c for c in comments if bot_name(who(c)[0]) == bot] + own_reviews = [r for r in reviews if bot_name(who(r)[0]) == bot] + on_head = any((r.get("commit") or {}).get("oid") == head for r in own_reviews) + if own_checks: + done = all(c["bucket"] != "pending" for c in own_checks.values()) + else: + done = on_head or any(short in s["body"] for s in summaries) + seen = bool(own_checks or summaries or own_reviews) + if bot in ADVISORY_BOTS and own_checks: + desc = next(iter(own_checks.values())) + bot_status[bot] = f"{bot} {desc['description'] or desc['bucket']} (advisory)" + elif seen: + bot_status[bot] = f"{bot} {'done' if done else 'pending'}{' (advisory)' if bot in ADVISORY_BOTS else ''}" + key = f"bot:{bot}:{head}" + was_done = key in self.reported + if done: + if bot in GATING_BOTS: + reviewed.append(bot) + failed = [name for name, c in own_checks.items() if c["bucket"] in FAILED] + detail = "; ".join(filter(None, [ + next((v for v in map(verdict, (s["body"] for s in summaries)) if v), ""), + f"failed: {', '.join(failed)}" if failed else "", + ])) + tag = " (advisory, not waited on)" if bot in ADVISORY_BOTS else "" + self.emit(key, f"{bot} finished on {short}{': ' + detail if detail else ''}{tag}") + if bot in GATING_BOTS: + for s in summaries: + new, old = digest(s["body"]), self.state["summaries"].get(s["id"]) + self.state["summaries"][s["id"]] = new + if was_done and old and old != new: + text = verdict(s["body"]) or snippet(s["body"]) + self.emit(f"summary:{s['id']}:{new}", f"{bot} summary changed on {short}: {text} {s['url']}") + + # Base branch and merge state. + base_oid = ((pr.get("baseRef") or {}).get("target") or {}).get("oid") + old_base = self.state["base_oid"] + if base_oid and old_base and base_oid != old_base and not self.baseline: + touched = self.base_overlap(head, old_base, base_oid) + if touched: + more = f" and {len(touched) - 5} more" if len(touched) > 5 else "" + self.emit( + f"base:{base_oid}", + f"{base} moved to {base_oid[:7]} and touches files in this PR: {', '.join(touched[:5])}{more}", + ) + if base_oid: + self.state["base_oid"] = base_oid + merge_state = pr["mergeStateStatus"] + dirty_line = f"merge state is DIRTY: the branch conflicts with {base}, rebase it" + behind_line = f"merge state is BEHIND: update the branch from {base} before merging" + if merge_state != "UNKNOWN": + if merge_state in ("BEHIND", "DIRTY") and self.state["merge_state"] != merge_state: + line = dirty_line if merge_state == "DIRTY" else behind_line + self.emit(f"merge:{merge_state}:{head}:{base_oid}", line) + self.state["merge_state"] = merge_state + + # One summary line per head once all checks finish. + counts: dict[str, int] = {} + for c in watched.values(): + counts[c["bucket"]] = counts.get(c["bucket"], 0) + 1 + failed_names = sorted(name for name, c in watched.items() if c["bucket"] in FAILED) + parts = [ + ", ".join(f"{n} {b}" for b, n in sorted(counts.items())) + + (f" ({', '.join(failed_names)})" if failed_names else ""), + f"required {sum(bucket(n) in ('pass', 'skipping') for n in self.required)}/{len(self.required)} green" + if self.required + else "", + ", ".join(bot_status[b] for b in GATING_BOTS + ADVISORY_BOTS if b in bot_status) + or "no Greptile or Macroscope yet", + f"{len(unresolved)} unresolved threads", + f"merge state {merge_state}", + ] + summary = "; ".join(p for p in parts if p) + checks_key = f"checks:{head}" + + # Decide whether to stop. A green or ready line carries the same summary + # as the checks line, so it marks that event as reported. + if self.until != "any-change": + if merge_state == "DIRTY": + self.finish(1, [dirty_line]) + if fail_lines: + self.finish(1, fail_lines) + if green and self.until == "green": + self.reported.add(checks_key) + self.finish(0, [f"green on {short}: {summary}{self.behind(base, base_oid, head)}"]) + # ready waits for Greptile or Macroscope, never for CodeRabbit. + if green and reviewed: + if unresolved: + self.finish(1, [f"blocked by {len(unresolved)} unresolved threads on {short}: {' '.join(unresolved)}"]) + if merge_state == "BEHIND": + self.finish(1, [behind_line]) + self.reported.add(checks_key) + self.finish(0, [f"ready on {short}: {summary}{self.behind(base, base_oid, head)}"]) + if all_done and (stable or self.baseline): + self.emit(checks_key, f"checks finished on {short}: {summary}") + if self.until == "any-change" and self.events: + self.finish(0) + + def run(self) -> NoReturn: + failures = 0 + while True: + try: + self.poll() + failures = 0 + except GhError as error: + if not error.transient: + self.finish(1, [f"pr-wait stopped: {error}"]) + failures += 1 + log(f"poll failed ({failures}/{MAX_FAILED_POLLS}): {error}") + if failures >= MAX_FAILED_POLLS: + self.finish(1, [f"pr-wait stopped: GitHub unreachable for {failures} polls: {error}"]) + else: + self.save() + if self.baseline: + log(f"baseline recorded for {self.repo}#{self.pr}; reporting only new events") + self.baseline = False + time.sleep(self.interval) + + +def main() -> None: + parser = argparse.ArgumentParser(prog="pr-wait", description="Watch a GitHub PR and print one line per real event.") + parser.add_argument("pr", nargs="?", help="PR number or URL") + parser.add_argument("--repo", help="owner/name (default: from the URL or the current checkout)") + parser.add_argument("--until", choices=("green", "ready", "any-change"), default="ready") + parser.add_argument("--interval", type=int, default=20, help="seconds between polls (default 20, min 5)") + args = parser.parse_args() + repo, pr = parse_target(args.pr, args.repo) + _lock = lock(repo, pr) + Watcher(repo, pr, args.until, max(args.interval, 5)).run() + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + sys.exit(130) diff --git a/users/clover/agents/skills/cold-read/SKILL.md b/users/clover/agents/skills/cold-read/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..aa271f825ca035b53e53fd8a8c73f1848b637863 --- /dev/null +++ b/users/clover/agents/skills/cold-read/SKILL.md @@ -0,0 +1,112 @@ +--- +name: cold-read +description: Review anything you are about to hand to a person (screenshot, GIF, chart, UI state, user-facing string, error message, PR or commit body, report) as a reader with no context, before it ships. Use this before sending an image or chart, before reporting a UI change done, before filing a PR or writing a commit message, and before any string a user will read. It catches what the author cannot see after working with full context. Cut-off text, jargon, dead ends, demo-only data and claims nobody can judge without the thread. Lighter than the whole-app tester in `ux-testing`. +--- + +# Cold read + +After hours in a task, every gap in the artifact is filled in by what you know. +You read "needs ACP adapter" and see a precise term; the owner sees nonsense. +Re-reading with that context passes the same flaws, so the check has to run in a +reader who never had it. + +`AGENTS.md` says when: anything that leaves the thread. This skill says how. +`ux-testing` ("fresh eyes") drives a whole app as a first-time user; this is the +per-artifact version of the same idea. + +## 1. Make the artifact the thing the reader sees + +- Review the output, not its source: the PNG, the rendered page, the final PR + body, the string as it appears in the UI. +- Use real data. A fixture that happens to fit hides truncation, `0.00`, odd + ordering, and entries the owner did not expect to see. +- Capture every state a person can land in (empty, long, error, narrow), not just + the happy one. + +## 2. Self pass, every time (cheap) + +A screenshot script that exits 0 has been tested, not reviewed: the feature +works and the image can still be cropped, blank, stale, or showing the wrong +state. Capture and send must be separate steps, never one script or one call, +and no image goes to the owner (or into a PR, report, or `html_render`) that you +have not opened in this turn. + +Open the file with the image viewer and write down, in plain words, what is on +it before judging. Check that it shows the state you meant to prove, not just +some state. Then check: + +- text ending in `…` (a finding even when intentional, since it reads as cut + off), clipped at an edge, or overlapping something; +- uneven spacing, empty regions, content hugging one side; +- marks with no label: icons, badges, `+1`, colours, ticks; +- a chart's title, axis names, units and legend. Can its claim be read at a + glance? + +## 3. Cold pass (anything past a one-liner) + +Launch a fresh sub-agent on Claude Sonnet at low effort. It gets the artifact, +one line naming the audience, and the questions for its kind. It never gets the +diff, the thread, the code, or what you meant it to say. When Claude usage is +low, use `gpt-6.1-terra` at low effort instead, and check geometry and +affordance yourself in the self pass (see "Choosing the reader"). + +``` +You are . You have +only the attached . Do not read any code or docs. Say in two +sentences what you think it shows or does. Then list at most three things a +real person would stop or misunderstand at (confusing, cut off, undefined, +misleading, missing), worst first, one line each: what you saw → what you +expected. Skip taste and polish. Do not say whether you like it. If it is fine, +say "nothing" and stop. + +Questions: +``` + +A reader that cannot restate the artifact correctly in its first two sentences +is the finding. + +| artifact | ask | +|---|---| +| screenshot, UI state | Is any text cut off or any gap uneven? What can I do next, and can I undo it? Which things are buttons? | +| UI copy, labels | Is every word and symbol defined for someone who just arrived? Does anything use the project's internal vocabulary? | +| chart | What is the claim? Are axes, units and legend present? What would a skeptic say is missing? | +| generated or computed content | Does anything look wrong for a real input (rounding, ordering, casing, an item that shouldn't be there)? | +| form of the content | What does the reader decide from this, and is this the shape that serves that decision? | +| PR, commit, issue body | Can a reviewer judge each claim without the thread? Is the size justified in the first lines? Is anything stated that the reader cannot verify? | +| error or status | What happened, whose fault is it, what do I do? | + +## Choosing the reader + +Measured on 18 screenshots (9 with one planted flaw each, 9 fixed controls) at +low, medium and high effort. Single runs, blatant flaws only; subtle ones such +as a 2px misalignment are untested. + +| reader | planted flaws caught | findings per image | misses | +|---|---|---|---| +| Claude Sonnet, any effort | 9/9 | 3.3–4.1 | none | +| gpt-6.1-sol | 6–8/9 | 1.1–1.4 | unclickable menu, uneven padding | +| gpt-6.1-terra, any effort | 7/9 | 0.9–1.1 | unclickable menu, uneven padding | + +- More effort never caught more; on Sonnet it only added nitpicks, so use low. +- Sonnet sees layout and affordance the others miss, and its extra findings are + mostly polish, which the three-finding cap in the brief removes. +- Terra is solid on meaning, cut-off text, rounding and missing labels, and + stays quiet on clean images. It misses pure layout and affordance, so as the + fallback the self pass must check spacing and "what looks clickable" itself. +- Sol offers nothing over Terra here. Do not use opus- or fable-class models. + +## 4. Act on it + +- Fix every real confusion and re-render. Re-run the cold pass once if the fix + changed layout or wording substantially. +- Findings about taste or direction go to the owner as a question. The cold + reader cannot judge taste, so never ask it whether something is good. +- Report the fix in one line after the artifact, never before it. + +## Where it has already failed + +Owner complaints this skill exists to prevent: a "Use reset link" cut off to +`Use…`; "needs ACP adapter makes no sense to me"; "unclear where you get this +key from"; "I can't tell what is a button"; "a learning rate reads 0.00"; +"deepseek is showing up here"; "displaying a table is kind of wrong"; "+4800, +what the heck". diff --git a/users/clover/agents/skills/file-pr/SKILL.md b/users/clover/agents/skills/file-pr/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..3e91972bfdafe0b10a12d4ee4dbfea9373c1f8ab --- /dev/null +++ b/users/clover/agents/skills/file-pr/SKILL.md @@ -0,0 +1,85 @@ +--- +name: file-pr +description: File a concise pull request. Use when the user asks to file, open, or create a PR. +--- + +# File PR + +## Push permission + +A request to file a PR, including "full send file pr", authorizes committing, +pushing this task's branch, and the branch updates described here without +asking again. This grant replaces general ask-first rules for these actions; +it does not bypass harness approvals or branch protection. `full-send` and +`full-stop` use this same policy. + +Before rewriting a published PR branch, check the live draft status and its +ready-for-review history. For a draft PR that has never been marked ready for +review, rebase as needed and automatically push with `--force-with-lease`. +Never use plain `--force` or overwrite someone else's unexpected changes. + +Once a PR has been marked ready for review, preserve its published history, +even if it later returns to draft. Use follow-up commits for fixes and merge +the target branch when an update is needed. Rewriting that history requires +explicit user authorization. If review history cannot be established, preserve +published history. This permission covers only this task's branch, never the +default branch or unrelated branches. + +## Filing + +Before filing, check whether a PR for this branch already exists. Review the +diff locally against the base branch (usually `origin/main`) to make sure its +contents match the goal. + +Write like a developer leaving a short note for teammates who know the project: +direct, conversational, and matter-of-fact. Name the change and keep useful +specifics. Cut ceremony ("This PR introduces..."), sales language, and a tour +of the diff. Keep technical terms when they are the clearest way to say it. + +PR titles usually become commit messages. Aim for 50 characters or fewer, +including any prefix and scope. Follow required repository conventions; use +a scope only when the project requires one. Learn the tone of user-endorsed +writing; a merge alone does not make a PR a style reference. + +Each row below rewrites the same change. Use the examples to learn the voice, +then write fresh wording from the actual diff. Preserve the facts; shortening +a title must not broaden its claim or invent a benefit. The scoped pair +assumes a project that requires scopes. + +| Before | After | +| --- | --- | +| `fix: improve retry handling to prevent duplicate sends` | `fix: stop retries from sending messages twice` | +| `feat: persist and hydrate open-tab state across app launches` | `feat: restore open tabs on launch` | +| `feat: unlock seamless note sharing with public links` | `feat: share notes with a public link` | +| `refactor: extract a common parser module for the CLI and worker` | `refactor: share the CLI and worker parser` | +| `perf: implement incremental file indexing using modification timestamps` | `perf: skip unchanged files when indexing` | +| `fix(sync): preserve the pending upload queue when the application restarts` | `fix(sync): keep pending uploads after restart` | + +Descriptions usually need one or two sentences. For a bug, give the symptom +and the changed behavior; for a feature, say what it lets someone do. For +internal work, say what changes and why. Keep a technical detail, measured +result, or validation when it helps the reviewer assess the change. No file +lists, section headings, or routine test plans. + +| Before | After | +| --- | --- | +| This PR fixes out-of-order search responses by introducing a monotonically increasing request counter and dropping payloads whose counter no longer matches the hook state. | An older search could finish last and replace the results for your current query. Responses for older queries are now ignored. | +| This PR introduces a powerful new capability that enables users to generate a public URL for a note and distribute it to external recipients without requiring them to authenticate. | You can share a note with a public link. Anyone with the link can read it without signing in. | +| Extracted a shared parser package, replaced the separate parsing utilities in the CLI and worker, and updated both callers so a syntax fix no longer needs two implementations. | The CLI and worker now use the same parser, so syntax fixes only need to happen once. | + +End the description with one trailer line per model that wrote part of the +change, in the form `Assisted-by: ` (`claude-opus-5.5`, `gpt-6.1-sol`). +Use the model ID the harness reports, never `Co-authored-by`, and never guess: +if the model is unavailable, name the harness. Put `Assisted-by: chatgpt-dot:lilac` +last when the task came from a Lilac agent or mentions "ChatGPT Dot". + +Before submission, check the title, description, quotes, and attachments for +secrets and private details. + +Open a real PR rather than a draft so review bots run. If `gh pr create` fails +because the GraphQL rate limit is used up, open it through REST with +`gh api repos///pulls -f title=... -f head=... -f base=... -F body=@`. +If the user also asked to babysit it, continue with the `babysit-pr` skill. + +Do not post a follow-up PR comment unless it serves the user's request. When a +comment is needed, use the `leaving-pr-comments` skill. diff --git a/users/clover/agents/skills/full-send/SKILL.md b/users/clover/agents/skills/full-send/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..5262c7779e05b95df434254f6153d6f4c0b6ad5e --- /dev/null +++ b/users/clover/agents/skills/full-send/SKILL.md @@ -0,0 +1,124 @@ +--- +name: full-send +description: Trigger this if the user says 'full send'. +--- + +# Full Send + +If the user triggered this, it's because they are not watching this thread, and +they want you to complete the work end-to-end autonomously. Your updates and +your final message go unread until long after you stop. You own the work from +its current state to a merged PR. + +If the user did not explicitly request "full send" in some clear way, do not +assume full autonomy. If they did, everything below applies. + +The user grants you permission to: + +- Merge the PR once the merge gate passes. +- Commit and push the task's branch under + [file-pr's push policy](../file-pr/SKILL.md#push-permission). +- Use the test methods that Proof needs, without asking first. + +## Testing permission + +A "full send" request is the permission. If a project file or other +instruction says to ask before a test method, or to leave testing to the +user, this request replaces that rule for this task. + +That includes ask-first rules for computer use, browser automation, +simulators and devices, running the app or a dev server, screenshots, and +visual checks. Use the method that gives direct proof. List it in the +report. + +Rules about how to test still apply. Follow rules that name the correct +command, fixture, or check. This permission only removes the ask-first or +leave-it-to-the-user step. If a preferred method cannot prove the change, +use a gated method under this permission. + +It covers only the tests needed for this task. It does not add permission +for the steps under "Asking the user", such as production changes or data +deletion. It also does not bypass a harness or system approval prompt if +one appears. + +## Steps + +1. **Finish the change.** Complete the goal from the user's request with the + smallest change that works. Fix the case that happened, not every case + that could. If you are on the default branch, create a branch first. +2. **Prove it.** Get proof for every change you made. See "Proof". +3. **Get feedback.** Use the `sol-loop` skill to verify changes. +4. **File the PR** with the `file-pr` skill. Update against the latest default + branch first, following its push policy for existing PRs. Add one short + line to the description that says how you proved the change. +5. **Babysit the PR** with the `babysit-pr` skill. Fix real findings and CI + failures. Get proof for each fix before you push it. +6. **Merge** when the merge gate passes. +7. **Report** in your final message: the PR link, the merge commit, your proof, + and each decision you made for the user. + +Stay active from step 1 to step 7. If you end your turn while checks or bots are +pending, the work stops, because nobody will prompt you again. Wait with the +watcher from `babysit-pr`, so something wakes you when the PR changes. In T3 +Code that is `watch_pull_request`. If you stop before the merge, call +`unwatch_pull_request` first. + +## Proof + +Proof is evidence you observed yourself in this session: command output, a +reproduction, a screenshot. Use the most direct proof the change allows: + +- Reproduce the original failure, apply the fix, then watch the same + reproduction pass. +- Run the checks that the repo's CI runs (typecheck, lint, tests). +- Add one focused test that fails without the fix, when the behavior has none + and the repo has a test setup. +- For UI and runtime behavior, run the app and look at the change. Green mocked + tests do not prove that the user experience works. Attach screenshots to the + PR when they help and you have a way to upload them. + +When you cannot find a way to prove a change, you do not have full confidence. +Ask the user. + +## Merge gate + +Full confidence means all of these are true on the latest commit: + +- Your proof covers every change in the diff. +- Required checks are green. +- Review bots have finished, and each finding is fixed or dismissed with a + written reason. +- No human review still requests changes. +- The branch is up to date with the default branch, and GitHub reports it as + mergeable. + +Merge with the method the repo uses. Check the allowed methods and recent merged +PRs. If the repo uses a merge queue or auto-merge, stay until GitHub reports the +PR as merged. Merge through branch protection as configured. Never use `--admin` +or other bypasses. You can ignore automated reviews that request "needs human +review" if you have high confidence in your changes. + +## Asking the user + +A question in a normal message goes unseen, and the thread looks done. To ask +the user something, use the harness's question tool so the thread shows that +it is waiting: `AskUserQuestion` in Claude Code, `request_user_input` in Codex, +or the question tool your harness has. Put all the context in the question: +the PR link, what blocks you, and the options with your recommendation first. + +Ask only when you cannot continue alone: + +- You cannot prove the change. +- The merge gate cannot pass, and you cannot fix that yourself. +- The next step is outside the grant above: deleting data, touching production, + changing things outside the repo, closing a PR, or force-pushing any other + branch. +- The goal is ambiguous in a way that changes the result. +- Another PR makes this one obsolete. + +Decide everything else yourself with sensible defaults, and list those decisions +in the report. + +If no question tool is available, or the tool returns no answer, take the safe +path: leave the PR open and unmerged, and start your final message with the +question. diff --git a/users/clover/agents/skills/full-stop/SKILL.md b/users/clover/agents/skills/full-stop/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..af99ea452d0f298b98db980e45e7da8b550bf21f --- /dev/null +++ b/users/clover/agents/skills/full-stop/SKILL.md @@ -0,0 +1,48 @@ +--- +name: full-stop +description: Trigger this if the user says 'full stop', even as a closing "Full stop." that reads like emphasis. +--- + +# Full Stop + +Do the same work as `full-send`, but stop with the PR ready for the user to merge. +Never merge it. + +Read [full-send](../full-send/SKILL.md) and follow its workflow, proof rules, +review, and babysitting steps. An explicit "full stop" request authorizes that +work without a separate "full send" request. That includes full-send's +testing permission. A "full stop" request is the permission for the test +methods Proof needs, even when a project file says to ask first, for +example before computer use. Use those methods directly. Its merge +permission does not apply. The overrides below take precedence. + +## No merging + +You may commit, push, rebase, and fix conflicts on this task's branch under +[file-pr's push policy](../file-pr/SKILL.md#push-permission). Never merge, +enable auto-merge, enter a merge queue, push to the default branch, bypass +branch protection, or delegate those actions. + +Disable existing auto-merge and remove the PR from any merge queue before +work begins; check again before each push. Report these changes. If you +cannot prevent automatic merging, report the blocker before proceeding. + +## Stop at the gate + +Use full-send's merge gate as the readiness check. Replace its merge and +final report steps with a handoff. Proof and review must cover the final diff; +recheck behavior changes and meaningful conflict fixes before handoff. + +Fetch the target branch and check the live PR's head, base, checks, reviews, +and mergeability. Confirm it is open, not a draft, and not set to merge +without the user. If someone else merged it, report that instead. + +- **Ready to merge:** the merge gate passes. Leave the PR open and unmerged. +- **Waiting for required approval:** only human approval remains. Confirm + that this is the actual blocker. +- **Blocked:** explain what prevents readiness, what you tried, and what is + needed. Follow full-send's rules for asking the user. + +In T3 Code, call `unwatch_pull_request` before the handoff or a question. +Report the PR link, final head, verdict, proof, reviewer outcome, and remaining +risks. State whether the PR is still open and unmerged. diff --git a/users/clover/agents/skills/full-stop/agents/openai.yaml b/users/clover/agents/skills/full-stop/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fe4b5e7605ef9f69690fcaee2018b593de734a30 --- /dev/null +++ b/users/clover/agents/skills/full-stop/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Full Stop" + short_description: "Prove, review, and prepare a PR without merging" + default_prompt: "Use $full-stop to make this PR ready for me to merge." diff --git a/users/clover/agents/skills/leaving-pr-comments/SKILL.md b/users/clover/agents/skills/leaving-pr-comments/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..d0a9390be3376563740da7b2244f22bd90e66eac --- /dev/null +++ b/users/clover/agents/skills/leaving-pr-comments/SKILL.md @@ -0,0 +1,138 @@ +--- +name: leaving-pr-comments +description: Use whenever leaving comments on GitHub. +--- + +# Leaving PR Comments + +Comments post from Clover's GitHub account but are written by an agent. A +reader should be able to tell who did what, and the comment should make sense +to someone who only sees the PR. Beyond the badge and point of view, everything +here is a default, not a checklist. It's not that deep. + +## Attribution badge + +The first line of every agent-written comment is this badge, alone, followed by +a blank line: + +```md +![comment written by Claude Sonnet 5.5](https://img.shields.io/badge/comment_written_by-Claude_Sonnet_5.5-8a63d2?style=flat-square) +``` + +Put the verified display name of the model writing the comment in both the +alt text and the badge: "Claude Sonnet 5.5", "GPT-6.1 Sol", "Qwen3.8 27B", +never a model ID like `claude-sonnet-5-5` or `gpt-6.1-sol`. In the badge URL, +write spaces as `_`, `-` as `--`, and `_` as `__` (`GPT-6.1 Sol` → +`GPT--6.1_Sol`). If the harness exposes no model name, use the harness name. +Do not guess. + +The badge is the only attribution: no callout, signature, footer, or second +credit. + +Use it on top-level comments, inline review comments, review bodies, replies to +bots or reviewers, and explanations left before resolving or dismissing +feedback. Leave it off PR descriptions, commit messages, and text Clover asked +to post verbatim without attribution. + +## Point of view + +First person is ambiguous here, so don't write "I", "me", or "my". + +| write | for | +| ------------ | ------------------------------------------------------------- | +| you | the patch author, or whoever the comment replies to | +| Clover | Clover specifically: her accounts, machines, decisions, plans | +| the agent | the model doing work for Clover: pushing, testing, fixing | +| we, our | Clover and her agents together: "we tried it on a fresh install" | +| (no subject) | plain actions: "pushed abc1234", "tried it on Linux" | + +State Clover's opinions and rules in the comment's own voice, not as a relayed +note ("Clover's note:"). + +## Shape + +Inline comments and bot replies are usually a line or three: the conclusion and +its evidence. For top-level comments and review bodies, this order works well; +skip what has nothing to say: + +1. **What this means for the patch.** Thanks if earned, what changed, the + state, and what happens next. +2. **Details.** How to reproduce, what broke, why, with file references. +3. **What wasn't verified, if it leaves something on the reader.** The reason + and who carries it ("Clover has no ARM machine, so we're trusting your own + testing there"), rather than a bare "did not test X" or a passive "still + needs verification". +4. **Clover's general note, if she gave one,** and how serious it was in plain + words. Don't invent a rule or a severity she didn't give. + +Clover's asks usually block the merge; findings only the agent made usually +don't. When a comment mixes both, label them `blocking:` and `non-blocking:`. + +Closing a PR takes a line or two of reason. + +Don't mention the chat, the transcript, Clover's instructions, or "as +requested"; turn an instruction into what the reader needs to know or do. + +## Voice + +A variant of Clover's own: lowercase sentence starts, informal, short, warm, +blunt. Keep exact case for code, paths, UI labels, SHAs, and names. Backtick +code, paths, and UI labels. Her own review lines, for calibration: + +> windows seems flaky. not your fault. +> looks reasonable. doing some testing before merging +> model resolution already is aware of this, and should snap you to the correct tier already. does that code break and this is the fix? +> needs a rebase anyways + +- Say "not your fault" when the failure isn't theirs. +- Ask a direct question instead of hedging. +- Thank once, specifically when there's something to name. +- Leave Clover's harsh slang to Clover (cooked, slop, trolled). From an agent + it reads as mockery of the contributor. +- Skip canned openers, status narration, and closing summaries. + +## Dictionary + +| term | meaning | +| -------------- | ---------------------------------------------------------------- | +| patch | the contributor's change; preferred over "PR" for the change itself | +| PR | the GitHub object: open PRs, linked issue, PR description | +| harness | an agent CLI driven by another tool | +| code review | reading the diff | +| manual testing | running the feature end to end | +| spot check | a quick run of the main path, not a full test | +| smell check | a first look; it fails when something is obviously off | +| hardening | robustness work. Partial hardening doesn't close the issue | +| edge cases | e.g. empty input, signed out, no network | +| non-blocking | the merge doesn't wait on it | +| nitpicks | style-level notes | +| rebase | "needs a rebase" means the branch is behind and conflicts | +| draft | marking as draft parks a patch; it is not a rejection | +| sus | suspicious: looks off, worth a second look | +| soon™ | soon, but timing not promised | + +When closing or parking a stale PR, open the body with: "hi, we're working on +reducing the number of open PRs, and apologize for reviewer delays." + +## Example + +A contrived one, to show the form rather than any real patch: + +```md +![comment written by GPT-6.1 Sol](https://img.shields.io/badge/comment_written_by-GPT--6.1_Sol-8a63d2?style=flat-square) + +thanks for the patch, the topping picker reads much better now. one thing blocks the merge, the rest doesn't. + +blocking: `--extra-cheese` doubles the cheese twice when the order also has `--deluxe`, since both `apply_deluxe()` and `apply_extras()` in `src/order/toppings.rs` scale `cheese_grams`. is that intended, or should deluxe skip the extras pass? + +non-blocking: `Toppings` → `Cheese` still says "mozzarella" on vegan orders. fine as a follow-up. + +Clover's oven tops out at 250°C, so the 300°C bake profile wasn't tried. we're trusting your own test of that one. +``` + +## Posting + +Before posting, check the whole comment, including quoted text and +attachments, for secrets and private details. Preview the Markdown so the badge +and blank lines render. After posting, verify GitHub returned the comment or +review URL. Resolve a review thread only after its reply posted. diff --git a/users/clover/agents/skills/maintain-it/SKILL.md b/users/clover/agents/skills/maintain-it/SKILL.md deleted file mode 100644 index 592a74a79e9dfc4205c20939981660cf3c34d2d9..0000000000000000000000000000000000000000 --- a/users/clover/agents/skills/maintain-it/SKILL.md +++ /dev/null @@ -1,247 +0,0 @@ ---- -name: maintain-it -description: Take over a solo repo as its maintainer. One long-lived thread decides what to work on, briefs and supervises sub-agents, gates and lands small changes straight on main, optionally cuts releases and keeps an issue tracker in sync, and leaves state any session can resume from. Use when the owner says "maintain this", "own this repo", "you're the maintainer", "keep shipping", "run the project" or "work through the issue tracker", or asks which issues to close or open; when a personal project with no CI that pushes to main is handed over; and when resuming that role after a compaction, a usage limit or a reboot. Not for a single fix or feature. ---- - -# Maintain it - -You maintain a solo project. You keep a queue, run sub-agents, and land small -changes on main behind a local gate. If the project has releases and an issue -tracker, you run those too. You keep state that any session can resume from. -The owner keeps taste, names, public words and anything irreversible. -Everything else is yours. - -The strategy comes from Snowbound, Clover's OneNote 2010 remake. One thread -maintained it for ten days: about 230 commits on main and about twenty releases, -on up to seven platforms, to friends running self-updating builds. - -> "thru a lot of that chat … the ai owned the app more than me" — Clover - -Her standing order was "your job remains orchestration and shipping changes onto -main". Her quotes appear throughout. The rules below keep what worked and fix -what cost her attention. A **wave** is one batch of agents launched together and -landed. - -Related skills: `ui-review-loop` covers briefs and feedback rounds, `ux-testing` -covers verification and the owner's machine, and `ui-copy` covers the words. - -## 0. First session - -1. Read the repo's AGENTS.md or CLAUDE.md, its README, the tracker and recent - history. -2. Run the contract round (section 1). -3. Write the state file (`references/state-file.md`). -4. Find the gate, or build one (`references/gate.md`). -5. Run the prechecks in section 8. -6. Propose the first wave, ranked, with reasons. - -## 1. The contract - -Ask these in one multiple-choice round, with the lean first. Record the answers -verbatim and dated, in the state file's Contract section and in memory. Record -any later authorization the same way, the moment it's given. The repo's own -rules (version control, trailers, forbidden paths) come from its AGENTS.md or -CLAUDE.md. - -| Question | Options (lean first) | Snowbound's answer | -| --- | --- | --- | -| Landing | Push each green change to main / batch per wave / ask first | "feel free to push bugfixes as you make them" | -| Commit convention | Conventional prefixes plus the repo's trailers / the repo's existing style | Prefixes, and one trailer naming each model actually used | -| Releases | None / on request / every wave | Every wave, every platform: "build and publish all future versions with OS X 10.6 build and Linux x86_64 and aarch64" | -| The owner's installed copy | Updater only / rebuild it for them / never touch | Rebuilt for her at first; once the updater shipped, "you should not mutate the build so we can observe the updater" | -| Tracker writes | Open, comment on and close issues in the browser / list them for the owner | Never touched by the maintainer thread; Clover wants it driven through the browser (section 4) | -| Budget | Use it all while there's work / stay under a cap by a date | "its ok to blow through the entire limit as long as theres stuff to actually do"; later, "lets try not to go above 70% by start of monday" | -| Machines | Lab VMs freely, named devices with permission / ask each time | Lab VMs freely; her real Windows 7 laptop only with explicit permission | -| The state file | Kept out of version control / committed | Kept out of version control, inside the repo | -| What stays theirs | Names, public prose, guides, passion features, system settings | The guide ("i value the human<->human communication"), a passion feature ("i'd like to discuss that when it comes time to"), system settings, syncing a mirror | - -## 2. The loop - -``` -pick → brief → isolate → gate → land → release? → close → report → back to pick -``` - -- **Pick.** Draw from the tracker, the agreed roadmap, and evidence you gather: - sweeps over real data, red gate lanes, audits. Keep agents busy within the - budget. Clover once had to ask, "only one running task is this the only thing - that should run in parallel right now?" -- **Brief.** Use the `ui-review-loop` brief, including its effort routing. -- **Isolate.** Give every agent its own checkout (a workspace) branched from - main; they can share the build cache. One shared working copy was Snowbound's - most expensive mistake: - - builds broken for hours by another agent's half-edit; - - commits that swept in unfinished code; - - installs that silently didn't happen ("btw your new build was not - installed"); - - releases that aborted mid-run. -- **Gate** the exact revision (section 3). -- **Land.** - 1. Rebase the agent's change onto main. - 2. Gate that revision. - 3. Push it. - - Keep commits small, with a conventional prefix (`feat:`, `fix:`, `chore:`, - `docs:`). The prefixes become the release notes and the updater's "3 - features, 5 bug fixes" line, so a batch commit lists its changes as bullets. - - Before deleting an agent's workspace, confirm that its work is reachable from - main. Snowbound nearly lost one finished change in a workspace cleanup (it - was recovered only because Clover noticed). It later found another finished - change that had never landed. -- **Release** (optional; section 3). -- **Close** issues (section 4). -- **Report** (section 6). - -## 3. Gate and release - -- **The gate replaces the CI you don't have.** Follow `references/gate.md`, and - build one in the first session if the repo lacks it. Gate the exact revision - you're landing, never the working copy, and judge it by its exit status. -- **Releases** follow `references/release.md`. Hold pushes to main while a - release runs. - -## 4. The issue tracker - -Snowbound's maintainer thread never touched the tracker. Clover opened and -closed every issue herself, or had a separate Codex session do it in Safari. -She asked which ones to close about a dozen times ("i def didnt close issues -last time"). - -**Drive the tracker's web UI with browser use**: the in-app browser, Claude in -Chrome, or computer use. Browser use works on any forge with no setup. A CLI or -an MCP server is fine if one is already configured. The contract confirms that -tracker writes are allowed, since issues may be public. - -**Opening issues.** Every note from the owner that isn't fixed in the same turn -gets an issue, and so does every finding from a sweep, audit or follow-up. For -each one: - -1. Search the open and closed issues first. If a match exists, comment on it - instead of opening a new one. -2. Title it with the problem in the owner's terms. Keep it under ten words, with - no prefix. -3. The body holds: - - the owner's words, verbatim, with any screenshot attached; - - steps to reproduce; - - what was expected; - - the build or version it was seen in; - - links to related issues. -4. Apply the forge's existing labels. Add a "needs owner" label (or the forge's - equivalent) when a decision is theirs. -5. Report the new issue numbers alongside what each is for. - -**Closing issues.** Write `fixes #N` in the commit. Don't assume the forge -closes issues on push: after the push, or after the release if the project has -releases, reload each issue. If it's still open, close it in the browser with a -comment saying what changed, which commit or version has it, and a screenshot -for anything visible. Never close one before its fix ships. Clover was once -about to close two issues whose fixes were only in the working copy. - -**Triage every wave.** Look for duplicates, stale issues, and fixes that landed -without closing anything. Another agent once landed fixes for three issues -locally while the forge was down, and nothing reconciled the tracker -afterwards. Close not-a-bug reports with the evidence. - -**Without browser access**, notes and findings go into the state file's Queue, -each with an id. When their fixes ship, post a "close these / open these" list. - -Either way, decisions for the owner live in the state file's "Decisions owed", -each with a lean. Don't re-list them in every report. - -## 5. State that survives - -Snowbound ran through six compactions, repeated usage limits and a reboot. Usage -limits killed six agents mid-edit at once, more than once, and each resume -waited on Clover. - -- **Keep the state file current.** Rewrite it every wave instead of appending. - Snowbound's handoff file collected answered questions at the top. Keep secrets - and account identifiers out of it; point to config paths instead. -- **Keep durable rules in memory:** authorizations, boundaries and taste. Save - each one when it's given, and replace it when it's superseded. -- **After a compaction, a limit or a reboot:** - 1. Re-read the state file. - 2. List the agents that were cut off, with each one's workspace and last - checkpoint. - 3. Resume every one as soon as usage allows, telling each where its partial - work is. Never wait to be asked. - 4. Gate anything they left before landing it. -- **If the main thread stops too**, schedule a wake-up for the limit's reset - (a loop or scheduled task, if the harness has one). That way resuming - doesn't wait for the owner. -- **Budget.** Throttle new work as usage nears the owner's limit, and keep the - last few hours of usage for them: "make sure at least get a few hours so i can - send the picture". - -## 6. Talking to the owner - -- **A non-event ends the turn without a message.** That covers duplicate - "finished" notices and "still waiting" checks. Snowbound's transcript has - dozens of "Nothing new" replies. -- **Open with a status table at sign-off and on return:** running, landed, - released, installed, blocked on whom, decisions owed. Status labels and - visible long-running tasks follow `ui-review-loop`, section 5. -- **Say exactly what changed.** "did u move everything to the external drive?" - got the answer "No: only the build output had moved", a day after the move. -- **Run UI feedback rounds with `ui-review-loop`.** - -## 7. Act like the owner - -The ownership Clover felt came from habits more than from any single feature: - -- **Propose what's next, ranked and with reasons, from evidence.** A sweep over - all 23 of her real pages ranked the work, and she approved it whole. Start - what's approved. -- **Catch what nobody asked about:** - - licensing risks in fixtures; - - private data before a push; - - flaky tests that block releases; - - duplicated constants that need one home; - - data-path cost. Audit CPU and IO per action on your own schedule. "what - makes it use a whole core?" should never have to be the owner's question. -- **Push back with evidence**, and say so when a default you kept turns out - wrong. -- **Make engineering calls yourself.** Bring the owner only their own decisions, - each with a lean. -- **Keep AGENTS.md and the architecture docs current.** They are how each new - sub-agent learns the repo. -- **Schedule review and simplification passes**: "it's also worth investing now - on codebase review passes and simplification". - -## 8. Keep the machine healthy - -- **Disk.** Watch it on any large project, because builds pile up: Rust's - `target/` grows by gigabytes every wave. Snowbound's passed 150 GB, with over a - million files, which also slowed font-scanning tests by minutes. Clover ran low - on disk more than once ("bump noting that you're low on disk space"). - - Check free space and the size of the build directory every wave, and before - every build and release. - - Use one shared build directory for all agents, never a private copy per - agent. Delete scratch and finished workspaces. - - Prune the build directory between waves. - - Set a threshold, say 50 GB free. Below it, launch nothing new until you've - pruned. - - Keep a protected list (SDKs, toolchains, keys) that cleanup never touches. - Snowbound deleted the macOS 10.6 SDK, which only the 10.6 laptop could - supply, and that platform missed releases for two days. -- **CPU.** Cap concurrent heavy builds and VMs, and give releases priority. - Unthrottled link-time-optimized builds plus VMs froze Clover's Mac: "i - literally couldnt even move the mouse i had to ssh in". -- **Waiter tasks are the main agent's job.** Claude and its sub-agents tend to - start background waiters (sleep-and-poll loops, watchers, "tell me when this - build finishes") and forget them. On Snowbound, 18 stuck waiting loops - belonged to agents that had already finished, some a day old. Later Clover - found "50 running bg tasks right now". - - Every wave, list the background tasks. - - Kill any whose owner has finished or that has outlived its time limit. - - Give every wait a time limit when you start it. - - Brief sub-agents to stop their own waits before they report. -- **Prechecks.** Run these early and ask about any of them only once: - - that a freshly built binary launches (a wedged system service once hung - every launch for hours, unnoticed); - - that push credentials are loaded after a reboot; - - that signing works from your shell. -- **Other writers.** Before moving, rewriting or releasing, check for commits - and sessions that aren't yours. Snowbound caught another vendor's agent's - eight local commits that way. -- **The owner's own machine** is covered in `ux-testing`. diff --git a/users/clover/agents/skills/maintain-it/references/gate.md b/users/clover/agents/skills/maintain-it/references/gate.md deleted file mode 100644 index 71a3546d599941777a99e0934d46eb538af2c3e6..0000000000000000000000000000000000000000 --- a/users/clover/agents/skills/maintain-it/references/gate.md +++ /dev/null @@ -1,45 +0,0 @@ -# The local gate - -A solo repo with no CI still needs one command that decides whether a revision -may land. Write it in the repo's own scripting language, and keep it small. -Snowbound's working example is -[`tools/ci.py`](https://shale.paperclover.net/snowbound/tree/-/tools/ci.py). - -## What it does - -- **Gates a revision, not the working copy.** It defaults to main and takes a - revision as an argument. It checks that revision out into its own - workspace, with its own build cache, so agents' half-finished edits can't - leak in. A working-copy mode freezes the tree as it was when the run - started. -- **Holds a lock**, so two runs never share a build directory. The second run - says it is waiting. -- **Runs lanes:** format, lint with warnings as errors, tests, and a build for - each other platform the project ships. Each lane has its own time limit. -- **Skips a lane whose toolchain is missing, and says why** ("needs zig"). It - never passes that lane silently. -- **Is fast by default.** The default run finishes in minutes. Exhaustive or - fuzz-like sweeps sit behind an opt-in flag or env var. Snowbound's tests went - from about half an hour to under three minutes once its sweeps moved out. -- **Can run only what changed.** A changed-files mode runs just the lanes and - test packages that the diff from main reaches. -- **Reports failures by owner.** The output is a table of failures, each with - its first errors at file and line, so the agent whose edit broke it is - obvious. -- **Keeps logs.** Each run writes its lane logs and a machine-readable summary - into a folder, and the last twenty folders are kept. -- **Keeps the build cache under a size budget** after each run. A cache of a - million files once slowed font tests by minutes. -- **Clears env vars that tests read** before running, so the agent's own - environment doesn't change results. -- **Exits with the result.** - -## Rules around it - -- **Gate the exact revision you are about to land**, after rebasing onto main. - A green working copy proves nothing about the commit. -- **Never pipe the gate through `grep`, `awk` or `tail` to judge it.** Read its - exit status. A filtered "clean" once hid a check that had never run. -- **The release script runs the gate on the commit it is about to publish.** -- **After a usage limit or a crash, gate the cut-off agents' work before landing - any of it.** diff --git a/users/clover/agents/skills/maintain-it/references/release.md b/users/clover/agents/skills/maintain-it/references/release.md deleted file mode 100644 index 8fd25e863af352098c756053e70c5ee563393dfe..0000000000000000000000000000000000000000 --- a/users/clover/agents/skills/maintain-it/references/release.md +++ /dev/null @@ -1,54 +0,0 @@ -# Release mode - -For projects that ship builds to people. Snowbound's working example is -[`tools/release.py`](https://shale.paperclover.net/snowbound/tree/-/tools/release.py) -with [`tools/RELEASE.md`](https://shale.paperclover.net/snowbound/tree/-/tools/RELEASE.md). -It publishes every desktop platform to a folder the app's updater reads. - -## The release script - -1. **Run from a dedicated release checkout** that is moved to main before each - run. Agents' edits then can't abort it. Snowbound's first releases ran from - the shared tree and aborted twice. -2. **Refuse a dirty tree.** Publish exactly the commit main points at. -3. **Derive the version from that commit.** Snowbound uses the commit's date - in the owner's timezone plus how many commits landed that day: - `2026-09-29-r4`. The version is deterministic and needs no tags. A folder - that already exists for that commit makes the run a no-op. -4. **Run the gate on that commit.** -5. **Build each platform with the version compiled in.** Builds without a - version are dev builds and never update themselves. Split out debug - symbols, and ship them beside each archive. -6. **Sign every file and the manifest.** -7. **Write the build folder under a temporary name, then rename it.** A - published folder is immutable and never deleted. -8. **Update the history file, then the latest pointer, each by rename.** The - latest pointer only ever moves a platform forward. - -## Release notes from commits - -The manifest lists every commit since the previous published build. `feat:` -counts as a feature and `fix:` as a fix; anything else is "other". A commit -whose body is a bulleted list contributes one entry per bullet. The updater sums -these across every build the user skipped, and shows "3 features, 5 bug fixes, -and 2 other changes" with the titles. So the commit convention in the main -skill is the release-notes format: one `fix:` commit per fix, and bullets on -batch commits. - -## Around a release - -- **Hold pushes to main while a release runs.** Snowbound's release stopped - itself when main moved under it. -- **Run releases detached, as a visible task.** A two-hour limit on background - commands once killed a release that had been queued behind other builds. -- **Before the first publish, test the updater end to end**: install the old - build, publish the new one, update. Snowbound's first release shipped an - updater that rejected every download. -- **Once the updater exists, the owner's installed build changes only through - it** (see `ux-testing`, on the owner's machine). -- **After publishing:** - - close the issues whose fixes are in this release, naming the version; - - say which release first contains each fix ("am i actually updated?"). -- **Add release tooling as the project grows.** Snowbound later added signing - keys published with the README, debug-symbol archives, a crash reporter, and - a separate web deploy. Each was added when someone needed it, not up front. diff --git a/users/clover/agents/skills/maintain-it/references/state-file.md b/users/clover/agents/skills/maintain-it/references/state-file.md deleted file mode 100644 index d79975a3c9b392bce70993d757de00885ee6044d..0000000000000000000000000000000000000000 --- a/users/clover/agents/skills/maintain-it/references/state-file.md +++ /dev/null @@ -1,52 +0,0 @@ -# State file - -One file in the repo that any session or agent can resume from. Rewrite it at -every wave; history lives in commits and the tracker. The contract decides -whether it is committed or kept out of version control. It never holds secrets -or account identifiers, only the paths where config lives. - -``` -# state - -Updated . main at ; latest release ; -the owner runs . - -## Contract -- : "" → -- Budget: , . - -## How work is run -- Gate: `` (, about warm). Run it on the exact revision before landing. -- Land: , then push to /main. -- Release: `` from ``; ; publishes to . -- Agents: one workspace each under ``; shared build cache ``; each deletes its own scratch. -- Protected paths, never deleted: . -- The owner's machines: : . -- Tracker: , through ; issues close on . -- Owner-reserved: . - -## Running now -| Agent | Task (issue) | Workspace | Started | Last checkpoint | -| --- | --- | --- | --- | --- | - -## Finished, not landed -- : , ; - -## Shipped, not closed -- #N: - -## Decisions owed -1. . Options: / . Lean: . Until answered: . - -## Queue -1. (#N, or a local id when there's no tracker) -2. : blocked on | owner-reserved - -## Recovery -- After a usage limit, compaction or reboot: . -- Cleanup owed: . -``` - -"Running now" answers "what's running" before anyone asks. "Finished, not -landed" is the list that keeps finished work from being lost in a workspace -cleanup. "Decisions owed" replaces re-listing questions in every report. diff --git a/users/clover/agents/skills/orchestrate/AGENTS-orchestration-proposed.md b/users/clover/agents/skills/orchestrate/AGENTS-orchestration-proposed.md new file mode 100644 index 0000000000000000000000000000000000000000..7ee8776294d9deb0d939b85869a0b20ade408d68 --- /dev/null +++ b/users/clover/agents/skills/orchestrate/AGENTS-orchestration-proposed.md @@ -0,0 +1,39 @@ +# Proposed AGENTS.md changes + +## 1. Delete `## Orchestration` + +Nothing replaces it. The skill's description triggers on being asked to +orchestrate, maintain or run a project with sub-agents, on delegating several +tasks, and on resuming the role. The one rule every thread needs, "after +launching a sub-agent: nothing", already lives in Output Preferences. + +Where each old rule went: + +| Old rule | Skill | +| --- | --- | +| Main thread holds the plan, ownership and seam; sub-agents hold edits and deep planning | intro, §1, §3 | +| No acknowledgement or recap after launching; keep the parent run active | §10 | +| No final reply, even empty, while required work is pending | §10 | +| Review completed results, then report; surface questions with context | §1 (spot-check), §10 (questions) | +| The transcript records completed work; zero output when only queued work changed | §10 | +| Streamed tasks: none lost half-implemented; sub-agent questions surface with context | §1, §10 | +| Relay my words or another agent's over your own opinion | §10 | +| Full context and a concrete deliverable; independent agents in one message; self-review; spot-check the diff | §5, `references/brief.md`, §1 | +| Route by judgment: low / med / high | §4: model cards, account cards, and rules for adapting to quota | +| Floated ideas; a search agent only when the answer needs a lot of context | §1 | +| Run browser checks yourself | §1 | +| On request, split commits as work continues, crediting every model | §10; the trailer format stays in Jujutsu (`claude-opus-5.5`; the old example said `claude-opus-5`) | + +## 2. Add compatibility to `## Code Quality` + +You called it "project specific or a global agent change if any". As a global +rule, after the shipped-contracts paragraph: + +``` +Keep changes two-way compatible when you can: new code reads old data, and old +code reads new data. Propose a breaking or backwards-only change before making +it. +``` + +The skill's §6 says the same for orchestrated work; with this line in +AGENTS.md, §6 can shrink to a pointer. diff --git a/users/clover/agents/skills/orchestrate/NOTES.md b/users/clover/agents/skills/orchestrate/NOTES.md new file mode 100644 index 0000000000000000000000000000000000000000..c08a21c27b2cd9c243b1a41eb8b83fd09f4e8bb0 --- /dev/null +++ b/users/clover/agents/skills/orchestrate/NOTES.md @@ -0,0 +1,36 @@ +# Open questions for Clover + +1. **One editor at a time in conservative mode.** §2 lets read-only agents run + alongside, but editing agents take turns in the shared checkout. + **Lean:** keep; Snowbound's shared working copy broke builds and swept + half-edits into commits. The alternative is parallel editors on disjoint + claims. +2. **What unlocks autonomous mode.** §2 counts "you're the maintainer", "use + worktrees" and "work through the tracker". "keep shipping" triggers the skill + but unlocks nothing. **Lean:** keep that split, so a work repo never goes + autonomous on a casual phrase. +3. **State location.** `NOW.md` and `DECISIONS.md` sit where project memory + says, else `~/.local/state/orchestrate//`. The log is its own file + because `NOW.md` is rewritten and a rewrite could drop decisions. + **Lean:** keep both. +4. **jj rewrites beyond AGENTS.md's default set.** §3 lets the named rewriter + squash, rebase, restore, abandon and restore operations. **Lean:** the skill + grants it for orchestrated repos; AGENTS.md's default holds everywhere else. +5. **Default stop rule.** §7 proposes "no P1 or P2 inside the threat model; P3 + and copy batch into the next release". Your words only said to agree one up + front. **Lean:** keep it as the starting offer. +6. **"On a fork, matching upstream is usually the simpler thing."** It decided + the Claude usage endpoint, but HANDOFF doesn't say whether that rule was + yours. **Lean:** keep the clause if it's yours, otherwise cut it. +7. **Brief overlap with `ui-review-loop`.** Its `references/agent-brief.md` + shares most headings with `references/brief.md`. **Lean:** this brief is the + base; ui-review-loop's keeps the UI parts (verify block, taste calls, + screenshots) and points here. +8. **Knife facts cut from the skill:** the manifest shell-hash check (code + release or shell release) and the hot-update turn gap. **Lean:** they go in + the Knife's AGENTS.md; the turn-gap line is deleted when its fix ships. +9. **`skills/README.md`** says `orchestrate` works best with "an issue tracker + the agent can write to". **Lean:** add "in autonomous mode". +10. **First enforcement to build** from `references/safety-checklist.md`. + **Lean:** the scratch launcher and `JJ_EDITOR=false`; those cover the leaks + into your real home and the hung squash. diff --git a/users/clover/agents/skills/orchestrate/SKILL.md b/users/clover/agents/skills/orchestrate/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..52c6549b006201c9edb7713ec31435d3e771ad8b --- /dev/null +++ b/users/clover/agents/skills/orchestrate/SKILL.md @@ -0,0 +1,380 @@ +--- +name: orchestrate +description: Run a multi-agent project as its orchestrator. The top-level thread claims parts of the code for agents, routes each task to a model and account, briefs and steers sub-agents, answers their questions, gates what lands, and keeps state any session can resume from. Conservative by default (one checkout, no tracker writes, no extra worktrees); project memory or an explicit instruction unlocks autonomous mode (worktrees, tracker, releases, parallel agents). Use when asked to orchestrate, play orchestrator, maintain, own or run a project with sub-agents ("keep shipping", "work through the tracker", "you're the maintainer"); whenever you are about to delegate several tasks; and when resuming that role after a compaction, a usage limit, an app update or a reboot. Not for a single fix. +--- + +# Orchestrate + +You are the manager. The top level holds the plan, knows which agent owns which +part of the code, and watches the seams between them. Sub-agents hold the edits +and the deep planning. Clover (she/her) streams notes, screenshots and changes +of plan while work runs, and she is often away. Your job is that nothing she +says gets lost, nothing unsafe lands, and the queue keeps moving without her. + +Related: `ui-review-loop` for UI rounds and UI briefs, `ux-testing` for +evidence. The stories behind these rules are in `references/casebook.md`. + +## 1. The role + +Most of your value shows up where two streams of work meet. Agents are good at +their own task and blind to everyone else's, so the problems that slip through +are at the edges: two patches touching one interface, a screen that shows two +contradictory states, a review finding that only matters because of another +change. Watch those edges. + +- Check the work yourself. Read the diff, look at the screenshots and confirm + the commit ids. A report is a claim, not proof. Agents should review their own + work before reporting, but you still look. +- Every note she sends goes somewhere: to the agent already working in that + code, or to a small new agent. Never leave a started task half done. +- When she floats an idea, answer from what you already know. Only spawn a + research agent when the answer needs a lot of reading. +- Run browser checks yourself every so often, so a long session doesn't quietly + break features that already worked. +- Propose what comes next, ranked, and say why. Push back when the evidence says + so, and say plainly when one of your own calls was wrong. + +## 2. Modes + +Most repos are not set up for an agent to run wild in. The default mode is +careful, and the autonomous mode has to be switched on. Both modes share the +core of this skill: claiming parts of the code for agents (§3) and routing work +to the right model (§4). + +- **Conservative (the default).** Work in the one checkout you started in. + Editing agents take turns there, while read-only agents (searches, reviews) + can run alongside them. The issue tracker is read-only. Don't create new + worktrees or workspaces, don't release, and don't commit or push unless she + asks. +- **Autonomous.** Each editing agent gets its own workspace or worktree, so + editors run in parallel. You may write to the tracker using the shale MCP when + applicable. You may release, within the publishing permission recorded for the + project. One agent at a time may rewrite history (§3). +- **Switching it on.** Autonomous mode needs either a project memory that + records the unlock with her words and the date, or an explicit instruction in + this thread (examples: "you're the maintainer" = permission to push, "use + worktrees" = permission to make more checkouts, "triage the issue tracker" = + permission to mutate issue tracker). An instruction that names one capability + unlocks only that one. When she unlocks something in the thread, save it as a + project memory. With neither, stay conservative. Note that it means you could + be given partial autonomy. + +Generally, these modes are to allow not stepping outside of the strict review +that the company's main project would have, while allowing smaller projects to +be given fuller control. + +"Full auto" is the short term to allow all permissions, which implies you should +ship your changes as you build them. This is useful for projects where `main` is +stabilized and the product has few users, and the main form of user testing is +to just load the new build for real. + +## 3. Ownership + +Parallel agents only work when they don't step on each other. Think of the +codebase as a set of claims: every running agent owns some files, directories or +patches, and nobody else edits them. You keep the map, and you try to keep as +much of the code claimed as you can, so agents stay busy without colliding. + +- Keep the map in `NOW.md` (§11): every running agent, plus Clover and you, with + what each owns and where its checkout is. +- Claim before launching. Each brief names the agent's claim and the + neighbouring claims it must not touch. A file has one editor at a time. Give + an overlapping task to the agent already there, or queue it. +- Shared seams (types, schemas, lockfiles, generated files) have one owner. + Others ask for changes through you. +- When a claim frees up, look at the queue again for work that fits the + unclaimed parts, and launch it. +- Only one agent rewrites history at a time. Folding, rebasing, squashing, + abandoning and restoring operations all belong to the rewriter named in + `NOW.md`; everyone else commits on top in their own workspace. Rewrites from + several workspaces at once create divergent changes. Hand the role over + explicitly. A `jj` wrapper that locks rewriting commands is one way to enforce + this. The rewriter may use the commands in `references/jj.md`, beyond + AGENTS.md's default set. +- An agent that was cut off keeps its claim until you've checked what it left. +- Know where every checkout is. `t3_worktree_list` and `jj workspace list` show + them, and each one goes in `NOW.md`. +- Clean up after yourself. Delete the scratch work the orchestration created + once it's done: workspaces whose commits are in the stack or deliberately + abandoned, temp directories, scratch servers, waiting loops. Never delete + anything you didn't create. + +## 4. Routing + +As of writing, Claude models tend to do better at UI/UX and attention to detail, +and OpenAI models do better at headless, precise engineering and at review. They +complement each other, so use both. We generally have more Codex tokens than +Claude tokens, and a large supply of each, but using less lets us do more, +either in parallel or over time. Reviewers from Claude and OpenAI tend to catch +different things, while different tiers within one lab tend to share the same +blind spots. + +Breakdown: + +- **Opus 5.5:** Strong, creative, attentive, and has a bit of taste. At low, + medium and high it is a great worker; at xhigh and max it will blow your mind. + UI prototypes and extremely intricate designs deserve max Opus. It has few + weaknesses, but it is the most expensive and the scarcest in our token + budgets. +- **GPT-6.1 Sol:** Strong and precise. Spots edge cases better than most. Good at + backend. It can make correct architectural decisions while working from + open-ended instructions, but don't use it mainly as a planning agent. + Otherwise it is in the same class as Opus at coding, with the lab differences + above. Run it at high, xhigh or max. +- **Sonnet 5.5:** A great worker that reliably finishes a task with a set goal. + Not creative, and not going to come up with incredible solutions. Run it at + medium, high or xhigh. +- **GPT-6 Astra:** Sol with a bit more knowledge and experience, at about 5× the + cost. It will catch things Opus and Sol miss. Usually run it at medium or + high; when usage is abundant, higher levels can pay off in the right + situation. +- **Haiku 5.5 and GPT-6 Luna:** Low-cost models that are still smart enough for + any well-scoped task with only one obvious way to do it. Capable, but not + smart: don't trust them to make any choice. Great for writing long scripts or + grinding through tedious processes that would cost you, or a more expensive + agent, many commands, lots of writing or other token spend. The Claude vs + OpenAI observations apply here too, but are harder to measure, so treat these + two as interchangeable. + +Relative cost within each lab, since each lab's quota is separate: + +- Claude: Haiku is about a quarter of Sonnet, and Opus about twice Sonnet. +- Codex: Luna is the cheapest, then Sol, and Astra is about 5× Sol. + +General setup for my accounts. Each lab has its own usage limits. We usually get +more firepower from OpenAI Codex, especially because the company hands out +random "usage resets" that bring the meter back to 100%. + +- Claude: Work and Home, both with large quotas. +- Codex: Tri and Work, both with large quotas, and Home, a free account. Don't + use Home. + +Every account listed above is fair game. Ask before using any account that isn't +listed. `references/accounts.md` has the details. + +Adapting: + +- **Check before you launch.** The app's usage view (the sidebar meters and the + Usage limits popover) shows each account's remaining percentage and when it + resets. `orchestrator_capabilities` shows which instances can run right now. + Instance ids change when accounts are re-shared, and leftover duplicates show + "not authenticated". +- **Reading is most of the cost.** Most usage goes to long agents rereading + large contexts, so shorter, well-scoped agent runs save more than switching to + a cheaper model. +- **Match the effort to the judgement needed.** Raise it for design and hard + fixes, lower it for mechanical work. +- **Review across labs.** A reviewer from a different lab than the builder + catches more. When one lab is short on quota, the other lab takes the reviews. +- **Spend the quota that resets soonest first,** since whatever is left at the + reset is wasted. +- **Move work off an account near its limit.** An agent that hits a limit stops + mid-task, so give long tasks and history rewrites to an account with headroom. +- **When your own account runs low,** keep your replies short and push reading + into agents on other accounts. +- **When work waits on a reset,** schedule a wake-up for it, so it resumes + without waiting on her. + +## 5. Briefs + +A sub-agent starts with nothing but its brief. Anything you know and don't write +down, it doesn't know. Templates, including the one for UI agents, are in +`references/brief.md`. Launch independent agents in one message. + +- Quote her words exactly, then say how you read them. Paraphrasing loses what + she cared about. +- Name the exact tree by commit id, and ask the agent to report the ids it + tested. A check run on a different tree proves nothing about this one. +- State the agent's claim (§3). +- Point the agent at the project's AGENTS.md for project rules, and only add the + rules this task needs (§8). +- Delegated agents run in the foreground only and never receive background + notifications. If one has to wait, give it a cheap polling loop with a time + limit. +- Cap the length of its report. Reading reports is a big part of your cost. +- Ask it to review its own work before reporting: a cleanup pass on the diff, + every wait stopped, its scratch deleted. +- Each review round is a new `delegate_task` with its own `clientRequestId`, + carrying the original brief, the earlier findings, the responses and anything + still disputed. Otherwise a fresh reviewer argues over settled points. +- When the scope changes, steer an implementation agent mid-run with + `t3_thread_send mode=steer`. Never steer a review round; start the next one + instead. + +## 6. Deciding and asking + +You should ask for her opinion, but you also have a lot of agency to decide what +is obvious. She would rather not be asked "should we use the better approach?" +The scary direction is expanding scope, not improving quality. + +- Decide obvious calls yourself. A call is obvious when her words, a logged + decision or one of the patterns below settles it, or when one option is + clearly stronger. +- Always take the stronger, more resilient implementation. +- Between two equally strong designs, do the simpler one: fewer moving parts. +- Ask before expanding scope: new features, new surfaces, or anything that would + reopen an expensive gate. If scope would reopen a gate, decline it and find a + way around. +- Keep changes compatible in both directions when you can: new code reads old + data, and old code reads new data. Add optional keys that old decoders ignore; + never extend a closed union. Propose breaking or backwards-only changes rather + than making them. +- Answer agents' questions yourself (`t3_pending_request_list`, or questions in + their reports) when the rules above settle them, and log each decision (§11). +- Patterns that settle common questions: + - Trust boundaries: use the trust model she stated for the project, kept in + memory. + - Damaged data: read what's usable. + - She answers "leans": every lean is approved. + - Processes of unknown origin: never signal a process you can't prove you own. + Anything unknown stays stopped, with an honest notice. + - Duplicates and leftovers: move the references over, then retire the copy. + Never delete data a native tool owns. +- Get a second opinion from an Opus or Sol reviewer at high or xhigh for: + - security trade-offs: consent, grants, network egress, credentials; + - anything that could lose data: migrations, record schemas, removing + compatibility for shipped data; + - risky subsystems the project names, hard designs and hard fixes. +- Ask Clover about: + - release gates: setting the stop rule, or waiving one; + - irreversible or outward-facing actions beyond what she's authorized: + publishing, pushing, messaging people, deleting anything outside scratch; + - scope expansion, taste, and any call that depends on how likely something is + to change; + - trade-offs she pays for: download size, money, time; + - anything on her machines, including when to apply an update; + - names and public-facing words; + - whether something odd is expected; + - anything her words and these patterns don't settle. + +## 7. Gates and releases + +A review can always find one more edge case. Without an agreed finish line, +review rounds go on and on while she waits. Decide what "good enough to ship" +means before the first round, not after the ninth. + +- Before the first review round, agree the threat model and the stop rule with + her. A good starting offer: ship when no P1 or P2 finding remains inside the + threat model, and batch P3 and copy findings into the next release. +- Batch P3 and copy findings, and check copy changes yourself. Neither deserves + a full review round. +- The tested tree is the shipped tree, by commit id. Builds, end-to-end runs and + the review can run in parallel before the gates close, but only publish the + commit that was tested. +- Risky subsystems need an isolated end-to-end run on the exact tree, plus a + review. These are the ones whose failure strands her, like an updater or + anything that migrates her data. The project's AGENTS.md names them. +- Before removing compatibility or touching migrations, check what has actually + shipped by reading live data, read-only. Run an update-path test over shipped + states before every publish. +- Judge a check by its exit status, never by filtered output. +- When a test fails, reproduce it on the base before blaming the change. +- She can waive a gate once she understands the risk. Offer it as an + AskUserQuestion with a concrete risk statement and a recommended option, then + tell her what to avoid until the fix ships. +- Ship often. Release finished fixes while the rest is still landing. +- Before rewriting history or releasing, check for commits from other writers: + hers, and other threads'. +- When she wants to apply an update cleanly, hold new launches and tell her once + nothing is running. +- Tell her which release first contains each fix. + +## 8. Safety + +Rules pasted into every brief cost tokens and still get forgotten. Safety +belongs in places agents can't skip: the project's AGENTS.md, which every agent +reads, and enforcement that holds whether or not they remember. + +- Put safety rules in the project's AGENTS.md and enforce them with tools: + hooks, sandbox writable roots, wrapper commands (such as a one-command scratch + server launcher), and harnesses that take their own locks. Never paste a + safety block into briefs. +- Briefs carry only the task's own rules, such as "don't fold while the + end-to-end run on `` is going". +- When an agent breaks a rule, clean up, note it in `NOW.md`, and propose the + AGENTS.md line or enforcement that would have stopped it. + `references/safety-checklist.md` lists what a project should cover. +- Keep her machine usable. Cap heavy parallel builds and VMs. Give every wait a + time limit, and stop the waiters you started once they're done. Cleanup never + touches the protected list: SDKs, toolchains, her data. + +## 9. Trouble + +- **"event stream closed unexpectedly" during a review:** retry as a new task + with a new `clientRequestId` on a working instance, and tell it to reuse the + partial work. +- **An agent cut off by a restart, an update or a usage limit:** look at its + checkout and `jj op log`, then relaunch with the original brief plus "you were + cut off at X". Check what it left before landing anything. +- **An agent silent for a long time:** check whether it's waiting for a + notification. If it is, cancel it and relaunch it foreground-only. +- **She says a bug is "still" broken:** first check which build produced her + logs. +- **A release breaks her machine:** revert the offending patch as its own change + on the tested tree, release that, and list the agents you cancelled in + `NOW.md` so they can be relaunched. +- **A test suite takes longer than one tool call allows:** split the test files + into lists, run each list in the foreground, and add up the results. +- **Checking a credential:** make real calls that print only status codes, never + the token. + +## 10. Talking to Clover + +Her Output Preferences apply. On top of them: + +- After launching agents, say nothing. Keep the run alive, and never send a + final reply, even an empty one, while required work is pending. A non-event, + like a duplicate "finished" or "still waiting", ends the turn without a + message. +- The transcript records finished work, never queued work. +- Lead with what she'll see. Label status precisely: queued, running, landed, + published, installed. Only claim what you've confirmed. +- Ask few questions, batched and numbered, each with your lean, or use + AskUserQuestion with the recommended option first. When passing on an agent's + question, include its context. +- Relay her words or another agent's words over your own opinion. +- Every visual change comes with screenshots or a video, which you check first. + She loves seeing them. Shipping doesn't wait for her to look. +- A mistake gets one plain line, last, with how it was fixed. +- She is often away. Keep the queue moving, and only ping her for real blockers. +- When she asks, split commits as the work continues, crediting every model with + `Assisted-by`. + +## 11. State and resuming + +Your context will get compacted, and the summary keeps the gist but loses the +details: task ids, commit ids, and her exact words. Write those down where you +can find them again. Keep the state files outside the repo, at the path the +project memory records. If none is recorded, use +`~/.local/state/orchestrate//`. + +- **`NOW.md`** is rewritten, never appended to, whenever a launch, a landing or + a claim changes. Its main reader is you after a compaction. It holds: + - a first line with the tip commit, the latest release, and her machines' + versions; + - `## Owners`: one line per owner (a task id with its model and account, + Clover, or you), with its claim, checkout path, goal and last checkpoint, + then `Rewriter: `; + - `## Queue`: ranked, one line each; + - `## Waiting on Clover`: numbered questions, each with your lean; + - `## Scratch`: workspaces, temp directories and servers to delete when + they're done. +- **`DECISIONS.md`** gets one line appended per decision: + `- : . Clover: ""`. +- **Memories** hold the durable rules: authorizations (verbatim and dated), the + mode unlock, boundaries, account permissions, taste. Replace a memory when + it's superseded. +- **The tracker** (autonomous mode) is the backlog. Feedback on work in flight + stays in the thread; later items go to the tracker. Search before opening an + issue, and close it only once the fix ships. +- **The first autonomous session** records in memory what may be published and + where, which accounts agents may use, which machines they may touch, and what + stays hers. +- **Resuming** after a compaction, a usage limit, an update or a reboot: + 1. Read the memories, `NOW.md`, and the end of `DECISIONS.md`. + 2. Run `task_status` on each task id in `NOW.md`, and list the cut-off agents + with their checkout and last checkpoint. + 3. Answer any pending requests. + 4. Relaunch each cut-off agent as soon as usage allows, without waiting to be + asked. + 5. Check what they left before landing anything. diff --git a/users/clover/agents/skills/orchestrate/references/accounts.md b/users/clover/agents/skills/orchestrate/references/accounts.md new file mode 100644 index 0000000000000000000000000000000000000000..d12cbf4900aff2b821e56ebcbdaecb60a5190678 --- /dev/null +++ b/users/clover/agents/skills/orchestrate/references/accounts.md @@ -0,0 +1,24 @@ +# Accounts + +As of 2026-10-22. Plans, limits and instance ids change. Before routing, check +`orchestrator_capabilities` for which instances are live and authenticated, and +the app's usage view for what's left in each window and when it resets. Update +a card when it's wrong. + +Every account below except Clover Home Codex is fair game, with standing +permission. Ask before using any account that isn't listed here. + +- **Clover Home Claude.** A setup token, with a five-hour session window and a + weekly window. The orchestrator usually lives here, so it tends to run low + first. +- **Clover Work Claude.** A setup token with a large quota. +- **Clover Work Codex.** Pro 100. Clover says it resets around 2 AM. +- **Tri Codex.** Pro 200. +- **Clover Home Codex.** The free plan, with Luna and legacy models only. Don't + use it. +- **Also available, unused so far:** a self-hosted Qwen through Codex, and + Antigravity's Gemini Flash. + +A re-shared account comes back under a new instance id (`codex-personal` became +`codex-yf324204uu`), and the old entry lingers as "not authenticated". Route to +the authenticated one. diff --git a/users/clover/agents/skills/orchestrate/references/brief.md b/users/clover/agents/skills/orchestrate/references/brief.md new file mode 100644 index 0000000000000000000000000000000000000000..287f50ca66a8ede2b009bd177013e24f785ea875 --- /dev/null +++ b/users/clover/agents/skills/orchestrate/references/brief.md @@ -0,0 +1,79 @@ +# Agent briefs + +Two shapes: one for building, one for each review round. Keep the headings and +fill in the angle brackets. UI agents use `ui-review-loop`'s brief, with this +brief's Checkout and Claim sections. + +## Build brief + +``` +You own **** in . The user is Clover (she/her). +Read /AGENTS.md and first; its rules apply in full. + +## Checkout + (jj workspace ), on . +Conservative mode instead: , shared with Clover and the orchestrator; you are its only editor until you report. + +## Clover's words (verbatim) +"" +The job, as I read it: . + +## What it looks like now +- + +## Decisions already made +- () + +## Deliverable +1. : +N. Anything else in your area that clearly breaks: fix it, without adding features beyond this list. + +## Claim +You own: . +Others own: , one line each. Don't edit those; ask through the orchestrator. +History: commit on top in your own workspace. .> + +## Rules for this task +- is going"> +- Foreground only: background notifications never reach you. Poll cheaply with a timeout. + +## Verify +- Test on , and report the commit ids you tested. +- Probes that count effects: <"one click sends exactly one request", "the end-to-end row passes 3/3">. +- Visual changes: screenshots or a video, at . +- Before reporting: a cleanup pass on your diff, every wait you started stopped, your scratch deleted. + +## Report (≤ lines) +- Per item: done / skipped (why). +- Change and commit ids, and the exact tree you tested. +- Evidence paths: logs, screenshots, videos. +- Anything you touched outside your claim and scratch. +- Questions, each with a lean. +``` + +## Review round brief + +A new `delegate_task` per round, with its own `clientRequestId`. + +``` +Review round of in . The user is Clover (she/her). +Diff: → , in . Read-only: edit nothing, rewrite nothing. +Read /AGENTS.md first. + +## Threat model and stop rule (agreed with Clover, ) +Threat model: +Stop rule: +Out of scope: <…> + +## History +- Original brief: +- Round findings: +- Responses: | accepted as temporary: why | disputed: why> +- Unresolved objections: <…> +Don't reopen findings marked resolved or accepted unless the diff changed them. + +## Report (≤ lines, also written to ) +- Verdict: SHIP | BLOCK, against the stop rule. +- Per prior finding: RESOLVED (how you checked) | OPEN. +- New findings: id, severity, file:line, failure scenario. P3 and copy as one batched list. +``` diff --git a/users/clover/agents/skills/orchestrate/references/casebook.md b/users/clover/agents/skills/orchestrate/references/casebook.md new file mode 100644 index 0000000000000000000000000000000000000000..6df6ceae1c604a4106d21a1c3f6dfa99504cb36b --- /dev/null +++ b/users/clover/agents/skills/orchestrate/references/casebook.md @@ -0,0 +1,132 @@ +# Casebook + +What happened behind the rules, for anyone curious. Nothing here is needed to +follow the skill. Projects: **the Knife**, Clover's fork of T3 Code with its +own updater and background holder processes (October 2026); **Snowbound**, a +OneNote remake one thread maintained for ten days. Quotes are Clover's. + +## The role + +- **Seams.** On the Knife, the orchestrator saw that the Tools patches touched + the adapters hot-update relies on, which became a test scenario; found that + the update dialog said "interrupted" because orchestrator turns are never + handed off; and caught a banner showing two contradictory delivery lines. +- **Say when your call was wrong.** The orchestrator recommended dropping a + compatibility shim without checking live data, and her Devices page went + empty. + +## Modes + +- Clover, on scope: "i dont want orchestrate to activate in [a work repo] and + then the agent starts messing with issue tracker and worktrees and stuff." + The core stays shared because "the core theory of locking parts of the code + and routing to different models is the meat of the skill." + +## Ownership + +- **Keep the code claimed.** Clover: "the top level needs to ensure that as much + of the codebase is locked as possible, re-checking the queue for tasks that + slot into the gaps." +- **One rewriter.** Knife agents rewriting one jj store from several workspaces + made divergent changes. A shared `mkdir` lock fixed it; Clover preferred the + orchestrator knowing who works on what. +- **Own workspace per editor.** Snowbound's one shared working copy broke builds + for hours and swept half-edits into commits. +- **Confirm reachability before forgetting.** Snowbound nearly lost a finished + change by forgetting its workspace. + +## Routing + +- **Reading is the cost.** On 2026-10-21, on Clover Home Claude, Opus subagents + used 84% of the day's usage and the orchestrator 14%; Sonnet came to 1%, and + 230 Haiku test sessions to under 1%. Nearly all of it was cache reads by long + agents rereading large contexts. +- **Limits mid-task.** Clover Home Claude hit 12% with hours to go. Clover Work + Codex hit its limit mid-rebase; the agent failed with nothing changed. +- **Live instance ids.** Re-sharing an account renamed `codex-personal` to + `codex-yf324204uu`, and the old entry stayed listed as "not authenticated". + +## Briefs + +- **The exact tree.** A Knife release gate ran its updater end-to-end matrix on + one commit while the release tip had added the Tools patches, so the gate + proved nothing about what shipped. +- **Foreground only.** Two Knife agents stalled waiting for a background + notification that never came. +- **Steering.** "No Host rewriting, real host header" landed mid-build as a + steer. +- **Safety in AGENTS.md.** v1 pasted a 13-line safety block into every brief. + Clover: "you shouldn't be wasting your tokens re-emitting this block." + +## Deciding and asking + +- **Obvious calls.** Clover: "i am glad i dont have to go 'yeah obviously we + should use the better approach' … i will ALWAYS appreciate a stronger and more + resilient implementation. expanding scope is the scarier one." +- **Trust model.** Knife: "computer to computer, trust the main port, permission + for other ports in the browser." It answered two agent questions without + asking her. +- **Declining scope behind a gate.** A stderr channel for one fix would have + changed the holder protocol and reopened the full matrix plus a review; + structured errors detected the same failure. +- **Do the simpler thing.** It decided the Claude usage endpoint: match + upstream. +- **Security escalation.** A Knife review blocked on four P1s, including proxy + egress reaching the LAN and a lease renewing without fresh approval. + +## Gates and releases + +- **Stop rule up front.** The Knife updater took 12 fix rounds because the + reviewer kept finding the next ring: protocol-1 notices, then advice copy, + then damaged-record copy. +- **Prove shipped state.** Dropping a scope shim broke decoding of her shipped + auth rows and emptied Devices; a consolidation renumbered migrations her + database had already recorded. +- **Exit status.** A filtered "clean" once hid a check that never ran. +- **Reproduce on the base.** Thirteen server failures in unchanged tests + reproduced on the original source: the environment. +- **Waivers.** She chose "Publish it now" over a third review round, and was + told not to use keyed Tools servers with Codex until the next update. +- **Ship often.** Knife wave 1 (fixes) went out while wave 2 (UI) was still + folding. + +## Safety + +- An agent ran read-only `git config` in a jj repo. +- Two updater harness runs shared one home, port and bundle id, and killed each + other. +- A bare `jj squash --into` opened an editor and hung the agent. +- An inherited `TMPDIR` and `CLAUDE_CONFIG_DIR` leaked a scratch server into the + agent's real profile, and 315 MB of build temp into her real home. +- Scratch servers without their own home wrote test identities into her real + `~/.knife`. +- An agent copied a scratch Claude credential into a fixture, then disclosed and + removed it. +- Closed literal unions (the icon colors) break old decoders when extended. +- **Machine load.** On Snowbound, stale waiter loops piled up (18 belonged to + finished agents; later "50 running bg tasks"). Unthrottled builds plus VMs + froze her Mac: "i literally couldnt even move the mouse." Deleting the macOS + 10.6 SDK cost a platform two days of releases. + +## jj stack + +- **A deep fold.** Squashing a commit into a patch far below it cascaded + conflicts through 26 commits, because it depended on later patches. +- **Frozen snapshot.** Adding a workspace at an obsolete commit unhid its + ancestors and made the stack divergent. + +## Trouble + +- **"Still" broken.** Her laptop sat on an old build; "it was just the updater". +- **A release broke her machine.** Applying a Knife update hung her app and + cancelled every delegated task. The hotfix reverted the offending patch on the + tested tree and released that. +- **A long suite.** The Knife's server tests run serially and outlast a + 10-minute tool call, so they run as file-list chunks. + +## Talking to Clover + +- **Screenshots.** Spot-checking them caught the banner copy and a test thread + showing an auth failure. Clover: "screenshots and videos are always awesome to + see i just love seeing them." +- **Confidence.** "it should not be confident if it doesn't know." diff --git a/users/clover/agents/skills/orchestrate/references/jj.md b/users/clover/agents/skills/orchestrate/references/jj.md new file mode 100644 index 0000000000000000000000000000000000000000..4476ce3ea1653e6aa7589c63b4e3a0d828f4f973 --- /dev/null +++ b/users/clover/agents/skills/orchestrate/references/jj.md @@ -0,0 +1,76 @@ +# jj recipes for a shared stack + +Rewrites (squash, rebase, restore, abandon, `op restore`, `workspace +update-stale`) are run only by the agent `NOW.md` names as the rewriter. Other +agents run `jj new`, `jj describe` and `jj commit` in their own workspace. +Always pass `-m '…'` or `--use-destination-message`; a bare `squash` or +`describe` opens an editor and hangs. Checked against jj 0.42. + +## Stack rules + +- Fold every fix into its owning patch. No "fix after review" commits. +- Fold into the lowest patch where the change compiles. A fold below a patch it + depends on cascades conflicts through every commit in between. +- Fold only when no end-to-end run is active; a fold changes the tree under it. +- Until the release ships, park fixes on top as `WIP: fold into : …`, + so the tested tree doesn't move. + +## An agent's workspace + +``` +jj workspace add /-ws- -r +``` + +Before `jj workspace forget`, confirm its commits are reachable from the stack +(`jj log -r ''`) or deliberately abandoned. Then delete the +directory. + +## Folding a fix into its owner + +``` +jj log -r '::' # other agents' "fold into " WIPs get rebased into conflicts +jj squash --from --into --use-destination-message +jj st # conflicts: stop and undo (below) +``` + +When unsure, park it and fold during the next rebase: + +``` +jj describe -r -m 'WIP: fold into : ' +jj rebase -r -A +``` + +## Undoing your own mistake + +``` +jj op log # only your operations since the bad one? +jj op restore # then restore +``` + +If another agent's operation came after, use `jj op revert ` for just +yours, or repair by hand. `jj op undo` doesn't exist here. + +## Keeping a frozen tree + +A fold below a frozen snapshot (a hotfix base, a tested tree) rebases it and +can move its tree. Restore it right after the fold: + +``` +jj restore --from --into +``` + +## Scratch workspace at a frozen snapshot + +Create it before folding. `jj workspace add -r ` unhides that +commit's old ancestors and turns the stack divergent; use a live change with +the same tree instead. Afterwards, `jj workspace forget` it, abandon its +commit, and delete the directory. + +## After an interruption + +``` +jj workspace update-stale +jj log -r 'description(substring:"")' # two copies of one commit? +jj diff --git -r # keep the one with the edits +jj abandon +``` diff --git a/users/clover/agents/skills/orchestrate/references/safety-checklist.md b/users/clover/agents/skills/orchestrate/references/safety-checklist.md new file mode 100644 index 0000000000000000000000000000000000000000..cc3f548df7d89776bf427c9d2ab1232360a882fa --- /dev/null +++ b/users/clover/agents/skills/orchestrate/references/safety-checklist.md @@ -0,0 +1,50 @@ +# Safety checklist for a project + +What a project's AGENTS.md should state, and how to enforce each item so it +holds when an agent forgets. Every enforcement here is a suggestion; none is +built yet. A rule that only a brief repeats will be forgotten. + +- **Version control.** AGENTS.md: which VCS; in a jj repo, never `git`, not even + read-only. Enforce: a hook that denies `git` when the repo has `.jj`, or a + `git` shim on agents' PATH that refuses there. +- **One history rewriter.** AGENTS.md: only the agent the orchestrator names + rewrites history. Enforce: a jj wrapper that takes a lock for rewriting + commands, or the orchestrator's ownership map alone. +- **Commands that open an editor.** AGENTS.md: always `-m` or + `--use-destination-message`. Enforce: `JJ_EDITOR=false` in agents' env, so a + bare `squash` fails instead of hanging. +- **Clean environments.** AGENTS.md: servers, tests and builds start from + `env -i` with their own `TMPDIR`, home and config dirs; agents check a + server's env (`ps eww`) before clicking anything that writes. Enforce: a + one-command scratch launcher that sets all of that, picks a free port, and + records the PID. +- **No-touch trees.** AGENTS.md: the paths agents may read but never write (her + real app data, credentials, `/Applications`, installer caches). Enforce: + sandbox writable roots that exclude them, or a hook on writes and deletes. +- **Processes.** AGENTS.md: signal only PIDs you started; never kill by pattern; + never touch her running app or its helpers. Enforce: a hook that denies + `pkill` and `killall`; a stop command in the scratch launcher that reads its + recorded PIDs. +- **Exclusive harnesses.** AGENTS.md: which harnesses allow one run at a time. + Enforce: the harness takes its own lock and refuses a second run. +- **Secrets.** AGENTS.md: no secrets in logs, output or tracked files; never + copy a credential into a fixture; check a credential by printing status codes + only. Enforce: a secret scan in the pre-publish gate. +- **Private names.** AGENTS.md: no employer names in tracked files. Enforce: a + denylist check in the pre-publish gate. +- **Model turns in tests.** AGENTS.md: Claude Haiku or Codex Luna only. Enforce: + the test harness rejects other model ids. +- **Shipped-data compatibility.** AGENTS.md: synced or persisted records stay + two-way compatible: optional keys old decoders drop, no additions to a closed + union. Enforce: a test that decodes fixtures captured from shipped versions. +- **Risky subsystems.** AGENTS.md: which subsystems need an isolated end-to-end + run on the exact tree plus a review before release. Enforce: the release + script refuses a tree without a passing run recorded for that commit. +- **Credits.** AGENTS.md: `Assisted-by: ` trailers, one per model, never + `Co-authored-by`. Enforce: a trailer check in the pre-publish gate. +- **Machine load.** AGENTS.md: caps on parallel builds, VMs and waits. Enforce: + the scratch launcher runs heavy jobs under `nice` with a job cap, and every + wait helper takes a timeout. +- **Protected paths for cleanup.** AGENTS.md: what cleanup never deletes (SDKs, + toolchains, her data). Enforce: cleanup deletes only under recorded scratch + roots. diff --git a/users/clover/agents/skills/sol-loop/SKILL.md b/users/clover/agents/skills/sol-loop/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..6b6892db436c5dfc3443f06569aaca89d7d1f902 --- /dev/null +++ b/users/clover/agents/skills/sol-loop/SKILL.md @@ -0,0 +1,119 @@ +--- +name: sol-loop +description: Use when the user says "sol loop". +--- + +# sol-loop + +This is a workflow for making your code changes more correct before (or +sometimes after) filing a pull request. tl;dr - use OpenAI's GPT Sol to review +your code in a loop. + +Make the most minimal possible changes to appease the Sol reviewers. Be careful +of scope creep and don't be scared to push back. + +## Budget + +- Default: 3 rounds total. Round 1 is full. Later rounds check only + changed code and open findings. +- Extend to 5 only for security, permissions, auth, data loss, or + state/concurrency, while a blocker or should stays open with evidence. Or when + the user asks. +- Stop early if a round returns only nits. Declined nits and comment, + doc, or format-only fixes need no new round. +- One reviewer only. Sol must not start subagents or reviewers. +- Keep a ledger: id, severity, outcome, usage if returned. Never guess it. + +## 1. Scope + +Run `git status --short`. Do not stash, discard, or include unrelated +changes. Limit review to the change paths if they separate cleanly. +Otherwise stop and ask. + +Find the base after `git fetch origin`: + +- PR: `gh pr view --json baseRefName,headRefOid`. Check out the branch + only if clean. Confirm `HEAD` is the PR head, or ahead only by this + change. Base: `git merge-base HEAD origin/`. +- Local: `git merge-base HEAD origin/`. No remote: a base + the user names, or `HEAD` for uncommitted changes only. + +The change is base to working tree in those paths, with untracked files. +Use one diff command all rounds. State intent and out-of-scope in 1-2 +sentences. Run covering checks. Do not send code this change breaks. Note +missing or pre-failing checks in the brief. + +## 2. Start Sol + +In T3, call `orchestrator_capabilities`. Pick the latest Sol unless the user +named a version. Do not hardcode an ID. Record provider, model, and effort +only if exposed. Use `delegate_task` every round (`role: "review"`, +`mode: "async"`). Save `taskId`. New `clientRequestId` per round. +`childThreadId` is storage, not the next target. Do not use +`t3_thread_send`, `create_threads`, or `t3_thread_launch` for review. + +If T3 tools are not listed, try one direct capability call. Outside T3, use +a native Sol subagent and keep its ID. In Claude Code, use a custom subagent +only if it is set up to run Sol. If no route runs Sol, report the blocker. Do +not substitute a model. + +Do not edit scoped files while review runs. Wait for the notice. Do not +poll or start a second reviewer. Timeout, error, or no reply is not +approval. On failure, cancel, verify stop, restart with the ledger. + +Round 1 brief (T3 children get no history): + +``` +Review only. Do not edit, commit, push, comment on PRs, or start subagents. +Repo: Base: Intent: Out of scope: Checks: +See: git diff [-- ]; git status --short (read untracked). +Read surrounding code. Find bugs, broken callers, mismatch with intent. +Skip style unless it hides a bug. Hold to the smallest change. Flag code, +tests, or guards the intent does not need. Other paths, rare cases, small +perf, extra compat: nits. +blocker = intended case wrong. should = real bug callers will hit, in intent. nit = rest. +Reply: +VERDICT: APPROVE or CHANGES +S1 [blocker|should|nit] : . Fix: (stable ids) +``` + +## 3. Answer findings + +Check each finding and severity yourself. Another path, rare case, or +small cost is a nit, whatever label it came with. + +- Agree: smallest fix. Prefer delete or narrow over new lock, cache, + helper, or option. Fix the case that happened. Add one focused test + that fails without the fix, if intent needs it. +- Disagree: say why, with evidence (file:line, test, output). +- Out of scope or nit: decline in one line. List as follow-up. + +Update the ledger. Re-run checks and `git diff --shortstat `. If +review grew the diff, cut first. Do not agree just to end the loop. + +## 4. Next round + +Start one only if budget remains and a blocker or should is open, behavior code +changed, or approval does not cover the current behavior diff. Use a fresh +`delegate_task` in T3, or follow up the saved native ID. Send the round 1 brief, +the ledger (`fixed:` / `disagree:` / `declined:` + evidence), the same base +diff, and the change since last round. Tell Sol: open ids and changed code only. +Mark each old id `resolved` or `still open: `. + +## 5. Stop and ship + +Agreed: APPROVE on the current behavior diff, no blocker or should open, +no concern of your own. Stuck: an item stays disputed after two replies, +or budget ends. Show both sides in 2-3 lines each. The user decides. +Budget end is not approval. + +Do not push during the loop. Push after agreement only if the user asked +to push, ship, or update the PR. If you push to a PR, add above the model +blurb: + +`Reviewed with sol-loop: rounds with . Sol verdict: approved`. + +Add `on ` only if verified. + +Report: rounds, model, what Sol changed, diff size before/after, fixed and +declined findings with reasons, usage if exposed (else say not), pushed or not. diff --git a/users/clover/agents/skills/ui-review-loop/SKILL.md b/users/clover/agents/skills/ui-review-loop/SKILL.md index 43432bbf92e947d1bab0cb15f3f1d776d4a91c69..77f2f9fa40fad4be83afafeffac4f9e2aa07ad61 100644 --- a/users/clover/agents/skills/ui-review-loop/SKILL.md +++ b/users/clover/agents/skills/ui-review-loop/SKILL.md @@ -75,7 +75,7 @@ Use `references/agent-brief.md`. These parts made briefs land: - **Decisions already made.** - **Ownership.** Assign it by function, CSS section or data array, and list who else edits what. One agent owns each UI surface; others hand off to it. Give - each agent its own checkout where possible (see `maintain-it`). If they share + each agent its own checkout where possible (see `orchestrate`). If they share one, they make small targeted edits and re-read on conflict. - **Hard rules:** - the repo's own version-control and safety rules, from its AGENTS.md or diff --git a/users/clover/home.nix b/users/clover/home.nix index 549c234a79f5c8cb59712a6bdd9b52b346285f9a..9f49deaa0a11441352db5e6d32fa4e3298b965f6 100644 --- a/users/clover/home.nix +++ b/users/clover/home.nix @@ -89,16 +89,38 @@ in config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/ui-review-loop"; home.file.".codex/skills/ui-review-loop".source = config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/ui-review-loop"; - home.file.".claude/skills/maintain-it".source = - config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/maintain-it"; - home.file.".codex/skills/maintain-it".source = - config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/maintain-it"; + home.file.".claude/skills/orchestrate".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/orchestrate"; + home.file.".codex/skills/orchestrate".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/orchestrate"; home.file.".claude/skills/accessibility".source = config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/accessibility"; home.file.".codex/skills/accessibility".source = config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/accessibility"; - home.file.".codex/skills/shale-issues".source = - config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/shale-issues"; + home.file.".claude/skills/full-send".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/full-send"; + home.file.".codex/skills/full-send".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/full-send"; + home.file.".claude/skills/full-stop".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/full-stop"; + home.file.".codex/skills/full-stop".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/full-stop"; + home.file.".claude/skills/babysit-pr".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/babysit-pr"; + home.file.".codex/skills/babysit-pr".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/babysit-pr"; + home.file.".claude/skills/leaving-pr-comments".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/leaving-pr-comments"; + home.file.".codex/skills/leaving-pr-comments".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/leaving-pr-comments"; + home.file.".claude/skills/sol-loop".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/sol-loop"; + home.file.".codex/skills/sol-loop".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/sol-loop"; + home.file.".claude/skills/file-pr".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/file-pr"; + home.file.".codex/skills/file-pr".source = + config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/file-pr"; home.file.".claude/skills/openai-docs".source = config.lib.file.mkOutOfStoreSymlink "${config.home.homeDirectory}/.codex/skills/.system/openai-docs"; home.file.".codex/skills/update-config".source = diff --git a/users/clover/jujutsu.nix b/users/clover/jujutsu.nix index 5864c7085753d6e540433ba8f04b484ac78f2b1d..597656c3964bcfdf2bf2325add95603b53a47125 100644 --- a/users/clover/jujutsu.nix +++ b/users/clover/jujutsu.nix @@ -9,6 +9,11 @@ postBuild = '' rm "$out/bin/jj" cp ${pkgs.writeShellScript "jj" '' + ${lib.optionalString pkgs.stdenv.isDarwin '' + if [[ -t 0 && -t 1 && -z "''${SSH_CONNECTION-}''${SSH_CLIENT-}''${SSH_TTY-}" ]]; then + set -- '--config=--scope=[{ "--when".commands = ["diff"], ui.diff-formatter = "knife", ui.paginate = "never" }]' "$@" + fi + ''} for arg in "$@"; do case "$arg" in desc|describe) @@ -94,6 +99,11 @@ muted = "bright black"; }; ui.default-command = lib.mkForce "show"; + merge-tools.knife = lib.mkIf pkgs.stdenv.isDarwin { + program = "/Applications/Knife Diff.app/Contents/MacOS/knife-code"; + diff-args = [ "$left" "$right" ]; + edit-args = [ "--edit" "$left" "$right" ]; + }; # ui.graph.style = "square"; revsets = { short-prefixes = "(trunk()..@)::"; diff --git a/users/clover/packages/agent-linear/agent-linear.js b/users/clover/packages/agent-linear/agent-linear.js index ddbcd0a708d26ab649ed61bcc0ac75ab0ba6f37d..f5db988c109cd410b8b640457d3f432c45574e54 100644 --- a/users/clover/packages/agent-linear/agent-linear.js +++ b/users/clover/packages/agent-linear/agent-linear.js @@ -267,11 +267,30 @@ async function runJj([executable, ...argv]) { } async function startIssues(text, onlyUnclaimed = false) { + const prefixesPath = path.join( + process.env.XDG_CONFIG_HOME || path.join(process.env.HOME, ".config"), + "agent-linear", + "prefixes", + ); + let prefixes; + try { + prefixes = new Set( + fs.readFileSync(prefixesPath, "utf8").toUpperCase().split(/\r?\n/) + .map((prefix) => prefix.trim()).filter(Boolean), + ); + } catch (error) { + if (error.code === "ENOENT") { + return []; + } + throw error; + } + const issues = new Set( [...text.matchAll( /(? match[0].toUpperCase()), + .map((match) => match[0].toUpperCase()) + .filter((id) => prefixes.has(id.split("-", 1)[0])), ); const messages = []; @@ -621,6 +640,8 @@ function usage(code) { stream.write(`\n`); stream.write(`api key: ~/.config/linear-api-key or LINEAR_API_KEY\n`); stream.write(`scope: only runs from numbered work repos under ~/dev\n`); + stream.write(`auto-start prefixes: $XDG_CONFIG_HOME/agent-linear/prefixes (default: ~/.config/agent-linear/prefixes)\n`); + stream.write(`one prefix per line, e.g. ALPHA; missing or empty disables auto-start in Claude, Codex, and jj desc\n`); process.exit(code); } diff --git a/users/clover/packages/agent-linear/agent-linear.test.cjs b/users/clover/packages/agent-linear/agent-linear.test.cjs new file mode 100644 index 0000000000000000000000000000000000000000..a3c02615d304aa8e1a66a99764cc078b81402654 --- /dev/null +++ b/users/clover/packages/agent-linear/agent-linear.test.cjs @@ -0,0 +1,125 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { test } = require("node:test"); +const vm = require("node:vm"); + +const source = fs.readFileSync(path.join(__dirname, "agent-linear.js"), "utf8"); + +async function run(t, { prefixes, text, command = "prompt", xdg = false, assigned = false }) { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "agent-linear-test-")); + t.after(() => fs.rmSync(home, { recursive: true, force: true })); + const config = xdg ? path.join(home, "custom-config") : path.join(home, ".config"); + if (prefixes !== undefined) { + fs.mkdirSync(path.join(config, "agent-linear"), { recursive: true }); + fs.writeFileSync(path.join(config, "agent-linear", "prefixes"), prefixes); + } + if (xdg) { + fs.mkdirSync(path.join(home, ".config", "agent-linear"), { recursive: true }); + fs.writeFileSync(path.join(home, ".config", "agent-linear", "prefixes"), "WRONG\n"); + } + + const requests = []; + const output = []; + const context = vm.createContext({ + require(name) { + if (name === "node:fs") { + return { + ...fs, + readFileSync(file, encoding) { + return file === 0 + ? JSON.stringify({ hook_event_name: "UserPromptSubmit", prompt: text }) + : fs.readFileSync(file, encoding); + }, + }; + } + if (name === "node:child_process") { + return { + spawnSync(executable, argv) { + assert.equal(executable, "jj"); + const stdout = argv.includes("log") + ? argv.at(-1) === "description" ? text : "change-id\n" + : ""; + return { status: 0, stdout }; + }, + }; + } + if (name === "node:process") { + return { + argv: ["node", "agent-linear", ...( + command === "jj" ? ["jj", "jj", "desc", "-m", text] : ["prompt"] + )], + env: { HOME: home, LINEAR_API_KEY: "test", ...(xdg ? { XDG_CONFIG_HOME: config } : {}) }, + stdout: { write: (value) => output.push(value) }, + exit: (code) => assert.fail(`unexpected exit ${code}`), + }; + } + return require(name); + }, + console: { error: (value) => output.push(value) }, + AbortSignal, + async fetch(url, options) { + assert.equal(url, "https://api.linear.app/graphql"); + const { query, variables } = JSON.parse(options.body); + requests.push({ query, variables }); + const data = query.includes("IssueProgress") + ? { issue: { + id: variables.id, + state: { name: "Todo" }, + assignee: assigned ? { id: "someone" } : null, + team: { states: { nodes: [{ id: "started", name: "In Progress", type: "started" }] } }, + } } + : query.includes("issueUpdate") + ? { issueUpdate: { success: true } } + : { viewer: { id: "viewer", name: "Clover" } }; + return { ok: true, text: async () => JSON.stringify({ data }) }; + }, + }); + + await vm.runInContext(source, context); + return { requests, output: output.join("") }; +} + +for (const command of ["prompt", "jj"]) { + test(`${command}: only configured prefixes start issues`, async (t) => { + const { requests, output } = await run(t, { + command, + prefixes: " alpha \r\nBETA\r\n\r\n", + text: "ALPHA-12 alpha-12 beta-3 GAMMA-4 XALPHA-5 ALPHA-6suffix ALPHA-7-8 ALPHA-8.1 _ALPHA-9 https://linear.app/team/issue/ALPHA-10/title", + }); + assert.deepEqual( + requests.filter(({ query }) => query.includes("IssueProgress")).map(({ variables }) => variables.id), + ["ALPHA-12", "BETA-3", "ALPHA-10"], + ); + assert.equal(requests.filter(({ query }) => query.includes("issueUpdate")).length, 3); + assert.match(output, /ALPHA-12 → In Progress/); + }); + + for (const prefixes of [undefined, "", "\n \r\n"]) { + test(`${command}: ${JSON.stringify(prefixes)} configuration disables automatic requests`, async (t) => { + const { requests, output } = await run(t, { command, prefixes, text: "ALPHA-123 OTHER-456" }); + assert.deepEqual(requests, []); + assert.equal(output, ""); + }); + } +} + +test("XDG_CONFIG_HOME overrides the default directory; prefixes are literal", async (t) => { + const { requests } = await run(t, { + xdg: true, + prefixes: "ALPHA\nB.*\n", + text: "ALPHA-1 BETA-2 WRONG-3", + }); + assert.deepEqual( + requests.filter(({ query }) => query.includes("IssueProgress")).map(({ variables }) => variables.id), + ["ALPHA-1"], + ); +}); + +test("prompts leave assigned issues alone; jj descriptions still start them", async (t) => { + for (const command of ["prompt", "jj"]) { + const { requests } = await run(t, { command, prefixes: "ALPHA", text: "ALPHA-1", assigned: true }); + assert.equal(requests.some(({ query }) => query.includes("issueUpdate")), command === "jj"); + } +}); diff --git a/users/clover/packages/workspaces/README.md b/users/clover/packages/workspaces/README.md deleted file mode 100644 index c84286b29d3d8c50f8c99e8e2ea7974a28fa4756..0000000000000000000000000000000000000000 --- a/users/clover/packages/workspaces/README.md +++ /dev/null @@ -1,100 +0,0 @@ -# Workspaces - -Requires macOS/APFS and T3 Code nightly with orchestrator V2. The source repo is -configured locally in `~/.config/workspaces.json`. - -```sh -ws setup /path/to/source-workspace -ws new # next available number, freshly fetched origin/main -ws new search -r some-change # ~/workspaces/search, with a fresh T3 chat -ws open search # reopen and renew the chat's claim -ws deps search # reconcile dependencies after changing revisions -ws gc --dry-run # show blockers; update grace observations -``` - -Raycast's **New Workspace** command runs `ws new --background`. Its managed script lives in -`~/.config/raycast/scripts`; register that folder in Raycast's Script Commands -settings once. Each workspace has its own T3 project, named after the source -project followed by ` | `, with the same logo. Additional chats -in that project use the same workspace folder. - -`ws new` and `ws open` accept `--no-open` to bind the chat without navigating -the desktop app. `ws new --json` returns `{workspacePath, projectId, threadId, -environmentId}` for callers that navigate the resulting chat themselves. By -default, standard output is the workspace path; setup progress goes to -standard error. The chat opens in an empty folder before fetching or creating -the JJ workspace; `--background` returns without waiting for preparation. -Claude and Codex startup and prompt hooks wait for the workspace to be ready. -Setup failures block the prompt until `ws deps ` succeeds. -New chats can be opened while another workspace prepares; preparation and -cleanup share a separate lock. Local T3 authentication is cached for one -minute with a two-minute token, and renewed when the server restarts. -Background preparation writes `~/Library/Logs/workspace-.log`. A failed -setup stays protected: run `ws deps ` and `ws open ` to finish it. - -```text -reserve empty folder → create and open T3 thread - → fetch origin/main → add JJ workspace → checkout → clone snapshot → pnpm install - → release waiting Claude/Codex hooks - -Every 30 seconds: - T3 verifies settled, quiet chats with linked PRs all merged → archive chats - unfinished setup / unarchived T3 chat / running work / VS Code / live shell cwd - → keep workspace, reset grace - no references for ≥60 seconds, with a fresh check immediately before removal - → JJ snapshot → JJ workspace forget → remove directory - unavailable API, untracked VS Code window, unreadable cwd, unexpected state - → keep workspaces, reset grace -``` - -Settling a chat keeps its workspace directory. Cleanup begins only after every -chat using the directory is archived or deleted and no work is running. Archival -releases the directory for cleanup; settling does not. Automatic archival uses -T3 Code's guarded merge check and retains chats with open, closed, or missing PRs. -An unavailable completion check pauses cleanup. `ws gc --dry-run` never archives chats. - -When a chat settles, T3 captures that workspace's current JJ change with -`ws settle`; resuming clears its capture with `ws unsettle`. `ws completion` -reports abandonment only for that same settlement, when its captured change has -no visible version, the current working change is empty, and its ancestry has -no nonempty work introduced since the captured repository operation. Rebased -changes, missing captures, and later work—even beneath an empty tip—retain the directory. These atomic -per-thread records bypass the preparation lock and are removed with the workspace. - -Only registered workspaces under `~/workspaces` are collected. JJ retains -snapshotted changes; ignored files are deleted with the directory. Closing T3 -pauses cleanup. VS Code's companion extension reports live folders and documents -through a local socket; windows without a responding tracker block cleanup. -Shell hooks register workspace shells, and cleanup reads their live cwd, -including terminals opened before the hooks were installed. - -Default creation fetches only `main` from `origin` and starts at `main@origin`. -An explicit `-r` skips the fetch. Source checkout files remain untouched, even -when stale. Managed checkouts update automatically; fetching does not abandon -unrelated commits in the shared repo. - -The dependency key includes package manifests, the lockfile, pnpm workspace -configuration, patches, pnpm version, platform, architecture, and Node ABI. -`clonefile` shares file data without sharing writable inodes. pnpm then -regenerates launchers containing absolute paths. One cached snapshot is kept; -changing the dependency key replaces it. - -Build and verify against a downloaded nightly CLI: - -```sh -cc -Wall -Wextra -Werror native.c -o /tmp/workspace-native -T3_TEST_CLI=/path/to/nightly/t3 WORKSPACE_TEST_NATIVE=/tmp/workspace-native \ - node --test --test-isolation=none workspaces.test.mjs -``` - -The lifecycle test starts an isolated nightly server, uses real JJ and pnpm, -checks clone isolation and launcher relocation, and verifies preservation of JJ -file contents after cleanup. VS Code process status is a fixture; its reference -socket and the terminal cwd probe are live. The lock test verifies overlap -rejection and release after process exit. - -`workspaces-hooks.test.mjs` tests the installed Claude and Codex CLIs against -a local API stub. Set `WORKSPACE_TEST_CLAUDE`, `WORKSPACE_TEST_CODEX`, and -`WORKSPACE_TEST_HOOK_PYTHON` (Python with tomlkit). It verifies that early prompts -wait, setup failures prevent model requests, and instructions created during -preparation reach the first model request. It makes no external model calls. diff --git a/users/clover/packages/workspaces/configure-hooks.py b/users/clover/packages/workspaces/configure-hooks.py deleted file mode 100644 index 5dea8c9c692e98dee9337e25e8a47725c9ddff65..0000000000000000000000000000000000000000 --- a/users/clover/packages/workspaces/configure-hooks.py +++ /dev/null @@ -1,103 +0,0 @@ -import json -import os -from pathlib import Path -import select -import subprocess -import sys - -import tomlkit - -home = Path(sys.argv[1]) -command = sys.argv[2] -codex = sys.argv[3] - - -def write(file, contents): - if file.exists() and file.read_text() == contents: - return - file.parent.mkdir(parents=True, exist_ok=True) - temporary = file.with_name(file.name + ".workspace-hook.tmp") - temporary.write_text(contents) - os.chmod(temporary, file.stat().st_mode & 0o777 if file.exists() else 0o600) - os.replace(temporary, file) - - -for provider, filename in [("claude", "settings.json"), ("codex", "config.toml")]: - file = home / ("." + provider) / filename - if provider == "claude": - settings = json.loads(file.read_text()) if file.exists() else {} - else: - settings = tomlkit.parse(file.read_text()) if file.exists() else tomlkit.document() - - if "hooks" not in settings: - settings["hooks"] = {} - for event in ["SessionStart", "UserPromptSubmit"]: - hook = { - "type": "command", "command": command, "timeout": 300, - "statusMessage": "Preparing workspace", "async": False, - } - if provider == "claude": - hook["onFailure"] = "block" - groups = settings["hooks"].get(event) - if groups is None: - settings["hooks"][event] = [{"hooks": [hook]}] - else: - existing = next((item for group in groups for item in group["hooks"] - if item.get("command") == command), None) - if existing is None: - groups.append({"hooks": [hook]}) - else: - existing.update(hook) - - contents = json.dumps(settings, indent=2) + "\n" if provider == "claude" else tomlkit.dumps(settings) - write(file, contents) - - if provider != "codex": - continue - - with subprocess.Popen([codex, "app-server", "--stdio"], stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0, - env={**os.environ, "CODEX_HOME": str(file.parent)}) as server: - try: - def request(request_id, method, params): - message = {"id": request_id, "method": method, "params": params} - server.stdin.write((json.dumps(message) + "\n").encode()) - while select.select([server.stdout], [], [], 15)[0]: - line = server.stdout.readline() - if not line: - break - response = json.loads(line) - if response.get("id") != request_id: - continue - if "error" in response: - raise RuntimeError(response["error"]) - return response["result"] - raise RuntimeError("Codex did not confirm workspace hook configuration") - - request(1, "initialize", { - "clientInfo": {"name": "workspace-hook-installer", "version": "1"}, - "capabilities": {"experimentalApi": True}, - }) - server.stdin.write(b'{"method":"initialized"}\n') - listed = request(2, "hooks/list", {"cwds": [str(home)]}) - hooks = [hook for entry in listed["data"] for hook in entry["hooks"] - if hook.get("command") == command - and hook["eventName"] in ["sessionStart", "userPromptSubmit"] - and hook["sourcePath"] == str(file)] - if len(hooks) != 2: - raise RuntimeError("Codex did not load both workspace readiness hooks") - - settings = tomlkit.parse(file.read_text()) - if "state" not in settings["hooks"]: - settings["hooks"]["state"] = {} - for hook in hooks: - settings["hooks"]["state"][hook["key"]] = { - "trusted_hash": hook["currentHash"], "enabled": True, - } - write(file, tomlkit.dumps(settings)) - finally: - server.terminate() - try: - server.wait(timeout=5) - except subprocess.TimeoutExpired: - server.kill() diff --git a/users/clover/packages/workspaces/default.nix b/users/clover/packages/workspaces/default.nix deleted file mode 100644 index 81041db8ffdc3cfc7c41111c66b65d2c47064768..0000000000000000000000000000000000000000 --- a/users/clover/packages/workspaces/default.nix +++ /dev/null @@ -1,29 +0,0 @@ -{ pkgs, ... }: -let - native = pkgs.runCommandCC "workspace-native" { } '' - mkdir -p $out/bin - $CC ${./native.c} -o $out/bin/workspace-native - ''; -in -pkgs.writeShellApplication { - name = "ws"; - runtimeInputs = with pkgs; [ - nodejs_26 - jujutsu - pnpm_10 - native - ]; - text = '' - case "''${1-}" in - ready-hook|settle|unsettle|completion) - exec node ${./workspaces.mjs} "$@" - ;; - esac - mkdir -p "$HOME/.local/state/workspaces" - workspace_lock="$HOME/.local/state/workspaces/lock" - if [[ "''${1-}" == new ]]; then - workspace_lock="$HOME/.local/state/workspaces/creation-lock" - fi - exec workspace-native lock "$workspace_lock" node ${./workspaces.mjs} "$@" - ''; -} diff --git a/users/clover/packages/workspaces/extension/extension.js b/users/clover/packages/workspaces/extension/extension.js deleted file mode 100644 index c0612719807754d8217916dc92475b0fbd31e863..0000000000000000000000000000000000000000 --- a/users/clover/packages/workspaces/extension/extension.js +++ /dev/null @@ -1,33 +0,0 @@ -const vscode = require("vscode"); -const fs = require("node:fs"); -const net = require("node:net"); -const os = require("node:os"); -const path = require("node:path"); - -function activate(context) { - const directory = path.join(os.homedir(), ".local/state/workspaces/vscode"); - fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); - const socket = path.join(directory, `${process.pid}.sock`); - fs.rmSync(socket, { force: true }); - - const server = net.createServer((client) => { - const uris = [ - ...(vscode.workspace.workspaceFolders ?? []).map((folder) => folder.uri), - ...vscode.workspace.textDocuments.map((document) => document.uri), - vscode.workspace.workspaceFile, - ]; - const paths = uris.filter((uri) => uri?.scheme === "file").map((uri) => - uri.fsPath - ); - client.end(JSON.stringify({ pid: process.pid, paths }) + "\n"); - }); - server.listen(socket); - context.subscriptions.push({ - dispose() { - server.close(); - fs.rmSync(socket, { force: true }); - }, - }); -} - -module.exports = { activate }; diff --git a/users/clover/packages/workspaces/extension/package.json b/users/clover/packages/workspaces/extension/package.json deleted file mode 100644 index 596d83076f397c9817c4975e9e57df775e8157ec..0000000000000000000000000000000000000000 --- a/users/clover/packages/workspaces/extension/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "workspace-references", - "displayName": "Workspace References", - "description": "Keeps open VS Code folders safe from workspace cleanup.", - "publisher": "clover", - "version": "0.0.1", - "engines": { "vscode": "^1.74.0" }, - "main": "./extension.js", - "extensionKind": ["ui"], - "activationEvents": ["*"], - "capabilities": { "untrustedWorkspaces": { "supported": true } } -} diff --git a/users/clover/packages/workspaces/native.c b/users/clover/packages/workspaces/native.c deleted file mode 100644 index 3722533a4de0fc78379ca84349b69bb873c57214..0000000000000000000000000000000000000000 --- a/users/clover/packages/workspaces/native.c +++ /dev/null @@ -1,39 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -int main(int argc, char **argv) { - if (argc >= 4 && (strcmp(argv[1], "lock") == 0 || - strcmp(argv[1], "wait-lock") == 0)) { - int fd = open(argv[2], O_CREAT | O_RDWR, 0600); - if (fd < 0) { - perror("Cannot open workspace lock"); - return 1; - } - int flags = LOCK_EX | (strcmp(argv[1], "lock") == 0 ? LOCK_NB : 0); - if (flock(fd, flags) < 0) { - if (errno != EWOULDBLOCK) { - perror("Cannot lock workspaces"); - return 1; - } - fprintf( - stderr, - "Another workspace command is running. Retry when it finishes.\n"); - return 1; - } - execvp(argv[3], argv + 3); - perror("Cannot start workspace command"); - return 1; - } - if (argc != 4 || strcmp(argv[1], "clone") != 0) - return 2; - if (clonefile(argv[2], argv[3], - CLONE_NOFOLLOW | CLONE_NOOWNERCOPY | CLONE_ACL) == 0) - return 0; - perror("Cannot clone dependencies"); - return 1; -} diff --git a/users/clover/packages/workspaces/shell.zsh b/users/clover/packages/workspaces/shell.zsh deleted file mode 100644 index 77fba91b1986bc15a7764a8311ed5df02a51e542..0000000000000000000000000000000000000000 --- a/users/clover/packages/workspaces/shell.zsh +++ /dev/null @@ -1,15 +0,0 @@ -function _workspace_reference() { - local directory="$HOME/.local/state/workspaces/shells" - if [[ "$PWD" == "$HOME/workspaces/"* ]]; then - mkdir -p "$directory" - print -r -- "$PWD" > "$directory/$$" - else - [[ ! -e "$directory/$$" ]] || rm -f "$directory/$$" - fi -} - -autoload -Uz add-zsh-hook -add-zsh-hook chpwd _workspace_reference -add-zsh-hook precmd _workspace_reference -add-zsh-hook preexec _workspace_reference -_workspace_reference diff --git a/users/clover/packages/workspaces/workspaces-hooks.test.mjs b/users/clover/packages/workspaces/workspaces-hooks.test.mjs deleted file mode 100644 index bcc4112217014035b2c6f646d8dca3e235701127..0000000000000000000000000000000000000000 --- a/users/clover/packages/workspaces/workspaces-hooks.test.mjs +++ /dev/null @@ -1,144 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import fs from "node:fs"; -import path from "node:path"; -import http from "node:http"; -import childProcess from "node:child_process"; -import { once } from "node:events"; -import { fileURLToPath } from "node:url"; - -const script = fileURLToPath(new URL("./workspaces.mjs", import.meta.url)); -const installer = fileURLToPath(new URL("./configure-hooks.py", import.meta.url)); -const python = process.env.WORKSPACE_TEST_HOOK_PYTHON; - -for (const provider of ["codex", "claude"]) { - const executable = process.env[`WORKSPACE_TEST_${provider.toUpperCase()}`]; - test(`${provider} holds a real prompt until preparation, including repository instructions`, { - skip: !executable || !python, - timeout: 45_000, - }, async () => { - const home = fs.realpathSync(fs.mkdtempSync("/tmp/workspaces-hooks-")); - const workspace = path.join(home, "workspaces/pending"); - const record = path.join(home, ".local/state/workspaces/workspaces/pending.json"); - fs.mkdirSync(workspace, { recursive: true }); - fs.mkdirSync(path.dirname(record), { recursive: true }); - fs.writeFileSync(record, JSON.stringify({ prepared: false })); - - const invoked = path.join(home, "hook-invoked"); - const wrapper = path.join(home, "hook.mjs"); - fs.writeFileSync(wrapper, `import fs from "node:fs"; -import childProcess from "node:child_process"; -fs.writeFileSync(${JSON.stringify(invoked)}, "started"); -const child = childProcess.spawn(process.execPath, [${JSON.stringify(script)}, "ready-hook"], { stdio: "inherit" }); -child.on("exit", (code) => { process.exitCode = code ?? 1; }); -`); - const command = [process.execPath, wrapper].map((value) => - "'" + value.replaceAll("'", "'\\''") + "'" - ).join(" "); - const hook = { type: "command", command, timeout: 30 }; - const hooks = { - SessionStart: [{ hooks: [hook] }], - UserPromptSubmit: [{ hooks: [hook] }], - }; - const requests = []; - const server = http.createServer(async (request, response) => { - let body = ""; - for await (const chunk of request) body += chunk; - if (request.method === "POST" && /\/(responses|messages)(\?|$)/.test(request.url)) { - requests.push(body); - } - response.writeHead(401, { "Content-Type": "application/json" }); - response.end(JSON.stringify({ error: { type: "authentication_error", message: "Fixture finished" } })); - }); - server.listen(0, "127.0.0.1"); - await once(server, "listening"); - const origin = `http://127.0.0.1:${server.address().port}`; - const codexHome = path.join(home, ".codex"); - const claudeHome = path.join(home, ".claude"); - fs.mkdirSync(codexHome); - fs.mkdirSync(claudeHome); - fs.writeFileSync(path.join(codexHome, "config.toml"), `model_provider = "fixture" -model = "gpt-6.1-sol" -[model_providers.fixture] -name = "Fixture" -base_url = "${origin}/v1" -wire_api = "responses" -requires_openai_auth = false -request_max_retries = 0 -stream_max_retries = 0 -[[hooks.SessionStart]] -[[hooks.SessionStart.hooks]] -type = "command" -command = ${JSON.stringify(command)} -timeout = 30 -[[hooks.UserPromptSubmit]] -[[hooks.UserPromptSubmit.hooks]] -type = "command" -command = ${JSON.stringify(command)} -timeout = 30 -`); - fs.writeFileSync(path.join(claudeHome, "settings.json"), JSON.stringify({ hooks })); - const env = { - ...process.env, HOME: home, CODEX_HOME: codexHome, CLAUDE_CONFIG_DIR: claudeHome, - ANTHROPIC_BASE_URL: origin, ANTHROPIC_API_KEY: "fixture", - ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", - CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_TELEMETRY: "1", - }; - const args = provider === "codex" - ? ["exec", "--json", "--sandbox", "read-only", "--skip-git-repo-check", "Say ready."] - : ["-p", "--model", "claude-sonnet-4-6", "--output-format", "json", "Say ready."]; - let child; - let output = ""; - try { - const configure = childProcess.spawn(python, [ - installer, home, command, process.env.WORKSPACE_TEST_CODEX, - ], { env }); - let configuredOutput = ""; - configure.stderr.on("data", (chunk) => { configuredOutput += chunk; }); - const [configuredStatus] = await once(configure, "exit"); - assert.equal(configuredStatus, 0, configuredOutput); - child = childProcess.spawn(executable, args, { cwd: workspace, env }); - child.stdin.end(); - child.stdout.on("data", (chunk) => { output += chunk; }); - child.stderr.on("data", (chunk) => { output += chunk; }); - const exited = once(child, "exit"); - for (let attempt = 0; !fs.existsSync(invoked); attempt++) { - assert.ok(attempt < 200 && child.exitCode === null, output); - await new Promise((resolve) => setTimeout(resolve, 50)); - } - await new Promise((resolve) => setTimeout(resolve, 400)); - assert.equal(requests.length, 0, "no model request while the workspace is unprepared"); - assert.equal(child.exitCode, null, "prompt remains waiting"); - fs.writeFileSync(path.join(workspace, "AGENTS.md"), "WORKSPACE_READY_INSTRUCTIONS_8732\n"); - fs.writeFileSync(record, JSON.stringify({ prepared: true })); - for (let attempt = 0; requests.length === 0; attempt++) { - assert.ok(attempt < 300 && child.exitCode === null, output); - await new Promise((resolve) => setTimeout(resolve, 50)); - } - assert.match(requests[0], /WORKSPACE_READY_INSTRUCTIONS_8732/); - child.kill("SIGKILL"); - await exited; - - fs.rmSync(invoked); - requests.length = 0; - fs.writeFileSync(record, JSON.stringify({ prepared: false, preparationError: "fixture setup failed" })); - output = ""; - child = childProcess.spawn(executable, args, { cwd: workspace, env }); - child.stdin.end(); - child.stdout.on("data", (chunk) => { output += chunk; }); - child.stderr.on("data", (chunk) => { output += chunk; }); - await once(child, "exit"); - assert.ok(fs.existsSync(invoked), output); - assert.equal(requests.length, 0, "a setup failure blocks the model request"); - if (provider === "codex") assert.match(output, /"input_tokens":0/); - else assert.match(output, /setup stopped|resend your prompt/); - } finally { - if (child?.exitCode === null && child.signalCode === null) { - child.kill("SIGKILL"); - await once(child, "exit"); - } - await new Promise((resolve) => server.close(resolve)); - fs.rmSync(home, { recursive: true, force: true, maxRetries: 3 }); - } - }); -} diff --git a/users/clover/packages/workspaces/workspaces.mjs b/users/clover/packages/workspaces/workspaces.mjs deleted file mode 100644 index 8a890d35e6a62f7424481b51d46aa83ca06a4bd9..0000000000000000000000000000000000000000 --- a/users/clover/packages/workspaces/workspaces.mjs +++ /dev/null @@ -1,992 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import os from "node:os"; -import net from "node:net"; -import { createHash, randomUUID } from "node:crypto"; -import childProcess from "node:child_process"; -import { fileURLToPath } from "node:url"; - -const home = fs.realpathSync(os.homedir()); -const root = path.join(home, "workspaces"); -const state = path.join(home, ".local/state/workspaces"); -const cache = path.join(home, ".cache/workspaces/deps"); -const configFile = path.join(home, ".config/workspaces.json"); -const records = path.join(state, "workspaces"); -const t3Home = process.env.T3CODE_HOME ?? path.join(home, ".t3"); - -function run(command, args, cwd, inherit = false) { - if (command === "jj") { - args = ["--config", "snapshot.auto-update-stale=true", ...args]; - } - - return childProcess.execFileSync(command, args, { - cwd, - encoding: "utf8", - stdio: inherit ? ["ignore", 2, 2] : ["ignore", "pipe", "pipe"], - timeout: inherit ? undefined : 30_000, - })?.trim(); -} - -function writeJson(file, value) { - fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); - const temporary = `${file}.${process.pid}.tmp`; - fs.writeFileSync(temporary, JSON.stringify(value) + "\n", { mode: 0o600 }); - fs.renameSync(temporary, file); -} - -function alive(pid) { - try { - process.kill(pid, 0); - return true; - } catch (error) { - if (error.code === "ESRCH") return false; - throw error; - } -} - -function inside(candidate, directory) { - const relative = path.relative(directory, candidate); - return relative === "" || - (!relative.startsWith(`..${path.sep}`) && relative !== ".." && - !path.isAbsolute(relative)); -} - -function canonical(file) { - try { - return fs.realpathSync(file); - } catch (error) { - if (error.code === "ENOENT") return path.resolve(file); - throw error; - } -} - -function jjRepository(directory) { - const file = path.join(directory, ".jj/repo"); - return fs.statSync(file).isDirectory() ? canonical(file) : canonical( - path.resolve(path.dirname(file), fs.readFileSync(file, "utf8").trim()), - ); -} - -function workspace(id) { - if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(id)) { - throw new Error( - "Choose a workspace name containing letters, numbers, underscores, or hyphens.", - ); - } - return path.join(root, id); -} - -export async function t3() { - const runtime = JSON.parse( - fs.readFileSync(path.join(t3Home, "userdata/server-runtime.json")), - ); - if (!Number.isInteger(runtime.pid) || !alive(runtime.pid)) { - throw new Error("Start T3 Code nightly before using workspaces."); - } - const origin = new URL(runtime.origin); - if ( - origin.protocol !== "http:" || - !["127.0.0.1", "localhost", "[::1]"].includes(origin.hostname) - ) throw new Error("Workspace cleanup needs a local T3 Code server."); - - const executable = run("/bin/ps", ["-p", String(runtime.pid), "-o", "comm="]); - const app = executable.includes("/Contents/MacOS/") - ? executable.split("/Contents/MacOS/")[0] - : null; - const cli = app - ? [ - executable, - path.join(app, "Contents/Resources/app.asar/apps/server/dist/bin.mjs"), - ] - : [executable]; - const authFile = path.join(state, "t3-auth.json"); - let authentication; - if (fs.existsSync(authFile) && Date.now() - fs.statSync(authFile).mtimeMs < 60_000) { - authentication = JSON.parse(fs.readFileSync(authFile)); - } - if (authentication?.pid !== runtime.pid) { - const token = childProcess.execFileSync(cli[0], [ - ...cli.slice(1), - "auth", - "session", - "issue", - "--base-dir", - t3Home, - "--ttl", - "2m", - "--token-only", - ], { - env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" }, - encoding: "utf8", - timeout: 15_000, - stdio: ["ignore", "pipe", "pipe"], - }).trim(); - authentication = { pid: runtime.pid, token }; - writeJson(authFile, authentication); - } - - async function request(route, body) { - const response = await fetch(new URL(route, origin), { - method: body === undefined ? "GET" : "POST", - // Synchronous JJ/pnpm calls can outlive HTTP keep-alive sockets. - headers: { - Authorization: `Bearer ${authentication.token}`, - "Content-Type": "application/json", - "x-t3-orchestration-protocol": "2", - Connection: "close", - }, - body: body === undefined ? undefined : JSON.stringify(body), - signal: AbortSignal.timeout(10_000), - }); - if (!response.ok) { - throw new Error( - `T3 Code returned ${response.status}. Cleanup is paused; check the nightly app.`, - ); - } - return response.json(); - } - - const environment = await request("/.well-known/t3/environment"); - if (environment.orchestrationProtocolVersion !== 2) { - throw new Error("Update T3 Code to a nightly build with orchestrator V2."); - } - - async function snapshot() { - const [data, archived] = await Promise.all([ - request("/api/orchestration/shell"), - rpc("orchestration.getArchivedShellSnapshot", {}), - ]); - if ( - !Array.isArray(data.projects) || !Array.isArray(data.threads) || - !Array.isArray(archived.threads) - ) { - throw new Error( - "T3 Code returned an unknown thread list. Cleanup is paused.", - ); - } - data.archivedThreads = archived.threads; - for (const thread of [...data.threads, ...data.archivedThreads]) { - if ( - ![ - "settledOverride", - "activeRunId", - "worktreePath", - "deletedAt", - "archivedAt", - "pendingRuntimeRequest", - "status", - ].every((field) => field in thread) - ) { - throw new Error( - "T3 Code returned an unknown thread state. Cleanup is paused.", - ); - } - } - return data; - } - - async function rpc(tag, payload) { - const { ticket } = await request("/api/auth/websocket-ticket", {}); - const url = new URL("/ws", origin); - url.protocol = "ws:"; - url.searchParams.set("wsTicket", ticket); - url.searchParams.set("orchestrationProtocol", "2"); - return new Promise((resolve, reject) => { - const socket = new WebSocket(url); - const timeout = setTimeout( - () => - finish( - new Error( - "T3 Code did not respond. Start the nightly app and retry.", - ), - ), - 15_000, - ); - function finish(error, value) { - clearTimeout(timeout); - socket.close(); - if (error) reject(error); - else resolve(value); - } - socket.onopen = () => - socket.send( - JSON.stringify({ - _tag: "Request", - id: "1", - tag, - payload, - headers: [], - }) + "\n", - ); - socket.onmessage = (event) => { - for (const line of String(event.data).trim().split("\n")) { - const message = JSON.parse(line); - if (message._tag !== "Exit" || String(message.requestId) !== "1") { - continue; - } - if (message.exit._tag === "Success") finish(null, message.exit.value); - else { - finish( - new Error( - `T3 Code rejected the workspace request: ${ - JSON.stringify(message.exit) - }`, - ), - ); - } - } - }; - socket.onerror = () => - finish( - new Error("Cannot reach T3 Code. Start the nightly app and retry."), - ); - socket.onclose = () => { - clearTimeout(timeout); - reject(new Error("T3 Code closed the chat connection.")); - }; - }); - } - - function dispatch(command) { - return rpc( - command.type.startsWith("project.") - ? "projects.mutate" - : "orchestration.dispatchCommand", - { commandId: randomUUID(), ...command }, - ); - } - - return { snapshot, dispatch, rpc, environment, app }; -} - -function dependencyKey(directory) { - const files = run("jj", ["--ignore-working-copy", "file", "list"], directory).split("\n").filter(( - file, - ) => - path.basename(file) === "package.json" || - ["pnpm-lock.yaml", "pnpm-workspace.yaml", ".npmrc", ".pnpmfile.cjs"] - .includes(file) || - file.startsWith("patches/") - ).sort(); - const hash = createHash("sha256"); - hash.update( - `${process.platform}:${process.arch}:${process.versions.modules}:${ - run("pnpm", ["--version"], directory) - }\0`, - ); - for (const file of files) { - hash.update(file + "\0").update(fs.readFileSync(path.join(directory, file))) - .update("\0"); - } - return hash.digest("hex"); -} - -function moduleDirectories(directory, relative = "") { - const found = []; - for ( - const entry of fs.readdirSync(path.join(directory, relative), { - withFileTypes: true, - }) - ) { - if (!entry.isDirectory() || entry.name.startsWith(".")) continue; - const child = path.join(relative, entry.name); - if (entry.name === "node_modules") found.push(child); - else found.push(...moduleDirectories(directory, child)); - } - return found; -} - -function dependencies(directory, source) { - const key = dependencyKey(directory); - let seed; - if ( - fs.existsSync(path.join(cache, "key")) && - fs.readFileSync(path.join(cache, "key"), "utf8") === key - ) seed = cache; - else if ( - dependencyKey(source) === key && - fs.existsSync(path.join(source, "node_modules/.pnpm/lock.yaml")) - ) seed = source; - if (seed) { - for (const relative of moduleDirectories(seed)) { - const target = path.join(directory, relative); - if (fs.existsSync(target) || !fs.existsSync(path.dirname(target))) { - continue; - } - run( - "workspace-native", - ["clone", path.join(seed, relative), target], - undefined, - true, - ); - } - } - - // pnpm regenerates launchers that embed the previous workspace's absolute path. - run( - "pnpm", - [ - "install", - "--frozen-lockfile", - "--prefer-offline", - "--store-dir", - path.join(home, ".local/share/pnpm/store"), - ], - directory, - true, - ); - if (dependencyKey(directory) !== key) { - throw new Error( - "Dependency files changed during installation. Run ws deps again.", - ); - } - if (seed === cache) return; - - const temporary = `${cache}.tmp`; - fs.rmSync(temporary, { recursive: true, force: true }); - fs.mkdirSync(temporary, { recursive: true }); - for (const relative of moduleDirectories(directory)) { - const target = path.join(temporary, relative); - fs.mkdirSync(path.dirname(target), { recursive: true }); - run( - "workspace-native", - ["clone", path.join(directory, relative), target], - undefined, - true, - ); - } - fs.writeFileSync(path.join(temporary, "key"), key); - fs.rmSync(cache, { recursive: true, force: true }); - fs.renameSync(temporary, cache); -} - -async function editorReferences() { - const processes = run("/bin/ps", ["-axo", "pid=,comm="]); - const instances = processes.split("\n").filter((line) => - line.endsWith("/Visual Studio Code.app/Contents/MacOS/Code") - ).map((line) => Number(line.trim().split(/\s+/, 1)[0])); - if (!instances.length) return []; - const status = run("/usr/local/bin/code", ["--status"]); - const reported = [...status.matchAll(/^\s*\d+\s+\d+\s+(\d+)\s+code\s*$/gm)] - .map((match) => Number(match[1])); - if (instances.some((pid) => !reported.includes(pid))) { - throw new Error( - "Cannot inspect every VS Code instance. Cleanup is paused.", - ); - } - const pids = [...status.matchAll(/\b(\d+)\s+extension-host\b/g)].map(( - match, - ) => Number(match[1])); - const windows = [...status.matchAll(/\bwindow \[\d+\]/g)].length; - if (pids.length < windows) { - throw new Error( - "VS Code has a window without a reference tracker. Reload its windows before cleanup.", - ); - } - const paths = []; - for (const pid of pids) { - const response = await new Promise((resolve, reject) => { - const socket = net.createConnection( - path.join(state, "vscode", `${pid}.sock`), - ); - let data = ""; - socket.setTimeout( - 2000, - () => - socket.destroy( - new Error( - "VS Code reference tracker did not respond. Reload its windows before cleanup.", - ), - ), - ); - socket.on("data", (chunk) => { - data += chunk; - }); - socket.on("end", () => { - try { - resolve(JSON.parse(data)); - } catch (error) { - reject(error); - } - }); - socket.on("error", reject); - }); - if (response.pid !== pid || !Array.isArray(response.paths)) { - throw new Error( - "Cannot verify VS Code's open folders. Reload its windows before cleanup.", - ); - } - paths.push(...response.paths.map(canonical)); - } - return paths; -} - -function terminalReferences() { - const pids = new Set(); - const processes = run("/bin/ps", ["-axo", "pid=,tty=,comm="]); - for (const line of processes.split("\n")) { - const match = line.match(/^\s*(\d+)\s+(\S+)\s+(.+)$/); - if (match && match[2] !== "??" && /\/(zsh|bash|fish|sh)$/.test(match[3])) { - pids.add(Number(match[1])); - } - } - const directory = path.join(state, "shells"); - for ( - const name of fs.existsSync(directory) ? fs.readdirSync(directory) : [] - ) { - if (!/^\d+$/.test(name)) continue; - const pid = Number(name); - if (alive(pid)) pids.add(pid); - else fs.rmSync(path.join(directory, name)); - } - if (!pids.size) return []; - - let output; - try { - output = run("/usr/sbin/lsof", [ - "-a", - "-p", - [...pids].join(","), - "-d", - "cwd", - "-Fpn", - ]); - } catch (error) { - if (error.status !== 1) throw error; - output = String(error.stdout ?? ""); - } - const found = new Set(); - const paths = []; - let pid; - for (const line of output.split("\n")) { - if (line.startsWith("p")) pid = Number(line.slice(1)); - if (line.startsWith("n")) { - found.add(pid); - paths.push(canonical(line.slice(1))); - } - } - for (const pid of pids) { - if (!found.has(pid) && alive(pid)) { - throw new Error( - `Cannot read terminal ${pid}'s folder. Cleanup is paused.`, - ); - } - } - return paths; -} - -async function references(client) { - const [snapshot, editors] = await Promise.all([ - client.snapshot(), - editorReferences(), - ]); - const projects = new Map( - snapshot.projects.map((project) => [project.id, project.workspaceRoot]), - ); - const chats = []; - for (const thread of [...snapshot.threads, ...snapshot.archivedThreads]) { - const released = thread.deletedAt !== null || thread.archivedAt !== null; - const busy = ![ - "idle", - "completed", - "interrupted", - "failed", - "cancelled", - "rolled_back", - ].includes(thread.status) || thread.activeRunId !== null || - thread.pendingRuntimeRequest !== null || - thread.pendingBackgroundTasks?.length > 0; - if (released && !busy) continue; - const directory = thread.worktreePath ?? projects.get(thread.projectId); - if (!directory) { - throw new Error( - "Cannot locate a T3 chat's workspace. Cleanup is paused.", - ); - } - chats.push(canonical(directory)); - } - return { chats, editors, terminals: terminalReferences() }; -} - -async function openChat(id, config, client, open = true) { - const directory = workspace(id); - const file = path.join(records, `${id}.json`); - const record = JSON.parse(fs.readFileSync(file)); - const snapshot = await client.snapshot(); - const repository = jjRepository(config.repository); - const source = snapshot.projects.find((project) => - canonical(project.workspaceRoot) === config.repository - ) ?? snapshot.projects.find((project) => - !inside(canonical(project.workspaceRoot), root) && - fs.existsSync(path.join(project.workspaceRoot, ".jj/repo")) && - jjRepository(project.workspaceRoot) === repository - ); - if (!source) { - throw new Error( - "Add the source repository to T3 Code before creating a workspace chat.", - ); - } - let thread = [...snapshot.threads, ...snapshot.archivedThreads].find( - (thread) => thread.id === record.threadId, - ); - if (!thread) { - let project = snapshot.projects.find((project) => - canonical(project.workspaceRoot) === directory - ); - const latest = [...snapshot.threads, ...snapshot.archivedThreads].filter( - (thread) => thread.projectId === (project?.id ?? source.id), - ).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0]; - const modelSelection = project?.defaultModelSelection ?? - source.defaultModelSelection ?? - latest?.modelSelection; - if (!modelSelection) { - throw new Error( - "Choose a model in the source repository's T3 settings, then run ws open again.", - ); - } - if (!project) { - project = await client.dispatch({ - type: "project.create", - projectId: randomUUID(), - title: `${source.title} | ${id}`, - workspaceRoot: directory, - }); - } - await client.dispatch({ - type: "project.update", - projectId: project.id, - projectIcon: source.projectIcon ?? null, - faviconPath: source.faviconPath ?? null, - defaultThreadEnvMode: "local", - defaultModelSelection: modelSelection, - }); - const threadId = record.threadId ?? randomUUID(); - record.threadId = threadId; - writeJson(file, record); - await client.dispatch({ - type: "thread.create", - threadId, - projectId: project.id, - title: project.title, - modelSelection, - runtimeMode: latest?.runtimeMode ?? "full-access", - interactionMode: latest?.interactionMode ?? "default", - branch: null, - worktreePath: null, - createdBy: "user", - creationSource: "web", - }); - const confirmed = await client.snapshot(); - thread = confirmed.threads.find((thread) => thread.id === threadId); - if (!thread) { - throw new Error( - "T3 Code has not confirmed the chat yet. Run ws open again.", - ); - } - } - if (thread.archivedAt) { - await client.dispatch({ type: "thread.unarchive", threadId: thread.id }); - } - if (thread.settledOverride === "settled") { - await client.dispatch({ - type: "thread.unsettle", - threadId: thread.id, - reason: "user", - }); - } - record.idleSince = null; - writeJson(file, record); - const environmentId = client.environment.environmentId; - if (open) { - run("/usr/bin/open", [ - ...(client.app ? ["-a", client.app] : ["-b", "com.t3tools.t3code"]), - `t3code://threads/${environmentId}/${record.threadId}`, - ]); - } - return { - workspacePath: directory, - projectId: thread.projectId, - threadId: thread.id, - environmentId, - }; -} - -export async function main(args) { - const [command, argument, ...rest] = args; - if (command === "ready-hook") { - let input = ""; - for await (const chunk of process.stdin) input += chunk; - const event = JSON.parse(input); - const directory = canonical(event.cwd); - if (!inside(directory, root)) return; - const id = path.relative(root, directory).split(path.sep)[0]; - const file = path.join(records, `${id}.json`); - if (!fs.existsSync(file)) return; - - const deadline = Date.now() + 240_000; - let waited = false; - while (true) { - const record = JSON.parse(fs.readFileSync(file)); - if (record.preparationError) { - throw new Error(`Workspace ${id} setup stopped: ${record.preparationError}. Run ws deps ${id}, then resend your prompt.`); - } - if (record.prepared) break; - if (Date.now() >= deadline) { - throw new Error(`Workspace ${id} is still preparing. Check ~/Library/Logs/workspace-${id}.log, then resend your prompt.`); - } - waited = true; - await new Promise((resolve) => setTimeout(resolve, 100)); - } - if (waited && event.hook_event_name === "SessionStart") { - const files = new Set(["AGENTS.md", "CLAUDE.md"].map((name) => - path.join(workspace(id), name) - ).filter((file) => fs.existsSync(file)).map(canonical)); - const instructions = [...files].map((file) => fs.readFileSync(file, "utf8")); - if (instructions.length) { - console.log(JSON.stringify({ hookSpecificOutput: { - hookEventName: "SessionStart", - additionalContext: instructions.join("\n\n"), - } })); - } - } - return; - } - if (!command || command === "--help") { - console.log( - "ws setup \nws new [name] [-r revision] [--no-open] [--background] [--json]\nws open [--no-open]\nws deps \nws gc [--dry-run]", - ); - return; - } - fs.mkdirSync(state, { recursive: true, mode: 0o700 }); - if (command === "setup") { - if (!argument || rest.length) throw new Error("Run ws setup ."); - const repository = fs.realpathSync( - run("jj", ["workspace", "root"], path.resolve(argument)), - ); - if (!fs.existsSync(path.join(repository, "pnpm-lock.yaml"))) { - throw new Error("Choose the repository's pnpm workspace root."); - } - if (fs.existsSync(records) && fs.readdirSync(records).length) { - const configured = JSON.parse(fs.readFileSync(configFile)); - if (jjRepository(repository) !== jjRepository(configured.repository)) { - throw new Error( - "Finish existing workspaces before changing their source repository.", - ); - } - } - writeJson(configFile, { repository }); - console.log(`Workspace source: ${repository}`); - return; - } - if ( - command === "gc" && - (!fs.existsSync(records) || !fs.readdirSync(records).length) - ) return; - const config = JSON.parse(fs.readFileSync(configFile)); - if (["settle", "unsettle", "completion"].includes(command)) { - const expectedLength = command === "unsettle" ? 2 : command === "completion" ? 5 : 4; - if ( - !argument || rest.length !== expectedLength || rest[0] !== "--thread-id" || - (command !== "unsettle" && rest[2] !== "--settled-at") || - (command === "completion" && rest[4] !== "--json") - ) { - throw new Error(`Run ws ${command} --thread-id ${ - command === "unsettle" ? "" : " --settled-at