authoravatarclover caruso<git@paperclover.net>2026-10-13 16:37:37-07:00
committeravatarclover caruso<git@paperclover.net>2026-11-13 16:28:31-08:00
log109c267af77be2317f65e6feddde30e860173573
treee6d01fd2d5f4f6a88fdf5a347593dd9fb8db19ce
parent19223a8e9d01da0e197884183f53c290fde7ab37
signature Signed by SSH key SHA256:cOKiuRFOeSRxne6EWgHtdQQSlBxjOXm2hOCFnCdLQbQ

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

42 files changed, 3214 insertions(+), 2833 deletions(-)

flake.nix+7
......@@ -75,6 +75,13 @@
7575 });
7676 })
7777
78 # Copy-on-write checkouts; exported from ~/dev/jj change trunyqzm.
79 (_: prev: {
80 jujutsu = prev.jujutsu.overrideAttrs (old: {
81 patches = old.patches or [ ] ++ [ ./packages/jujutsu/copy-on-write-checkouts.patch ];
82 });
83 })
84
7885 # custom packages
7986 (_: pkgs: {
8087 autofmt = pkgs.callPackage ./packages/autofmt { };
packages/jujutsu/copy-on-write-checkouts.patch created+828
......@@ -0,0 +1,828 @@
1diff --git a/lib/src/eol.rs b/lib/src/eol.rs
2index bfb111d3de..5eacfa4133 100644
3--- a/lib/src/eol.rs
4+++ b/lib/src/eol.rs
5@@ -49,6 +49,11 @@
6 }
7 }
8
9+ /// Whether [`Self::convert_eol_for_update()`] can change file content.
10+ pub(crate) fn converts_on_update(&self) -> bool {
11+ self.eol_conversion_mode == EolConversionMode::InputOutput
12+ }
13+
14 /// The limit to probe for whether the file is binary is 8KB.
15 /// All files strictly smaller than the limit are always
16 /// evaluated correctly and in full.
17diff --git a/lib/src/file_cache.rs b/lib/src/file_cache.rs
18new file mode 100644
19index 0000000000..be03d9ca74
20--- /dev/null
21+++ b/lib/src/file_cache.rs
22@@ -0,0 +1,169 @@
23+// Copyright 2026 The Jujutsu Authors
24+//
25+// Licensed under the Apache License, Version 2.0 (the "License");
26+// you may not use this file except in compliance with the License.
27+// You may obtain a copy of the License at
28+//
29+// https://www.apache.org/licenses/LICENSE-2.0
30+//
31+// Unless required by applicable law or agreed to in writing, software
32+// distributed under the License is distributed on an "AS IS" BASIS,
33+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
34+// See the License for the specific language governing permissions and
35+// limitations under the License.
36+
37+//! Content-addressed cache of materialized files, which checkouts clone
38+//! instead of rewriting.
39+
40+use std::collections::HashMap;
41+use std::fs;
42+use std::fs::File;
43+use std::io;
44+use std::io::Seek as _;
45+use std::path::Path;
46+use std::path::PathBuf;
47+
48+use futures::AsyncRead;
49+use tempfile::TempPath;
50+
51+use crate::file_util::copy_async_to_sync;
52+
53+/// Cache entries for one checkout. Entries it adds stay pending until
54+/// [`Self::commit()`] makes them durable with a single device flush, as Git's
55+/// `core.fsyncMethod=batch` does.
56+pub(crate) struct FileCache {
57+ dir: PathBuf,
58+ pending: HashMap<String, TempPath>,
59+}
60+
61+impl FileCache {
62+ /// Opens the cache of the repo at `repo_path`. Returns `None` where files
63+ /// can't be cloned.
64+ pub fn open(repo_path: &Path) -> Option<Self> {
65+ let dir = repo_path.join("file_cache");
66+ let supported = cfg!(target_vendor = "apple") && fs::create_dir_all(&dir).is_ok();
67+ supported.then(|| Self {
68+ dir,
69+ pending: HashMap::new(),
70+ })
71+ }
72+
73+ /// Opens the entry `name`, adding it from `contents` if missing.
74+ pub async fn entry(&mut self, name: String, contents: impl AsyncRead) -> io::Result<File> {
75+ let path = match self.pending.get(&name) {
76+ Some(temp_path) => temp_path.to_path_buf(),
77+ None => self.dir.join(&name),
78+ };
79+ match File::open(path) {
80+ Err(err) if err.kind() == io::ErrorKind::NotFound => {}
81+ result => return result,
82+ }
83+
84+ let mut temp_file = platform::new_entry(&self.dir)?;
85+ copy_async_to_sync(contents, temp_file.as_file_mut()).await?;
86+ platform::write_out(temp_file.as_file())?;
87+ let (mut file, temp_path) = temp_file.into_parts();
88+ file.rewind()?;
89+ self.pending.insert(name, temp_path);
90+ Ok(file)
91+ }
92+
93+ /// Publishes pending entries once they are durable.
94+ pub fn commit(self) -> io::Result<()> {
95+ if self.pending.is_empty() {
96+ return Ok(());
97+ }
98+ platform::flush_device(&File::open(&self.dir)?)?;
99+ for (name, temp_path) in self.pending {
100+ temp_path.persist(self.dir.join(name))?;
101+ }
102+ Ok(())
103+ }
104+}
105+
106+pub(crate) use platform::clone_dir;
107+pub(crate) use platform::clone_file;
108+
109+#[cfg(target_vendor = "apple")]
110+mod platform {
111+ use std::fs::File;
112+ use std::fs::Permissions;
113+ use std::io;
114+ use std::os::unix::fs::PermissionsExt as _;
115+ use std::path::Path;
116+
117+ use rustix::fs::CloneFlags;
118+ use rustix::fs::Mode;
119+ use rustix::fs::OFlags;
120+ use tempfile::NamedTempFile;
121+
122+ /// Creates a temporary entry with the mode of a checked-out file, so
123+ /// clones of it need no `chmod`.
124+ pub fn new_entry(dir: &Path) -> io::Result<NamedTempFile> {
125+ tempfile::Builder::new()
126+ .permissions(Permissions::from_mode(0o644))
127+ .tempfile_in(dir)
128+ }
129+
130+ /// Creates `dst` as a copy-on-write clone of `src`, failing if `dst`
131+ /// exists. The clone keeps the mode and mtime of `src`.
132+ pub fn clone_file(src: &File, dst: &Path) -> io::Result<()> {
133+ Ok(rustix::fs::fclonefileat(
134+ src,
135+ rustix::fs::CWD,
136+ dst,
137+ CloneFlags::empty(),
138+ )?)
139+ }
140+
141+ /// Like [`clone_file()`], but clones the directory hierarchy at `src`
142+ /// without following a symlink there.
143+ pub fn clone_dir(src: &Path, dst: &Path) -> io::Result<()> {
144+ let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW;
145+ let src = rustix::fs::open(src, flags, Mode::empty())?;
146+ Ok(rustix::fs::fclonefileat(
147+ src,
148+ rustix::fs::CWD,
149+ dst,
150+ CloneFlags::empty(),
151+ )?)
152+ }
153+
154+ /// Writes `file` to the device, but not through the device's own cache.
155+ pub fn write_out(file: &File) -> io::Result<()> {
156+ Ok(rustix::fs::fsync(file)?)
157+ }
158+
159+ pub fn flush_device(file: &File) -> io::Result<()> {
160+ Ok(rustix::fs::fcntl_fullfsync(file)?)
161+ }
162+}
163+
164+#[cfg(not(target_vendor = "apple"))]
165+mod platform {
166+ use std::fs::File;
167+ use std::io;
168+ use std::path::Path;
169+
170+ use tempfile::NamedTempFile;
171+
172+ pub fn new_entry(dir: &Path) -> io::Result<NamedTempFile> {
173+ NamedTempFile::new_in(dir)
174+ }
175+
176+ pub fn clone_file(_src: &File, _dst: &Path) -> io::Result<()> {
177+ Err(io::ErrorKind::Unsupported.into())
178+ }
179+
180+ pub fn clone_dir(_src: &Path, _dst: &Path) -> io::Result<()> {
181+ Err(io::ErrorKind::Unsupported.into())
182+ }
183+
184+ pub fn write_out(file: &File) -> io::Result<()> {
185+ file.sync_data()
186+ }
187+
188+ pub fn flush_device(file: &File) -> io::Result<()> {
189+ file.sync_all()
190+ }
191+}
192diff --git a/lib/src/lib.rs b/lib/src/lib.rs
193index c97831a80a..8466d009d1 100644
194--- a/lib/src/lib.rs
195+++ b/lib/src/lib.rs
196@@ -49,6 +49,7 @@
197 pub(crate) mod eol;
198 pub mod evolution;
199 pub mod extensions_map;
200+mod file_cache;
201 pub mod file_util;
202 pub mod files;
203 pub mod fileset;
204diff --git a/lib/src/local_working_copy.rs b/lib/src/local_working_copy.rs
205index d7da1716fc..7c1294ff6f 100644
206--- a/lib/src/local_working_copy.rs
207+++ b/lib/src/local_working_copy.rs
208@@ -53,6 +53,7 @@
209 use pollster::FutureExt as _;
210 use prost::Message as _;
211 use rayon::iter::IntoParallelIterator as _;
212+use rayon::iter::IntoParallelRefIterator as _;
213 use rayon::prelude::IndexedParallelIterator as _;
214 use rayon::prelude::ParallelIterator as _;
215 use tempfile::NamedTempFile;
216@@ -80,6 +81,9 @@
217 use crate::conflicts::materialize_tree_value;
218 pub use crate::eol::EolConversionMode;
219 use crate::eol::TargetEolStrategy;
220+use crate::file_cache::FileCache;
221+use crate::file_cache::clone_dir;
222+use crate::file_cache::clone_file;
223 use crate::file_util::FileIdentity;
224 use crate::file_util::check_symlink_support;
225 use crate::file_util::copy_async_to_sync;
226@@ -99,6 +103,7 @@
227 use crate::matchers::Matcher;
228 use crate::matchers::PrefixMatcher;
229 use crate::matchers::UnionMatcher;
230+use crate::matchers::Visit;
231 use crate::merge::Merge;
232 use crate::merge::MergeBuilder;
233 use crate::merge::MergedTreeValue;
234@@ -127,6 +132,7 @@
235 use crate::working_copy::WorkingCopy;
236 use crate::working_copy::WorkingCopyFactory;
237 use crate::working_copy::WorkingCopyStateError;
238+use crate::workspace_store::SimpleWorkspaceStore;
239
240 fn symlink_target_convert_to_store(path: &Path) -> Option<Cow<'_, str>> {
241 let path = path.to_str()?;
242@@ -818,6 +824,14 @@
243
244 const RESERVED_DIR_NAMES: &[&str] = &[".git", ".jj"];
245
246+/// Smaller files are written directly, since cloning a file costs more than
247+/// writing a few blocks.
248+const MIN_CACHED_FILE_SIZE: u64 = 16 << 10;
249+
250+/// Untracked directories that tend to be huge, so their parents are never
251+/// cloned from a sibling workspace whole.
252+const UNCLONED_DIR_NAMES: &[&str] = &["node_modules", "target"];
253+
254 fn file_identity_from_symlink_path(disk_path: &Path) -> io::Result<Option<FileIdentity>> {
255 match FileIdentity::from_symlink_path(disk_path) {
256 Ok(identity) => Ok(Some(identity)),
257@@ -2071,6 +2085,82 @@
258 .map_err(|err| checkout_error_for_mtime_out_of_range(err, disk_path))
259 }
260
261+ /// Like [`Self::write_file()`], but clones `disk_path` from `file_cache`
262+ /// if the content is large enough to be worth it. Drops `file_cache` and
263+ /// copies instead if the file system can't clone. `fresh` means the
264+ /// working copy held nothing before this checkout.
265+ async fn write_cached_file(
266+ &self,
267+ disk_path: &Path,
268+ id: &FileId,
269+ contents: impl AsyncRead + Send + Unpin,
270+ exec_bit: ExecBit,
271+ file_cache: &mut Option<FileCache>,
272+ fresh: bool,
273+ ) -> Result<FileState, CheckoutError> {
274+ let Some(cache) = file_cache else {
275+ return self.write_file(disk_path, contents, exec_bit, true).await;
276+ };
277+
278+ let mut contents = self
279+ .target_eol_strategy
280+ .convert_eol_for_update(contents)
281+ .await
282+ .map_err(|err| CheckoutError::Other {
283+ message: "Failed to convert the EOL for the content".to_string(),
284+ err: err.into(),
285+ })?;
286+ let mut head = Vec::new();
287+ futures::AsyncReadExt::take(&mut contents, MIN_CACHED_FILE_SIZE)
288+ .read_to_end(&mut head)
289+ .await
290+ .map_err(|err| CheckoutError::Other {
291+ message: format!("Failed to read the content for {}", disk_path.display()),
292+ err: err.into(),
293+ })?;
294+ let is_small = (head.len() as u64) < MIN_CACHED_FILE_SIZE;
295+ let contents = futures::AsyncReadExt::chain(head.as_slice(), contents);
296+ if is_small {
297+ return self.write_file(disk_path, contents, exec_bit, false).await;
298+ }
299+
300+ let entry_name = if self.target_eol_strategy.converts_on_update() {
301+ format!("{}.crlf", id.hex())
302+ } else {
303+ id.hex()
304+ };
305+ let entry =
306+ cache
307+ .entry(entry_name, contents)
308+ .await
309+ .map_err(|err| CheckoutError::Other {
310+ message: format!("Failed to cache {}", disk_path.display()),
311+ err: err.into(),
312+ })?;
313+ // A clone keeps the entry's mtime, which would look stale to build tools
314+ // unless nothing in the working copy predates this checkout.
315+ if !fresh {
316+ entry
317+ .set_modified(SystemTime::now())
318+ .map_err(|err| checkout_error_for_stat_error(err, disk_path))?;
319+ }
320+ let metadata = entry
321+ .metadata()
322+ .map_err(|err| checkout_error_for_stat_error(err, disk_path))?;
323+ if clone_file(&entry, disk_path).is_err() {
324+ *file_cache = None;
325+ return self
326+ .write_file(disk_path, AllowStdIo::new(entry), exec_bit, false)
327+ .await;
328+ }
329+ if exec_bit.0 {
330+ set_executable(exec_bit, disk_path)
331+ .map_err(|err| checkout_error_for_stat_error(err, disk_path))?;
332+ }
333+ FileState::for_file(exec_bit, metadata.len(), &metadata)
334+ .map_err(|err| checkout_error_for_mtime_out_of_range(err, disk_path))
335+ }
336+
337 fn write_symlink(&self, disk_path: &Path, target: String) -> Result<FileState, CheckoutError> {
338 let target = symlink_target_convert_to_disk(&target);
339
340@@ -2183,6 +2273,180 @@
341 })
342 }
343
344+ /// Loads the tree state of the sibling workspace whose tree differs least
345+ /// from `new_tree`, along with the paths that differ.
346+ async fn closest_sibling(&self, new_tree: &MergedTree) -> Option<(Self, HashSet<RepoPathBuf>)> {
347+ let workspace_paths = SimpleWorkspaceStore::load(self.store.repo_path())
348+ .and_then(|store| store.workspace_paths())
349+ .ok()?;
350+ let own_path = dunce::canonicalize(&self.working_copy_path).ok()?;
351+ let settings = TreeStateSettings {
352+ conflict_marker_style: self.conflict_marker_style,
353+ eol_conversion_mode: EolConversionMode::None,
354+ exec_change_setting: ExecChangeSetting::Auto,
355+ fsmonitor_settings: FsmonitorSettings::None,
356+ };
357+
358+ let mut closest: Option<(Self, HashSet<RepoPathBuf>)> = None;
359+ for path in workspace_paths {
360+ let state_path = path.join(".jj").join("working_copy");
361+ // Loading a missing tree state would create one in the sibling.
362+ if !state_path.join("tree_state").is_file()
363+ || dunce::canonicalize(&path).is_ok_and(|path| path == own_path)
364+ {
365+ continue;
366+ }
367+ let Ok(sibling) = Self::load(self.store.clone(), path, state_path, &settings) else {
368+ continue;
369+ };
370+ if sibling.sparse_patterns != [RepoPathBuf::root()] {
371+ continue;
372+ }
373+ let limit = closest
374+ .as_ref()
375+ .map_or(usize::MAX, |(_, paths)| paths.len());
376+ let differing_paths: HashSet<RepoPathBuf> = sibling
377+ .tree
378+ .diff_stream(new_tree, &EverythingMatcher)
379+ .map(|entry| entry.path)
380+ .take(limit)
381+ .collect()
382+ .await;
383+ if differing_paths.len() < limit {
384+ closest = Some((sibling, differing_paths));
385+ }
386+ }
387+ closest
388+ }
389+
390+ /// Seeds a fresh working copy with directories cloned from the sibling
391+ /// workspace closest to `new_tree`, then keeps only the cloned files whose
392+ /// content the sibling's tree state vouches for. Returns their states.
393+ async fn seed_from_sibling(
394+ &self,
395+ new_tree: &MergedTree,
396+ matcher: &dyn Matcher,
397+ ) -> Result<Vec<(RepoPathBuf, FileState)>, CheckoutError> {
398+ let Some((sibling, differing_paths)) = self.closest_sibling(new_tree).await else {
399+ return Ok(vec![]);
400+ };
401+ let sibling_states = sibling.file_states();
402+
403+ let mut tracked_dirs: HashSet<&RepoPath> = HashSet::new();
404+ for path in sibling_states.paths() {
405+ for dir in path.ancestors().skip(1) {
406+ if !tracked_dirs.insert(dir) {
407+ break;
408+ }
409+ }
410+ }
411+ let mut child_dirs: HashMap<&RepoPath, Vec<&RepoPath>> = HashMap::new();
412+ for &dir in &tracked_dirs {
413+ if let Some(parent) = dir.parent() {
414+ child_dirs.entry(parent).or_default().push(dir);
415+ }
416+ }
417+ let dirs_holding_uncloned: Vec<&RepoPath> = tracked_dirs
418+ .par_iter()
419+ .copied()
420+ .filter(|dir| {
421+ let disk_dir = dir.to_fs_path_unchecked(&sibling.working_copy_path);
422+ UNCLONED_DIR_NAMES.iter().any(|&name| {
423+ let child = dir.join(RepoPathComponent::new(name).unwrap());
424+ !tracked_dirs.contains(&*child)
425+ && disk_dir.join(name).symlink_metadata().is_ok()
426+ })
427+ })
428+ .collect();
429+ let split_dirs: HashSet<&RepoPath> = dirs_holding_uncloned
430+ .into_iter()
431+ .chain(differing_paths.iter().filter_map(|path| path.parent()))
432+ .flat_map(RepoPath::ancestors)
433+ .collect();
434+
435+ // Never the root, which holds .jj and usually build output.
436+ let mut clone_roots = vec![];
437+ let mut dirs_to_split = vec![RepoPath::root()];
438+ while let Some(dir) = dirs_to_split.pop() {
439+ for &child in child_dirs.get(dir).into_iter().flatten() {
440+ if !split_dirs.contains(child) && matcher.visit(child) == Visit::AllRecursively {
441+ clone_roots.push(child);
442+ } else {
443+ dirs_to_split.push(child);
444+ }
445+ }
446+ }
447+
448+ // Clone roots hold the same tree in both workspaces, so a file is
449+ // vouched for if the sibling would see it as unchanged.
450+ let vouched_state = |path: &RepoPath, metadata: &Metadata| {
451+ let old_state = sibling_states.get(path)?;
452+ let new_state = file_state(metadata).ok()??;
453+ let clean = old_state.materialized_conflict_data.is_none()
454+ && new_state.is_clean(&old_state)
455+ && old_state.mtime < sibling.own_mtime;
456+ clean.then_some(new_state)
457+ };
458+ let seed = |root: &RepoPath| -> Result<Vec<(RepoPathBuf, FileState)>, CheckoutError> {
459+ let disk_root = root.to_fs_path(&self.working_copy_path)?;
460+ let created_parent = fs::create_dir_all(disk_root.parent().unwrap());
461+ let source = root.to_fs_path(&sibling.working_copy_path)?;
462+ if created_parent
463+ .and_then(|()| clone_dir(&source, &disk_root))
464+ .is_err()
465+ {
466+ fs::remove_dir_all(&disk_root).ok();
467+ return Ok(vec![]);
468+ }
469+
470+ let mut seeded = vec![];
471+ let mut dirs_to_walk = vec![root.to_owned()];
472+ while let Some(dir) = dirs_to_walk.pop() {
473+ let disk_dir = dir.to_fs_path(&self.working_copy_path)?;
474+ let entries = fs::read_dir(&disk_dir)
475+ .map_err(|err| checkout_error_for_stat_error(err, &disk_dir))?;
476+ for entry in entries {
477+ let entry =
478+ entry.map_err(|err| checkout_error_for_stat_error(err, &disk_dir))?;
479+ let disk_path = entry.path();
480+ let metadata = entry
481+ .metadata()
482+ .map_err(|err| checkout_error_for_stat_error(err, &disk_path))?;
483+ let path = entry
484+ .file_name()
485+ .to_str()
486+ .and_then(|name| RepoPathComponent::new(name).ok())
487+ .map(|name| dir.join(name));
488+ let removed = match path {
489+ Some(path) if metadata.is_dir() && tracked_dirs.contains(&*path) => {
490+ dirs_to_walk.push(path);
491+ Ok(())
492+ }
493+ _ if metadata.is_dir() => fs::remove_dir_all(&disk_path),
494+ Some(path) => match vouched_state(&path, &metadata) {
495+ Some(state) => {
496+ seeded.push((path, state));
497+ Ok(())
498+ }
499+ None => fs::remove_file(&disk_path),
500+ },
501+ None => fs::remove_file(&disk_path),
502+ };
503+ removed.map_err(|err| CheckoutError::Other {
504+ message: format!("Failed to remove {}", disk_path.display()),
505+ err: err.into(),
506+ })?;
507+ }
508+ }
509+ Ok(seeded)
510+ };
511+ let seeded: Vec<Vec<_>> = clone_roots
512+ .into_par_iter()
513+ .map(seed)
514+ .collect::<Result<_, _>>()?;
515+ Ok(seeded.into_iter().flatten().collect())
516+ }
517+
518 async fn update(
519 &mut self,
520 old_tree: &MergedTree,
521@@ -2200,6 +2464,22 @@
522 let mut changed_file_states = Vec::new();
523 let mut deleted_files = HashSet::new();
524 let mut prev_created_path: RepoPathBuf = RepoPathBuf::root();
525+ let mut file_cache = FileCache::open(self.store.repo_path());
526+ let fresh = *old_tree.tree_ids() == self.store.empty_merged_tree_id()
527+ && fs::read_dir(&self.working_copy_path).is_ok_and(|mut entries| {
528+ entries.all(|entry| entry.is_ok_and(|entry| entry.file_name() == ".jj"))
529+ });
530+ let seeded = if fresh
531+ && file_cache.is_some()
532+ && *new_tree.tree_ids() != self.store.empty_merged_tree_id()
533+ && !self.target_eol_strategy.converts_on_update()
534+ {
535+ self.seed_from_sibling(new_tree, matcher).await?
536+ } else {
537+ vec![]
538+ };
539+ let seeded_matcher = FilesMatcher::new(seeded.iter().map(|(path, _)| path));
540+ let matcher: &dyn Matcher = &DifferenceMatcher::new(matcher, &seeded_matcher);
541
542 let mut process_diff_entry = async |path: RepoPathBuf,
543 before: MergedTreeValue,
544@@ -2336,8 +2616,15 @@
545 MaterializedTreeValue::File(file) => {
546 let exec_bit =
547 ExecBit::new_from_repo(file.executable, self.exec_policy, get_prev_exec);
548- self.write_file(&disk_path, file.reader, exec_bit, true)
549- .await?
550+ self.write_cached_file(
551+ &disk_path,
552+ &file.id,
553+ file.reader,
554+ exec_bit,
555+ &mut file_cache,
556+ fresh,
557+ )
558+ .await?
559 }
560 MaterializedTreeValue::Symlink { id: _, target } => {
561 if self.symlink_support {
562@@ -2451,6 +2738,16 @@
563 changed_file_states.sort_unstable_by(|(path1, _), (path2, _)| path1.cmp(path2));
564 }
565
566+ if !seeded.is_empty() {
567+ stats.added_files += u32::try_from(seeded.len()).unwrap();
568+ changed_file_states.extend(seeded);
569+ changed_file_states.sort_unstable_by(|(path1, _), (path2, _)| path1.cmp(path2));
570+ }
571+
572+ // The files are in place; a cache that fails to update only costs speed.
573+ if let Some(file_cache) = file_cache {
574+ file_cache.commit().ok();
575+ }
576 self.file_states
577 .merge_in(changed_file_states, &deleted_files);
578 Ok(stats)
579diff --git a/lib/src/repo.rs b/lib/src/repo.rs
580index 61e5a6e093..b69a8ae85f 100644
581--- a/lib/src/repo.rs
582+++ b/lib/src/repo.rs
583@@ -223,7 +223,7 @@
584 fs::write(&backend_path, backend.name()).context(&backend_path)?;
585 let merge_options =
586 MergeOptions::from_settings(settings).map_err(|err| BackendInitError(err.into()))?;
587- let store = Store::new(backend, signer, merge_options);
588+ let store = Store::new(backend, signer, merge_options, repo_path.clone());
589
590 let op_store_path = repo_path.join("op_store");
591 fs::create_dir(&op_store_path).context(&op_store_path)?;
592@@ -711,6 +711,7 @@
593 store_factories.load_backend(settings, &repo_path.join("store"))?,
594 Signer::from_settings(settings)?,
595 merge_options,
596+ repo_path.to_owned(),
597 );
598 let root_op_data = RootOperationData {
599 root_commit_id: store.root_commit_id().clone(),
600diff --git a/lib/src/store.rs b/lib/src/store.rs
601index 813d1eef87..e812b6b701 100644
602--- a/lib/src/store.rs
603+++ b/lib/src/store.rs
604@@ -16,6 +16,8 @@
605
606 use std::fmt::Debug;
607 use std::fmt::Formatter;
608+use std::path::Path;
609+use std::path::PathBuf;
610 use std::pin::Pin;
611 use std::sync::Arc;
612 use std::sync::Mutex;
613@@ -59,6 +61,7 @@
614 commit_cache: Mutex<CLruCache<CommitId, Arc<backend::Commit>>>,
615 tree_cache: Mutex<CLruCache<(RepoPathBuf, TreeId), Arc<backend::Tree>>>,
616 merge_options: MergeOptions,
617+ repo_path: PathBuf,
618 }
619
620 impl Debug for Store {
621@@ -74,6 +77,7 @@
622 backend: Box<dyn Backend>,
623 signer: Signer,
624 merge_options: MergeOptions,
625+ repo_path: PathBuf,
626 ) -> Arc<Self> {
627 Arc::new(Self {
628 backend,
629@@ -81,6 +85,7 @@
630 commit_cache: Mutex::new(CLruCache::new(COMMIT_CACHE_CAPACITY.try_into().unwrap())),
631 tree_cache: Mutex::new(CLruCache::new(TREE_CACHE_CAPACITY.try_into().unwrap())),
632 merge_options,
633+ repo_path,
634 })
635 }
636
637@@ -102,6 +107,11 @@
638 &self.merge_options
639 }
640
641+ /// The repo directory, which holds state shared by its workspaces.
642+ pub fn repo_path(&self) -> &Path {
643+ &self.repo_path
644+ }
645+
646 pub fn get_copy_records(
647 &self,
648 paths: Option<&[RepoPathBuf]>,
649diff --git a/lib/src/workspace_store.rs b/lib/src/workspace_store.rs
650index 32e6072b4b..a5ad1bf614 100644
651--- a/lib/src/workspace_store.rs
652+++ b/lib/src/workspace_store.rs
653@@ -127,6 +127,18 @@
654 Ok(store)
655 }
656
657+ /// Returns the paths of all registered workspaces.
658+ pub fn workspace_paths(&self) -> Result<Vec<PathBuf>, WorkspaceStoreError> {
659+ let paths = self
660+ .read_store()?
661+ .workspaces
662+ .iter()
663+ .map(|w| path_from_bytes(&w.path).map(|path| self.repo_path.join(path)))
664+ .collect::<Result<_, _>>()
665+ .map_err(SimpleWorkspaceStoreError::BadPathEncoding)?;
666+ Ok(paths)
667+ }
668+
669 fn lock(&self) -> Result<FileLock, SimpleWorkspaceStoreError> {
670 Ok(FileLock::lock(self.lock_file.clone())?)
671 }
672diff --git a/lib/tests/test_local_working_copy.rs b/lib/tests/test_local_working_copy.rs
673index 55aaffd9c9..00a12f87bc 100644
674--- a/lib/tests/test_local_working_copy.rs
675+++ b/lib/tests/test_local_working_copy.rs
676@@ -51,8 +51,10 @@
677 use jj_lib::merge::SameChange;
678 use jj_lib::merged_tree::MergedTree;
679 use jj_lib::merged_tree_builder::MergedTreeBuilder;
680+use jj_lib::object_id::ObjectId as _;
681 use jj_lib::op_store::OperationId;
682 use jj_lib::ref_name::WorkspaceName;
683+use jj_lib::ref_name::WorkspaceNameBuf;
684 use jj_lib::repo::ReadonlyRepo;
685 use jj_lib::repo::Repo as _;
686 use jj_lib::repo_path::RepoPath;
687@@ -68,6 +70,7 @@
688 use jj_lib::working_copy::WorkingCopy as _;
689 use jj_lib::workspace::Workspace;
690 use jj_lib::workspace::default_working_copy_factories;
691+use jj_lib::workspace::default_working_copy_factory;
692 use pollster::FutureExt as _;
693 use test_case::test_case;
694 use testutils::CommitBuilderExt as _;
695@@ -84,6 +87,7 @@
696 use testutils::repo_path_buf;
697 use testutils::repo_path_component;
698 use testutils::write_random_commit;
699+use testutils::write_working_copy_file;
700
701 fn check_icase_fs(dir: &Path) -> bool {
702 let test_file = tempfile::Builder::new()
703@@ -822,6 +826,125 @@
704 }
705
706 #[test]
707+fn test_checkout_clones_large_files_from_file_cache() -> TestResult {
708+ // Edits to a cloned file must not reach the cache entry or later checkouts.
709+ let mut test_workspace = TestWorkspace::init();
710+ let repo = test_workspace.repo.clone();
711+ let workspace_root = test_workspace.workspace.workspace_root().to_owned();
712+ let cache_dir = repo.store().repo_path().join("file_cache");
713+ let clones = cfg!(target_vendor = "apple");
714+
715+ let large_path = repo_path("large");
716+ let small_path = repo_path("small");
717+ let large_contents = "large\n".repeat(16 << 10);
718+ let tree = create_tree(
719+ &repo,
720+ &[(large_path, &large_contents), (small_path, "small")],
721+ );
722+ let commit = commit_with_tree(repo.store(), tree.clone());
723+ let Ok(Some(TreeValue::File { id: large_id, .. })) =
724+ tree.path_value(large_path).block_on()?.into_resolved()
725+ else {
726+ panic!("large file should be resolved");
727+ };
728+ let entry_path = cache_dir.join(large_id.hex());
729+ let large_disk_path = large_path.to_fs_path_unchecked(&workspace_root);
730+
731+ test_workspace
732+ .workspace
733+ .check_out(repo.op_id().clone(), None, &commit)
734+ .block_on()?;
735+ assert_eq!(std::fs::read_to_string(&large_disk_path)?, large_contents);
736+ if clones {
737+ assert_eq!(std::fs::read_to_string(&entry_path)?, large_contents);
738+ assert_eq!(std::fs::read_dir(&cache_dir)?.count(), 1);
739+ } else {
740+ assert!(!cache_dir.exists());
741+ }
742+
743+ write_working_copy_file(&workspace_root, large_path, "edited");
744+ assert_ne!(test_workspace.snapshot()?.tree_ids(), tree.tree_ids());
745+ if clones {
746+ assert_eq!(std::fs::read_to_string(&entry_path)?, large_contents);
747+ File::open(&entry_path)?.set_modified(SystemTime::UNIX_EPOCH)?;
748+ }
749+
750+ test_workspace
751+ .workspace
752+ .check_out(repo.op_id().clone(), None, &commit)
753+ .block_on()?;
754+ assert_eq!(std::fs::read_to_string(&large_disk_path)?, large_contents);
755+ let age = SystemTime::now().duration_since(large_disk_path.metadata()?.modified()?);
756+ assert!(age.is_ok_and(|age| age < Duration::from_secs(60)));
757+ assert_eq!(test_workspace.snapshot()?.tree_ids(), tree.tree_ids());
758+ Ok(())
759+}
760+
761+#[test]
762+fn test_checkout_fresh_workspace_seeds_from_sibling() -> TestResult {
763+ // Unchanged directories come from the sibling, but not its unsnapshotted
764+ // edits, untracked files, or node_modules.
765+ let mut test_workspace = TestWorkspace::init();
766+ let repo = test_workspace.repo.clone();
767+ let root1 = test_workspace.workspace.workspace_root().to_owned();
768+ let tree = create_tree(
769+ &repo,
770+ &[
771+ (repo_path("dir/clean"), "clean"),
772+ (repo_path("dir/edited"), "original"),
773+ (repo_path("pkg/src/lib"), "lib"),
774+ (repo_path("top"), "top"),
775+ ],
776+ );
777+ let commit = commit_with_tree(repo.store(), tree.clone());
778+ test_workspace
779+ .workspace
780+ .check_out(repo.op_id().clone(), None, &commit)
781+ .block_on()?;
782+ // Re-save the tree state so no file is racily clean.
783+ std::thread::sleep(Duration::from_millis(10));
784+ test_workspace.snapshot()?;
785+ std::fs::write(root1.join("dir/edited"), "edited")?;
786+ std::fs::write(root1.join("dir/untracked"), "untracked")?;
787+ std::fs::create_dir_all(root1.join("pkg/node_modules/dep"))?;
788+ std::fs::write(root1.join("pkg/node_modules/dep/index.js"), "dep")?;
789+
790+ let root2 = test_workspace.root_dir().join("ws2_root");
791+ std::fs::create_dir(&root2)?;
792+ let (mut ws2, repo) = Workspace::init_workspace_with_existing_repo(
793+ &root2,
794+ test_workspace.repo_path(),
795+ &repo,
796+ &*default_working_copy_factory(),
797+ WorkspaceNameBuf::from("ws2"),
798+ )
799+ .block_on()?;
800+ ws2.check_out(repo.op_id().clone(), None, &commit)
801+ .block_on()?;
802+
803+ assert_eq!(std::fs::read_to_string(root2.join("dir/clean"))?, "clean");
804+ assert_eq!(
805+ std::fs::read_to_string(root2.join("dir/edited"))?,
806+ "original"
807+ );
808+ assert_eq!(std::fs::read_to_string(root2.join("pkg/src/lib"))?, "lib");
809+ assert!(!root2.join("dir/untracked").exists());
810+ assert!(!root2.join("pkg/node_modules").exists());
811+ let mtime = |path: PathBuf| path.metadata().and_then(|metadata| metadata.modified());
812+ let seeded = cfg!(target_vendor = "apple");
813+ for path in ["dir/clean", "pkg/src/lib"] {
814+ assert_eq!(mtime(root2.join(path))? == mtime(root1.join(path))?, seeded);
815+ }
816+ let mut locked_ws = ws2.start_working_copy_mutation().block_on()?;
817+ let (snapshot, _stats) = locked_ws
818+ .locked_wc()
819+ .snapshot(&empty_snapshot_options())
820+ .block_on()?;
821+ assert_eq!(snapshot.tree_ids(), tree.tree_ids());
822+ Ok(())
823+}
824+
825+#[test]
826 fn test_snapshot_file_directory_transition() -> TestResult {
827 let mut test_workspace = TestWorkspace::init();
828 let repo = test_workspace.repo.clone();
users/clover/agents/AGENTS.md+29-6
......@@ -54,17 +54,24 @@ Keep an earned comment to a line, timeless, and rarely first person (no `I`,
5454topology, and cross-file mechanism belong in the commit or the linked issue. Cut
5555every clause a competent reader would already infer.
5656
57## alphaXiv
58
59I am testing a new patch for dev-tui. instead of starting it with pnpm dev run
60`node ~/dev/dev-tui/boot.ts`.
61
5762## Orchestration
5863
5964When asked to play orchestrator, you become a manager: the main thread holds the
6065plan, which agent owns which files, and the integration seam; sub-agents hold
6166the edits and the deep planning. Ignore this section when not explicitly asked
62to be an orchestrator or the "Maintain It" skill.
63
64- After launching agents, omit launch commentary. Continue working or
65 wait_agent. Collect results, integrate, verify, and complete the authorized
66 task before ending the turn. Agent launch or completion alone is not a
67 stopping condition.
67to be an orchestrator. In that mode, these rules apply:
68
69- After launching sub-agents, send no acknowledgement or recap. Keep the parent
70 run active and wait for results.
71- Never send a final reply, including an empty one, while work required for this
72 request is pending.
73- Review completed results, then report them. Surface questions needing my input
74 with their context.
6875- The transcript is a record of work completed, never of work queued. A
6976 sub-agent starting and finishing already shows as its own item. Answer a
7077 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.
127134 considered. One per message; pure negation earns no second clause.
128135- You cannot judge visual taste. Ship screenshots and GIFs so I can.
129136
137## Cold Read
138
139Anything that leaves the thread -- a screenshot, chart, user-facing string,
140error message, PR or commit body -- gets read by someone with no context before
141it ships. Your own context fills every gap, so a self-check passes what I would
142flag. Open the rendered artifact (the PNG, never the source), say what it shows,
143and look for cut-off text, undefined terms, dead ends, and claims a reviewer
144cannot judge. Anything past a one-liner goes to a fresh sub-agent that sees only
145the artifact: use the `cold-read` skill. Fix findings before sending.
146
147A passing test or a clean screenshot script proves nothing about the image it
148wrote. Never send or embed an image the same step that produced it; open it
149first, every time.
150
130151## Jujutsu
131152
132153- 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.
170191 models collaborate, be sure to credit all of them.
171192- If the prompt mentions "ChatGPT Dot" or a task referred from a "Lilac" agent,
172193 add `Assisted-by: chatgpt-dot:lilac` as the last credit.
194- Open every PR through the `file-pr` skill. PR bodies end in the same
195 `Assisted-by` trailers, never a "Generated with Claude Code" line.
173196
174197## Personal
175198
users/clover/agents/skills/README.md deleted-65
......@@ -1,65 +0,0 @@
1# Skills for building apps with agents
2
3Eight skills for Claude Code and Codex, distilled from about 60 sessions in which
4agents built three of Clover's apps:
5
6- **Snowbound**: a OneNote 2010 remake that one agent maintained for ten days;
7- **Clover Chat**: a chat app whose clickable HTML prototype became the spec for
8 the real thing;
9- **the snow globe**: a home-server dashboard.
10
11Quotes attributed to Clover are hers, kept for flavour and because they carry
12the reasons. `ui-copy` quotes published design systems.
13
14| Skill | Use it for |
15| --- | --- |
16| `ui-copy` | Every word a person reads on screen |
17| `ui-prototype` | A clickable HTML mock of the whole app before building the real UI, then building from it |
18| `ux-flows` | How screens, menus, settings, onboarding and errors should behave |
19| `ui-craft` | How it looks and moves: measured against the reference, nothing jumping |
20| `ux-testing` | Finding problems the way a user would, before handing anything over |
21| `accessibility` | Keyboard paths and the accessibility tree, tested without ever turning a screen reader on |
22| `ui-review-loop` | Turning a batch of feedback into one round of fixes |
23| `maintain-it` | Handing a solo repo to one agent that plans, ships to main, releases and keeps the tracker true |
24
25## Install
26
27Copy all eight folders into `~/.claude/skills/` for Claude Code, into
28`~/.codex/skills/` for Codex, or into both. They refer to each other by name,
29so install the set together.
30
31They work best with:
32
33- sub-agents;
34- a tool for asking multiple-choice questions;
35- a browser the agent can drive: the in-app browser, or Chrome plus Node 22 for
36 `ux-testing/scripts/drive.mjs`;
37- for `maintain-it`, an issue tracker the agent can write to.
38
39## Your taste
40
41Taste is yours. Put it where agents read it, such as AGENTS.md, CLAUDE.md or
42memory. Until you do, `ui-craft` uses Clover's taste as a worked example and
43asks before leaning on it.
44
45## Prompting moves
46
47The skills make agents offer most of these. Asking for them directly gets you
48there sooner.
49
50```
51start "mock this before we build it", plus a two-sentence pitch, the look to inherit,
52 2–3 reference apps, and which surface is the hard custom one
53answer the question round; free-text answers are followed literally
54review use the mock-controls panel; send numbered screenshots with one-liners;
55 send small things as you go
56name it "the way Discord does muting": naming the product that already solved it lands fastest
57unstick "something's off" gets an A/B/C sheet; open-ended taste gets variants
58before "run a fresh-eyes pass"; "sweep it" once nits pile up
59handoff "match the mock literally", plus which sizes, fonts and materials are exact targets
60maintain "you're the maintainer": then settle the contract it asks about (push, release,
61 tracker access, budget, what stays yours)
62```
63
64When a word could mean two things ("theme", "half", "tighter"), the agent is
65supposed to restate it before building. If it doesn't, ask it to.
users/clover/agents/skills/babysit-pr/SKILL.md created+117
......@@ -0,0 +1,117 @@
1---
2name: babysit-pr
3description: Monitor a pull request through review and CI. Use when the user asks to monitor, watch, or babysit a PR.
4---
5
6# Babysit PR
7
8Many repos have AI review bots. They're helpful, even if they are not always
9right.
10
11## Waiting
12
13Never write your own watcher, polling loop, or `sleep` loop. Use one watcher
14per PR: `watch_pull_request` in T3 Code, `pr-wait` everywhere else. Never run
15both on the same PR. Every watcher on a GitHub account shares one rate limit.
16
17### In T3 Code: `watch_pull_request`
18
19Handle the existing checks and comments first. Then call
20`watch_pull_request` and end your turn. T3 Code wakes you with a message when
21a check fails, the required checks pass, someone comments or reviews, or the
22branch conflicts.
23
24- **Only the thread that owns the PR watches it.** If you are a delegated
25 child task (a reviewer, a Sol round, any `delegate_task` child), never call
26 `watch_pull_request`. The parent owns the PR. Do not watch PRs you are not
27 working on.
28- **A wake is news, not a merge decision.** Check the merge gate yourself.
29- **Unwatch when you hand off.** A watched thread stays in Working and out of
30 the user's inbox. When you stop (ready, blocked, or asking the user a question),
31 call `unwatch_pull_request` first. A merge or close ends the watch on its
32 own.
33- **"Stopped watching, could not read it"** usually means GitHub's rate limit
34 is used up. Run `gh api rate_limit --jq .resources.graphql` before you
35 watch again. If `remaining` is near 0, wait for `reset` with one background
36 command, then watch again. Never watch again in a tight loop.
37
38### Everywhere else: `pr-wait`
39
40Wait with `scripts/pr-wait` from this skill's directory (use its absolute
41path).
42
43```bash
44pr-wait <pr> [--repo owner/name] [--until ready|green|any-change]
45```
46
47It prints one line per real event. It exits 0 when the `--until` condition is
48met or the PR merges, 1 when it needs you (a required check failed, conflicts,
49unresolved threads, PR closed), and 2 on bad input.
50
51- `ready` (default): required checks green, Greptile or Macroscope reviewed the
52 head, and no unresolved threads. Use this to babysit.
53- `green`: required checks only. Use it when the repo has no Greptile or
54 Macroscope.
55- `any-change`: exit on the first event.
56
57In Claude Code, run it with the Monitor tool (`timeout_ms: 3600000`), so each
58line wakes you. Without a monitor, run it as one long command. It ends on its
59own.
60
61Start it again after you push, after you handle an exit 1, and after a resume.
62It remembers what it already reported, so nothing that arrived in between is
63lost. If it says another pid already watches the PR, do not start a second one.
64Kill the old one only if its events do not reach you.
65
66With either watcher: when an event needs no action, end your turn without a
67message. Never post or say "still waiting".
68
69## GitHub rate limits
70
71`gh pr create`, `gh pr view`, and `gh pr checks` use GraphQL. When GraphQL is
72used up, the REST limit is separate and usually still has room. Use
73`gh api repos/<owner>/<repo>/pulls/<n>` to read a PR, and
74`gh api repos/<owner>/<repo>/commits/<sha>/check-runs` for checks.
75
76## Reviews
77
78Only act on checks and comments newer than the latest push. Verify every bot
79finding against the source before changing code. Fix real findings and CI
80failures, distinguish repository failures from infrastructure flakes, and reply
81with a written reason when dismissing false positives.
82
83If the repo has `.macroscope/check-run-agents/*.md`, read those rules before you
84reply to a Macroscope finding. Its findings cite them.
85
86CodeRabbit is advisory. Treat its findings like any other finding, but never
87wait for it and never hold a merge for it.
88
89If a review bot leaves feedback you believe is not worth addressing, reply with
90a written reason and resolve the comment. Use the `leaving-pr-comments` skill
91for every comment posted on the user's behalf.
92
93Screenshots and videos help as well, when you have a way to upload them.
94
95Keep the PR at the size the user's goal needs. Review loops tend to grow a
96PR one cheap-looking fix at a time. Fix real bugs in the intended case.
97Decline the rest with a written reason, and list them as follow-ups:
98unneeded tests, guards for edge cases that do not matter, extra integration
99or compatibility, and small performance costs. Prefer the fix that deletes or
100narrows code.
101
102## Base branch and merging
103
104Keep an eye on changes to `main` and rebase when needed. `pr-wait` reports when
105new base commits touch this PR's files, and when the PR becomes BEHIND or DIRTY.
106`watch_pull_request` reports conflicts only, so check for BEHIND yourself
107before you call the PR ready.
108If an overlapping PR makes this one obsolete, stop monitoring, report it to the
109user, and ask before closing the PR unless closure was explicitly authorized.
110
111If nothing has changed, stay quiet rather than posting filler comments. Stop
112when `pr-wait` exits 0, or in T3 Code when the merge gate passes on the latest
113head. Merge only when the user explicitly requested it;
114otherwise report that the PR is ready. Right before a merge, run `git fetch` and
115check the PR again. Never merge when it is BEHIND or DIRTY, or when base commits
116that landed after the last green run touch this PR's files. Rebase, push, and
117wait for green again.
users/clover/agents/skills/babysit-pr/scripts/pr-wait created+556
......@@ -0,0 +1,556 @@
1#!/usr/bin/env python3
2"""pr-wait: watch one GitHub pull request and print one line per real event.
3
4 pr-wait <pr> [--repo owner/name] [--until green|ready|any-change] [--interval 20]
5
6<pr> is a PR number or PR URL. Without --repo, the repo comes from the URL or
7from the current checkout. Stdout carries only events, one line each, so a
8monitor (Claude Code's Monitor tool) wakes the agent once per real event.
9Progress and errors that do not end the run go to stderr.
10
11--until
12 green required checks passed on the current head (every CI check when
13 the base branch requires none)
14 ready green, Greptile or Macroscope reviewed the current head, and no
15 review thread is unresolved (default)
16 any-change stop after the first poll that prints an event
17
18Exit codes
19 0 the --until condition is met, or the PR merged
20 1 the condition cannot be met without action: a required check failed, the
21 branch conflicts with its base, the PR closed, `ready` is blocked by
22 unresolved threads or a BEHIND branch, or GitHub stayed unreachable
23 2 bad arguments, unknown PR, or another pr-wait already watches this PR
24
25Events
26 - a required check failed (name and link)
27 - all checks finished on the head (one summary line)
28 - a new comment, review, thread, or thread reply from someone other than the
29 PR author or the gh user
30 - Greptile, Macroscope, or CodeRabbit finished on the head, or a Greptile or
31 Macroscope summary changed after that
32 - the base branch moved and the new commits touch files in this PR
33 - merge state became BEHIND or DIRTY
34 - the PR merged or closed
35
36CodeRabbit is advisory: pr-wait reports it but never waits for it. Comment
37edits are never events, and top-level comments from CI and deploy bots
38(github-actions, Vercel) are skipped, because checks already carry that news.
39
40State lives in ~/.local/state/pr-wait/. A lock makes a second watcher for the
41same PR exit at once. A state file lets a restarted watcher report what arrived
42while no watcher ran. The first run for a PR records what already exists and
43reports only what comes after.
44"""
45
46from __future__ import annotations
47
48import argparse
49import fcntl
50import hashlib
51import html
52import json
53import os
54import re
55import subprocess
56import sys
57import time
58from collections.abc import Sequence
59from pathlib import Path
60from typing import Any, NoReturn
61
62GATING_BOTS = ("greptile", "macroscope")
63ADVISORY_BOTS = ("coderabbit",)
64# CI and deploy bots report through checks. Their PR comments are status reports.
65STATUS_BOTS = ("github-actions", "vercel", "netlify", "railway", "cloudflare")
66STATE_DIR = Path.home() / ".local" / "state" / "pr-wait"
67# A state file older than this describes an old session. Start a fresh baseline
68# instead of replaying hours of comments as new events.
69STALE_STATE_SECONDS = 6 * 3600
70MAX_FAILED_POLLS = 10
71TRANSIENT = re.compile(
72 r"HTTP (5\d\d|429)|rate limit|timed? ?out|connection (reset|refused)|EOF|"
73 r"temporar|could not resolve host|TLS handshake|Something went wrong",
74 re.IGNORECASE,
75)
76FAILED = ("fail", "cancel")
77# gh pr checks buckets, worst first. Duplicate names (push and pull_request runs
78# of one job) collapse to the worst bucket.
79RANK = {"fail": 4, "cancel": 3, "pending": 2, "pass": 1, "skipping": 0}
80
81QUERY = """
82query($owner: String!, $name: String!, $number: Int!) {
83 viewer { login }
84 repository(owner: $owner, name: $name) {
85 pullRequest(number: $number) {
86 url state headRefOid baseRefName mergeStateStatus
87 author { login }
88 baseRef { target { oid } }
89 comments(last: 100) { nodes { id url body author { login __typename } } }
90 reviews(last: 100) {
91 nodes { id url state body commit { oid } author { login __typename } }
92 }
93 reviewThreads(last: 100) {
94 nodes {
95 isResolved path line
96 comments(first: 100) { nodes { id url body author { login __typename } } }
97 }
98 }
99 }
100 }
101}
102"""
103
104Json = dict[str, Any]
105
106
107class GhError(Exception):
108 def __init__(self, message: str, transient: bool) -> None:
109 super().__init__(message)
110 self.transient = transient
111
112
113def log(message: str) -> None:
114 print(f"pr-wait: {message}", file=sys.stderr, flush=True)
115
116
117def fail(message: str, code: int = 2) -> NoReturn:
118 # Fatal messages go to stdout so a monitor shows the agent why it stopped.
119 print(f"pr-wait: {message}", flush=True)
120 sys.exit(code)
121
122
123def gh(args: list[str], allow: tuple[int, ...] = (0,)) -> subprocess.CompletedProcess[str]:
124 """Run gh. Retries transient failures (HTTP 5xx or 429, network) with backoff."""
125 delay = 2
126 for attempt in range(5):
127 proc = subprocess.run(["gh", *args], capture_output=True, text=True)
128 transient = proc.returncode != 0 and bool(TRANSIENT.search(proc.stderr))
129 if not transient and proc.returncode in allow:
130 return proc
131 lines = proc.stderr.strip().splitlines()
132 message = lines[-1] if lines else f"gh exited {proc.returncode}"
133 if not transient or attempt == 4:
134 raise GhError(message, transient)
135 log(f"gh {' '.join(args[:2])}: {message}; retry in {delay}s")
136 time.sleep(delay)
137 delay *= 2
138 raise AssertionError("unreachable")
139
140
141def gh_lines(args: list[str]) -> list[str]:
142 return [line for line in gh(args).stdout.splitlines() if line]
143
144
145def bot_name(text: str | None) -> str | None:
146 """Which review bot a login or check name belongs to, if any."""
147 lowered = (text or "").lower()
148 return next((bot for bot in GATING_BOTS + ADVISORY_BOTS if bot in lowered), None)
149
150
151def who(node: Json) -> tuple[str, bool]:
152 author = node.get("author") or {}
153 return author.get("login") or "ghost", author.get("__typename") == "Bot"
154
155
156def plain(body: str) -> str:
157 body = re.sub(r"<!--.*?-->", " ", body or "", flags=re.DOTALL)
158 return html.unescape(re.sub(r"<[^>]+>", " ", body))
159
160
161def snippet(body: str, limit: int = 100) -> str:
162 text = re.sub(r"\s+", " ", plain(body)).strip()
163 return text if len(text) <= limit else text[: limit - 3] + "..."
164
165
166def verdict(body: str) -> str:
167 """The verdict line of a bot summary (Macroscope, Greptile), if it has one."""
168 for line in plain(body).splitlines():
169 if re.search(r"verdict|confidence score", line, re.IGNORECASE):
170 return snippet(line.replace("*", ""), 80)
171 return ""
172
173
174def digest(body: str) -> str:
175 return hashlib.sha1(re.sub(r"\s+", " ", plain(body)).encode()).hexdigest()[:12]
176
177
178def parse_target(raw: str | None, repo: str | None) -> tuple[str, int]:
179 if raw is None or not raw.strip():
180 fail("missing PR number. Did a variable expand to nothing? Usage: pr-wait <pr> [--repo owner/name]")
181 url = re.fullmatch(r"https?://github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)(?:[/?#]\S*)?", raw.strip())
182 number = re.fullmatch(r"#?(\d+)", raw.strip())
183 if url:
184 repo = repo or url.group(1)
185 pr = int(url.group(2))
186 elif number:
187 pr = int(number.group(1))
188 else:
189 fail(f"'{raw}' is not a PR number or PR URL")
190 if pr <= 0:
191 fail(f"'{raw}' is not a valid PR number")
192 if not repo:
193 try:
194 repo = gh(["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"]).stdout.strip()
195 except GhError as error:
196 fail(f"no --repo given and the current directory has no GitHub repo ({error})")
197 if not re.fullmatch(r"[\w.-]+/[\w.-]+", repo):
198 fail(f"'{repo}' is not owner/name")
199 try:
200 gh(["pr", "view", str(pr), "-R", repo, "--json", "number"])
201 except GhError as error:
202 if not error.transient: # a transient failure is retried by the poll loop
203 fail(f"cannot read {repo}#{pr}: {error}")
204 return repo, pr
205
206
207def lock(repo: str, pr: int) -> Any:
208 """Hold a per-PR lock for the life of the process. The OS drops it on exit."""
209 STATE_DIR.mkdir(parents=True, exist_ok=True)
210 handle = open(STATE_DIR / f"{repo.replace('/', '__')}__{pr}.lock", "a+")
211 try:
212 fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
213 except BlockingIOError:
214 handle.seek(0)
215 pid = handle.read().strip() or "unknown"
216 fail(
217 f"pid {pid} already watches {repo}#{pr}, so this watcher exits to avoid "
218 f"duplicate events. If no events reach you from it, run `kill {pid}` and start again."
219 )
220 handle.seek(0)
221 handle.truncate()
222 handle.write(str(os.getpid()))
223 handle.flush()
224 return handle
225
226
227def required_checks(repo: str, base: str) -> set[str]:
228 """Required check names for the base branch, from rulesets and classic branch
229 protection. Knowing them up front means a required check that has not started
230 yet counts as pending, instead of green by omission."""
231 sources = (
232 (
233 f"repos/{repo}/rules/branches/{base}",
234 '.[] | select(.type == "required_status_checks") | .parameters.required_status_checks[].context',
235 ),
236 (f"repos/{repo}/branches/{base}/protection/required_status_checks", ".contexts[]?, .checks[]?.context"),
237 )
238 names: set[str] = set()
239 for path, jq in sources:
240 try:
241 names.update(gh_lines(["api", path, "--jq", jq]))
242 except GhError as error:
243 if "HTTP 404" not in str(error): # 404 means no protection, which is normal
244 log(f"could not read required checks from {path}: {error}")
245 return names
246
247
248class Watcher:
249 def __init__(self, repo: str, pr: int, until: str, interval: int) -> None:
250 self.repo, self.pr, self.until, self.interval = repo, pr, until, interval
251 self.owner, self.name = repo.split("/")
252 self.path = STATE_DIR / f"{repo.replace('/', '__')}__{pr}.json"
253 state = self.load()
254 # First run for this PR: record what exists and report nothing.
255 self.baseline = state is None
256 self.state: Json = state or {"reported": [], "summaries": {}, "base_oid": None, "merge_state": None}
257 self.reported: set[str] = set(self.state["reported"])
258 self.printed: set[str] = set()
259 self.events = 0
260 self.required: set[str] | None = None
261 self.prev_snapshot: list[tuple[str, str]] | None = None
262 self.pr_files: dict[str, set[str]] = {}
263
264 def load(self) -> Json | None:
265 try:
266 if time.time() - self.path.stat().st_mtime > STALE_STATE_SECONDS:
267 return None
268 return json.loads(self.path.read_text())
269 except (OSError, ValueError):
270 return None
271
272 def save(self) -> None:
273 self.state["reported"] = sorted(self.reported)
274 tmp = self.path.with_suffix(".tmp")
275 tmp.write_text(json.dumps(self.state))
276 tmp.replace(self.path)
277
278 def say(self, line: str) -> None:
279 if line not in self.printed:
280 self.printed.add(line)
281 print(f"#{self.pr} {line}", flush=True)
282
283 def emit(self, key: str, line: str) -> None:
284 """Print an event once per PR, across restarts."""
285 if key in self.reported:
286 return
287 self.reported.add(key)
288 if not self.baseline:
289 self.events += 1
290 self.say(line)
291
292 def finish(self, code: int, lines: Sequence[str] = ()) -> NoReturn:
293 for line in lines:
294 self.say(line)
295 self.save()
296 sys.exit(code)
297
298 def fetch_pr(self) -> Json:
299 proc = gh([
300 "api", "graphql", "-f", f"query={QUERY}",
301 "-f", f"owner={self.owner}", "-f", f"name={self.name}", "-F", f"number={self.pr}",
302 ])
303 data = json.loads(proc.stdout)["data"]
304 pr = data["repository"]["pullRequest"]
305 pr["viewer"] = data["viewer"]["login"]
306 return pr
307
308 def fetch_checks(self) -> dict[str, Json]:
309 # gh pr checks exits 8 while checks are pending and 1 when one failed.
310 # Those are states, not errors: read the JSON and ignore the exit code.
311 proc = gh(["pr", "checks", str(self.pr), "-R", self.repo, "--json", "name,bucket,link,description"], allow=(0, 1, 8))
312 if not proc.stdout.strip():
313 if "no checks reported" in proc.stderr:
314 return {}
315 raise GhError(proc.stderr.strip() or f"gh pr checks exited {proc.returncode}", False)
316 checks: dict[str, Json] = {}
317 for row in json.loads(proc.stdout):
318 current = checks.get(row["name"])
319 if current is None or RANK.get(row["bucket"], 2) > RANK.get(current["bucket"], 2):
320 checks[row["name"]] = row
321 return checks
322
323 def base_overlap(self, head: str, old: str, new: str) -> list[str]:
324 """Files this PR touches that the new base commits also touch."""
325 try:
326 if head not in self.pr_files:
327 self.pr_files[head] = set(gh_lines(["pr", "diff", str(self.pr), "-R", self.repo, "--name-only"]))
328 moved = gh_lines(["api", f"repos/{self.repo}/compare/{old}...{new}", "--jq", ".files[].filename"])
329 except GhError as error:
330 log(f"could not compare base commits: {error}")
331 return []
332 return sorted(self.pr_files[head].intersection(moved))
333
334 def behind(self, base: str, base_oid: str | None, head: str) -> str:
335 """How far the head is behind its base, for the green and ready lines."""
336 if not base_oid:
337 return ""
338 try:
339 count = gh(["api", f"repos/{self.repo}/compare/{base_oid}...{head}", "--jq", ".behind_by"]).stdout.strip()
340 except GhError:
341 return ""
342 return f"; {count} commit{'' if count == '1' else 's'} behind {base}"
343
344 def poll(self) -> None:
345 pr = self.fetch_pr()
346 if pr["state"] == "MERGED":
347 self.finish(0, [f"merged: {pr['url']}"])
348 if pr["state"] == "CLOSED":
349 self.finish(1, [f"closed without merging: {pr['url']}"])
350
351 base = pr["baseRefName"]
352 if self.required is None:
353 self.required = required_checks(self.repo, base)
354 gate = ", ".join(sorted(self.required)) or "none set, so every CI check gates"
355 log(f"watching {self.repo}#{self.pr} until {self.until}; required checks: {gate}")
356 checks = self.fetch_checks()
357 head = pr["headRefOid"]
358 short = head[:7]
359 mine = {who(pr)[0], pr["viewer"]}
360 comments = pr["comments"]["nodes"]
361 reviews = pr["reviews"]["nodes"]
362 threads = pr["reviewThreads"]["nodes"]
363 self.events = 0
364
365 # Required checks. With no required checks configured, every CI check
366 # gates except the review bots' own checks.
367 gate = self.required or {name for name in checks if not bot_name(name)}
368 label = "required check" if self.required else "check"
369
370 def bucket(name: str) -> str:
371 return checks[name]["bucket"] if name in checks else "pending"
372
373 fail_lines: list[str] = []
374 for name in sorted(gate):
375 if bucket(name) in FAILED:
376 link = checks[name]["link"]
377 fail_lines.append(f"{label} failed: {name} {link}")
378 self.emit(f"fail:{head}:{name}:{link}", fail_lines[-1])
379 watched = {name: c for name, c in checks.items() if bot_name(name) not in ADVISORY_BOTS}
380 gate_done = bool(gate) and all(bucket(n) != "pending" for n in gate)
381 all_done = gate_done and all(c["bucket"] != "pending" for c in watched.values())
382 # Checks appear a few seconds after a push. Two identical polls in a row
383 # guard against calling a half-registered set of checks finished.
384 snapshot = sorted((name, c["bucket"]) for name, c in watched.items())
385 stable = snapshot == self.prev_snapshot
386 self.prev_snapshot = snapshot
387 green = gate_done and stable and not fail_lines
388
389 # People and bots talking. Edits are never events.
390 for comment in comments:
391 login, is_bot = who(comment)
392 if login in mine or bot_name(login) or (is_bot and any(b in login for b in STATUS_BOTS)):
393 continue
394 self.emit(f"c:{comment['id']}", f"comment from {login}: {snippet(comment['body'])} {comment['url']}")
395 for review in reviews:
396 login, is_bot = who(review)
397 if login in mine or is_bot:
398 continue
399 if review["state"] in ("APPROVED", "CHANGES_REQUESTED") or review["body"].strip():
400 state = review["state"].lower().replace("_", " ")
401 self.emit(f"c:{review['id']}", f"review from {login} ({state}): {snippet(review['body'])} {review['url']}")
402 unresolved: list[str] = []
403 for thread in threads:
404 nodes = thread["comments"]["nodes"]
405 if not thread["isResolved"] and nodes:
406 unresolved.append(nodes[0]["url"])
407 where = f"{thread['path']}:{thread['line']}" if thread["line"] else thread["path"]
408 for index, comment in enumerate(nodes):
409 login, _ = who(comment)
410 if login in mine:
411 continue
412 kind = "new thread" if index == 0 else "thread reply"
413 self.emit(f"c:{comment['id']}", f"{kind} from {login} on {where}: {snippet(comment['body'])} {comment['url']}")
414
415 # Review bots on the current head. A bot with checks is done when they
416 # finish. Otherwise it is done once it reviews the head commit or its
417 # summary names the head.
418 bot_status: dict[str, str] = {}
419 reviewed: list[str] = []
420 for bot in GATING_BOTS + ADVISORY_BOTS:
421 own_checks = {name: c for name, c in checks.items() if bot_name(name) == bot}
422 summaries = [c for c in comments if bot_name(who(c)[0]) == bot]
423 own_reviews = [r for r in reviews if bot_name(who(r)[0]) == bot]
424 on_head = any((r.get("commit") or {}).get("oid") == head for r in own_reviews)
425 if own_checks:
426 done = all(c["bucket"] != "pending" for c in own_checks.values())
427 else:
428 done = on_head or any(short in s["body"] for s in summaries)
429 seen = bool(own_checks or summaries or own_reviews)
430 if bot in ADVISORY_BOTS and own_checks:
431 desc = next(iter(own_checks.values()))
432 bot_status[bot] = f"{bot} {desc['description'] or desc['bucket']} (advisory)"
433 elif seen:
434 bot_status[bot] = f"{bot} {'done' if done else 'pending'}{' (advisory)' if bot in ADVISORY_BOTS else ''}"
435 key = f"bot:{bot}:{head}"
436 was_done = key in self.reported
437 if done:
438 if bot in GATING_BOTS:
439 reviewed.append(bot)
440 failed = [name for name, c in own_checks.items() if c["bucket"] in FAILED]
441 detail = "; ".join(filter(None, [
442 next((v for v in map(verdict, (s["body"] for s in summaries)) if v), ""),
443 f"failed: {', '.join(failed)}" if failed else "",
444 ]))
445 tag = " (advisory, not waited on)" if bot in ADVISORY_BOTS else ""
446 self.emit(key, f"{bot} finished on {short}{': ' + detail if detail else ''}{tag}")
447 if bot in GATING_BOTS:
448 for s in summaries:
449 new, old = digest(s["body"]), self.state["summaries"].get(s["id"])
450 self.state["summaries"][s["id"]] = new
451 if was_done and old and old != new:
452 text = verdict(s["body"]) or snippet(s["body"])
453 self.emit(f"summary:{s['id']}:{new}", f"{bot} summary changed on {short}: {text} {s['url']}")
454
455 # Base branch and merge state.
456 base_oid = ((pr.get("baseRef") or {}).get("target") or {}).get("oid")
457 old_base = self.state["base_oid"]
458 if base_oid and old_base and base_oid != old_base and not self.baseline:
459 touched = self.base_overlap(head, old_base, base_oid)
460 if touched:
461 more = f" and {len(touched) - 5} more" if len(touched) > 5 else ""
462 self.emit(
463 f"base:{base_oid}",
464 f"{base} moved to {base_oid[:7]} and touches files in this PR: {', '.join(touched[:5])}{more}",
465 )
466 if base_oid:
467 self.state["base_oid"] = base_oid
468 merge_state = pr["mergeStateStatus"]
469 dirty_line = f"merge state is DIRTY: the branch conflicts with {base}, rebase it"
470 behind_line = f"merge state is BEHIND: update the branch from {base} before merging"
471 if merge_state != "UNKNOWN":
472 if merge_state in ("BEHIND", "DIRTY") and self.state["merge_state"] != merge_state:
473 line = dirty_line if merge_state == "DIRTY" else behind_line
474 self.emit(f"merge:{merge_state}:{head}:{base_oid}", line)
475 self.state["merge_state"] = merge_state
476
477 # One summary line per head once all checks finish.
478 counts: dict[str, int] = {}
479 for c in watched.values():
480 counts[c["bucket"]] = counts.get(c["bucket"], 0) + 1
481 failed_names = sorted(name for name, c in watched.items() if c["bucket"] in FAILED)
482 parts = [
483 ", ".join(f"{n} {b}" for b, n in sorted(counts.items()))
484 + (f" ({', '.join(failed_names)})" if failed_names else ""),
485 f"required {sum(bucket(n) in ('pass', 'skipping') for n in self.required)}/{len(self.required)} green"
486 if self.required
487 else "",
488 ", ".join(bot_status[b] for b in GATING_BOTS + ADVISORY_BOTS if b in bot_status)
489 or "no Greptile or Macroscope yet",
490 f"{len(unresolved)} unresolved threads",
491 f"merge state {merge_state}",
492 ]
493 summary = "; ".join(p for p in parts if p)
494 checks_key = f"checks:{head}"
495
496 # Decide whether to stop. A green or ready line carries the same summary
497 # as the checks line, so it marks that event as reported.
498 if self.until != "any-change":
499 if merge_state == "DIRTY":
500 self.finish(1, [dirty_line])
501 if fail_lines:
502 self.finish(1, fail_lines)
503 if green and self.until == "green":
504 self.reported.add(checks_key)
505 self.finish(0, [f"green on {short}: {summary}{self.behind(base, base_oid, head)}"])
506 # ready waits for Greptile or Macroscope, never for CodeRabbit.
507 if green and reviewed:
508 if unresolved:
509 self.finish(1, [f"blocked by {len(unresolved)} unresolved threads on {short}: {' '.join(unresolved)}"])
510 if merge_state == "BEHIND":
511 self.finish(1, [behind_line])
512 self.reported.add(checks_key)
513 self.finish(0, [f"ready on {short}: {summary}{self.behind(base, base_oid, head)}"])
514 if all_done and (stable or self.baseline):
515 self.emit(checks_key, f"checks finished on {short}: {summary}")
516 if self.until == "any-change" and self.events:
517 self.finish(0)
518
519 def run(self) -> NoReturn:
520 failures = 0
521 while True:
522 try:
523 self.poll()
524 failures = 0
525 except GhError as error:
526 if not error.transient:
527 self.finish(1, [f"pr-wait stopped: {error}"])
528 failures += 1
529 log(f"poll failed ({failures}/{MAX_FAILED_POLLS}): {error}")
530 if failures >= MAX_FAILED_POLLS:
531 self.finish(1, [f"pr-wait stopped: GitHub unreachable for {failures} polls: {error}"])
532 else:
533 self.save()
534 if self.baseline:
535 log(f"baseline recorded for {self.repo}#{self.pr}; reporting only new events")
536 self.baseline = False
537 time.sleep(self.interval)
538
539
540def main() -> None:
541 parser = argparse.ArgumentParser(prog="pr-wait", description="Watch a GitHub PR and print one line per real event.")
542 parser.add_argument("pr", nargs="?", help="PR number or URL")
543 parser.add_argument("--repo", help="owner/name (default: from the URL or the current checkout)")
544 parser.add_argument("--until", choices=("green", "ready", "any-change"), default="ready")
545 parser.add_argument("--interval", type=int, default=20, help="seconds between polls (default 20, min 5)")
546 args = parser.parse_args()
547 repo, pr = parse_target(args.pr, args.repo)
548 _lock = lock(repo, pr)
549 Watcher(repo, pr, args.until, max(args.interval, 5)).run()
550
551
552if __name__ == "__main__":
553 try:
554 main()
555 except KeyboardInterrupt:
556 sys.exit(130)
users/clover/agents/skills/cold-read/SKILL.md created+112
......@@ -0,0 +1,112 @@
1---
2name: cold-read
3description: 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`.
4---
5
6# Cold read
7
8After hours in a task, every gap in the artifact is filled in by what you know.
9You read "needs ACP adapter" and see a precise term; the owner sees nonsense.
10Re-reading with that context passes the same flaws, so the check has to run in a
11reader who never had it.
12
13`AGENTS.md` says when: anything that leaves the thread. This skill says how.
14`ux-testing` ("fresh eyes") drives a whole app as a first-time user; this is the
15per-artifact version of the same idea.
16
17## 1. Make the artifact the thing the reader sees
18
19- Review the output, not its source: the PNG, the rendered page, the final PR
20 body, the string as it appears in the UI.
21- Use real data. A fixture that happens to fit hides truncation, `0.00`, odd
22 ordering, and entries the owner did not expect to see.
23- Capture every state a person can land in (empty, long, error, narrow), not just
24 the happy one.
25
26## 2. Self pass, every time (cheap)
27
28A screenshot script that exits 0 has been tested, not reviewed: the feature
29works and the image can still be cropped, blank, stale, or showing the wrong
30state. Capture and send must be separate steps, never one script or one call,
31and no image goes to the owner (or into a PR, report, or `html_render`) that you
32have not opened in this turn.
33
34Open the file with the image viewer and write down, in plain words, what is on
35it before judging. Check that it shows the state you meant to prove, not just
36some state. Then check:
37
38- text ending in `…` (a finding even when intentional, since it reads as cut
39 off), clipped at an edge, or overlapping something;
40- uneven spacing, empty regions, content hugging one side;
41- marks with no label: icons, badges, `+1`, colours, ticks;
42- a chart's title, axis names, units and legend. Can its claim be read at a
43 glance?
44
45## 3. Cold pass (anything past a one-liner)
46
47Launch a fresh sub-agent on Claude Sonnet at low effort. It gets the artifact,
48one line naming the audience, and the questions for its kind. It never gets the
49diff, the thread, the code, or what you meant it to say. When Claude usage is
50low, use `gpt-6.1-terra` at low effort instead, and check geometry and
51affordance yourself in the self pass (see "Choosing the reader").
52
53```
54You are <audience, e.g. "a developer who has never seen this app">. You have
55only the attached <artifact>. Do not read any code or docs. Say in two
56sentences what you think it shows or does. Then list at most three things a
57real person would stop or misunderstand at (confusing, cut off, undefined,
58misleading, missing), worst first, one line each: what you saw → what you
59expected. Skip taste and polish. Do not say whether you like it. If it is fine,
60say "nothing" and stop.
61
62Questions: <rows from the table below>
63```
64
65A reader that cannot restate the artifact correctly in its first two sentences
66is the finding.
67
68| artifact | ask |
69|---|---|
70| 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? |
71| UI copy, labels | Is every word and symbol defined for someone who just arrived? Does anything use the project's internal vocabulary? |
72| chart | What is the claim? Are axes, units and legend present? What would a skeptic say is missing? |
73| generated or computed content | Does anything look wrong for a real input (rounding, ordering, casing, an item that shouldn't be there)? |
74| form of the content | What does the reader decide from this, and is this the shape that serves that decision? |
75| 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? |
76| error or status | What happened, whose fault is it, what do I do? |
77
78## Choosing the reader
79
80Measured on 18 screenshots (9 with one planted flaw each, 9 fixed controls) at
81low, medium and high effort. Single runs, blatant flaws only; subtle ones such
82as a 2px misalignment are untested.
83
84| reader | planted flaws caught | findings per image | misses |
85|---|---|---|---|
86| Claude Sonnet, any effort | 9/9 | 3.3–4.1 | none |
87| gpt-6.1-sol | 6–8/9 | 1.1–1.4 | unclickable menu, uneven padding |
88| gpt-6.1-terra, any effort | 7/9 | 0.9–1.1 | unclickable menu, uneven padding |
89
90- More effort never caught more; on Sonnet it only added nitpicks, so use low.
91- Sonnet sees layout and affordance the others miss, and its extra findings are
92 mostly polish, which the three-finding cap in the brief removes.
93- Terra is solid on meaning, cut-off text, rounding and missing labels, and
94 stays quiet on clean images. It misses pure layout and affordance, so as the
95 fallback the self pass must check spacing and "what looks clickable" itself.
96- Sol offers nothing over Terra here. Do not use opus- or fable-class models.
97
98## 4. Act on it
99
100- Fix every real confusion and re-render. Re-run the cold pass once if the fix
101 changed layout or wording substantially.
102- Findings about taste or direction go to the owner as a question. The cold
103 reader cannot judge taste, so never ask it whether something is good.
104- Report the fix in one line after the artifact, never before it.
105
106## Where it has already failed
107
108Owner complaints this skill exists to prevent: a "Use reset link" cut off to
109`Use…`; "needs ACP adapter makes no sense to me"; "unclear where you get this
110key from"; "I can't tell what is a button"; "a learning rate reads 0.00";
111"deepseek is showing up here"; "displaying a table is kind of wrong"; "+4800,
112what the heck".
users/clover/agents/skills/file-pr/SKILL.md created+85
......@@ -0,0 +1,85 @@
1---
2name: file-pr
3description: File a concise pull request. Use when the user asks to file, open, or create a PR.
4---
5
6# File PR
7
8## Push permission
9
10A request to file a PR, including "full send file pr", authorizes committing,
11pushing this task's branch, and the branch updates described here without
12asking again. This grant replaces general ask-first rules for these actions;
13it does not bypass harness approvals or branch protection. `full-send` and
14`full-stop` use this same policy.
15
16Before rewriting a published PR branch, check the live draft status and its
17ready-for-review history. For a draft PR that has never been marked ready for
18review, rebase as needed and automatically push with `--force-with-lease`.
19Never use plain `--force` or overwrite someone else's unexpected changes.
20
21Once a PR has been marked ready for review, preserve its published history,
22even if it later returns to draft. Use follow-up commits for fixes and merge
23the target branch when an update is needed. Rewriting that history requires
24explicit user authorization. If review history cannot be established, preserve
25published history. This permission covers only this task's branch, never the
26default branch or unrelated branches.
27
28## Filing
29
30Before filing, check whether a PR for this branch already exists. Review the
31diff locally against the base branch (usually `origin/main`) to make sure its
32contents match the goal.
33
34Write like a developer leaving a short note for teammates who know the project:
35direct, conversational, and matter-of-fact. Name the change and keep useful
36specifics. Cut ceremony ("This PR introduces..."), sales language, and a tour
37of the diff. Keep technical terms when they are the clearest way to say it.
38
39PR titles usually become commit messages. Aim for 50 characters or fewer,
40including any prefix and scope. Follow required repository conventions; use
41a scope only when the project requires one. Learn the tone of user-endorsed
42writing; a merge alone does not make a PR a style reference.
43
44Each row below rewrites the same change. Use the examples to learn the voice,
45then write fresh wording from the actual diff. Preserve the facts; shortening
46a title must not broaden its claim or invent a benefit. The scoped pair
47assumes a project that requires scopes.
48
49| Before | After |
50| --- | --- |
51| `fix: improve retry handling to prevent duplicate sends` | `fix: stop retries from sending messages twice` |
52| `feat: persist and hydrate open-tab state across app launches` | `feat: restore open tabs on launch` |
53| `feat: unlock seamless note sharing with public links` | `feat: share notes with a public link` |
54| `refactor: extract a common parser module for the CLI and worker` | `refactor: share the CLI and worker parser` |
55| `perf: implement incremental file indexing using modification timestamps` | `perf: skip unchanged files when indexing` |
56| `fix(sync): preserve the pending upload queue when the application restarts` | `fix(sync): keep pending uploads after restart` |
57
58Descriptions usually need one or two sentences. For a bug, give the symptom
59and the changed behavior; for a feature, say what it lets someone do. For
60internal work, say what changes and why. Keep a technical detail, measured
61result, or validation when it helps the reviewer assess the change. No file
62lists, section headings, or routine test plans.
63
64| Before | After |
65| --- | --- |
66| 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. |
67| 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. |
68| 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. |
69
70End the description with one trailer line per model that wrote part of the
71change, in the form `Assisted-by: <model>` (`claude-opus-5.5`, `gpt-6.1-sol`).
72Use the model ID the harness reports, never `Co-authored-by`, and never guess:
73if the model is unavailable, name the harness. Put `Assisted-by: chatgpt-dot:lilac`
74last when the task came from a Lilac agent or mentions "ChatGPT Dot".
75
76Before submission, check the title, description, quotes, and attachments for
77secrets and private details.
78
79Open a real PR rather than a draft so review bots run. If `gh pr create` fails
80because the GraphQL rate limit is used up, open it through REST with
81`gh api repos/<owner>/<repo>/pulls -f title=... -f head=... -f base=... -F body=@<file>`.
82If the user also asked to babysit it, continue with the `babysit-pr` skill.
83
84Do not post a follow-up PR comment unless it serves the user's request. When a
85comment is needed, use the `leaving-pr-comments` skill.
users/clover/agents/skills/full-send/SKILL.md created+124
......@@ -0,0 +1,124 @@
1---
2name: full-send
3description: Trigger this if the user says 'full send'.
4---
5
6# Full Send
7
8If the user triggered this, it's because they are not watching this thread, and
9they want you to complete the work end-to-end autonomously. Your updates and
10your final message go unread until long after you stop. You own the work from
11its current state to a merged PR.
12
13If the user did not explicitly request "full send" in some clear way, do not
14assume full autonomy. If they did, everything below applies.
15
16The user grants you permission to:
17
18- Merge the PR once the merge gate passes.
19- Commit and push the task's branch under
20 [file-pr's push policy](../file-pr/SKILL.md#push-permission).
21- Use the test methods that Proof needs, without asking first.
22
23## Testing permission
24
25A "full send" request is the permission. If a project file or other
26instruction says to ask before a test method, or to leave testing to the
27user, this request replaces that rule for this task.
28
29That includes ask-first rules for computer use, browser automation,
30simulators and devices, running the app or a dev server, screenshots, and
31visual checks. Use the method that gives direct proof. List it in the
32report.
33
34Rules about how to test still apply. Follow rules that name the correct
35command, fixture, or check. This permission only removes the ask-first or
36leave-it-to-the-user step. If a preferred method cannot prove the change,
37use a gated method under this permission.
38
39It covers only the tests needed for this task. It does not add permission
40for the steps under "Asking the user", such as production changes or data
41deletion. It also does not bypass a harness or system approval prompt if
42one appears.
43
44## Steps
45
461. **Finish the change.** Complete the goal from the user's request with the
47 smallest change that works. Fix the case that happened, not every case
48 that could. If you are on the default branch, create a branch first.
492. **Prove it.** Get proof for every change you made. See "Proof".
503. **Get feedback.** Use the `sol-loop` skill to verify changes.
514. **File the PR** with the `file-pr` skill. Update against the latest default
52 branch first, following its push policy for existing PRs. Add one short
53 line to the description that says how you proved the change.
545. **Babysit the PR** with the `babysit-pr` skill. Fix real findings and CI
55 failures. Get proof for each fix before you push it.
566. **Merge** when the merge gate passes.
577. **Report** in your final message: the PR link, the merge commit, your proof,
58 and each decision you made for the user.
59
60Stay active from step 1 to step 7. If you end your turn while checks or bots are
61pending, the work stops, because nobody will prompt you again. Wait with the
62watcher from `babysit-pr`, so something wakes you when the PR changes. In T3
63Code that is `watch_pull_request`. If you stop before the merge, call
64`unwatch_pull_request` first.
65
66## Proof
67
68Proof is evidence you observed yourself in this session: command output, a
69reproduction, a screenshot. Use the most direct proof the change allows:
70
71- Reproduce the original failure, apply the fix, then watch the same
72 reproduction pass.
73- Run the checks that the repo's CI runs (typecheck, lint, tests).
74- Add one focused test that fails without the fix, when the behavior has none
75 and the repo has a test setup.
76- For UI and runtime behavior, run the app and look at the change. Green mocked
77 tests do not prove that the user experience works. Attach screenshots to the
78 PR when they help and you have a way to upload them.
79
80When you cannot find a way to prove a change, you do not have full confidence.
81Ask the user.
82
83## Merge gate
84
85Full confidence means all of these are true on the latest commit:
86
87- Your proof covers every change in the diff.
88- Required checks are green.
89- Review bots have finished, and each finding is fixed or dismissed with a
90 written reason.
91- No human review still requests changes.
92- The branch is up to date with the default branch, and GitHub reports it as
93 mergeable.
94
95Merge with the method the repo uses. Check the allowed methods and recent merged
96PRs. If the repo uses a merge queue or auto-merge, stay until GitHub reports the
97PR as merged. Merge through branch protection as configured. Never use `--admin`
98or other bypasses. You can ignore automated reviews that request "needs human
99review" if you have high confidence in your changes.
100
101## Asking the user
102
103A question in a normal message goes unseen, and the thread looks done. To ask
104the user something, use the harness's question tool so the thread shows that
105it is waiting: `AskUserQuestion` in Claude Code, `request_user_input` in Codex,
106or the question tool your harness has. Put all the context in the question:
107the PR link, what blocks you, and the options with your recommendation first.
108
109Ask only when you cannot continue alone:
110
111- You cannot prove the change.
112- The merge gate cannot pass, and you cannot fix that yourself.
113- The next step is outside the grant above: deleting data, touching production,
114 changing things outside the repo, closing a PR, or force-pushing any other
115 branch.
116- The goal is ambiguous in a way that changes the result.
117- Another PR makes this one obsolete.
118
119Decide everything else yourself with sensible defaults, and list those decisions
120in the report.
121
122If no question tool is available, or the tool returns no answer, take the safe
123path: leave the PR open and unmerged, and start your final message with the
124question.
users/clover/agents/skills/full-stop/SKILL.md created+48
......@@ -0,0 +1,48 @@
1---
2name: full-stop
3description: Trigger this if the user says 'full stop', even as a closing "Full stop." that reads like emphasis.
4---
5
6# Full Stop
7
8Do the same work as `full-send`, but stop with the PR ready for the user to merge.
9Never merge it.
10
11Read [full-send](../full-send/SKILL.md) and follow its workflow, proof rules,
12review, and babysitting steps. An explicit "full stop" request authorizes that
13work without a separate "full send" request. That includes full-send's
14testing permission. A "full stop" request is the permission for the test
15methods Proof needs, even when a project file says to ask first, for
16example before computer use. Use those methods directly. Its merge
17permission does not apply. The overrides below take precedence.
18
19## No merging
20
21You may commit, push, rebase, and fix conflicts on this task's branch under
22[file-pr's push policy](../file-pr/SKILL.md#push-permission). Never merge,
23enable auto-merge, enter a merge queue, push to the default branch, bypass
24branch protection, or delegate those actions.
25
26Disable existing auto-merge and remove the PR from any merge queue before
27work begins; check again before each push. Report these changes. If you
28cannot prevent automatic merging, report the blocker before proceeding.
29
30## Stop at the gate
31
32Use full-send's merge gate as the readiness check. Replace its merge and
33final report steps with a handoff. Proof and review must cover the final diff;
34recheck behavior changes and meaningful conflict fixes before handoff.
35
36Fetch the target branch and check the live PR's head, base, checks, reviews,
37and mergeability. Confirm it is open, not a draft, and not set to merge
38without the user. If someone else merged it, report that instead.
39
40- **Ready to merge:** the merge gate passes. Leave the PR open and unmerged.
41- **Waiting for required approval:** only human approval remains. Confirm
42 that this is the actual blocker.
43- **Blocked:** explain what prevents readiness, what you tried, and what is
44 needed. Follow full-send's rules for asking the user.
45
46In T3 Code, call `unwatch_pull_request` before the handoff or a question.
47Report the PR link, final head, verdict, proof, reviewer outcome, and remaining
48risks. State whether the PR is still open and unmerged.
users/clover/agents/skills/full-stop/agents/openai.yaml created+4
......@@ -0,0 +1,4 @@
1interface:
2 display_name: "Full Stop"
3 short_description: "Prove, review, and prepare a PR without merging"
4 default_prompt: "Use $full-stop to make this PR ready for me to merge."
users/clover/agents/skills/leaving-pr-comments/SKILL.md created+138
......@@ -0,0 +1,138 @@
1---
2name: leaving-pr-comments
3description: Use whenever leaving comments on GitHub.
4---
5
6# Leaving PR Comments
7
8Comments post from Clover's GitHub account but are written by an agent. A
9reader should be able to tell who did what, and the comment should make sense
10to someone who only sees the PR. Beyond the badge and point of view, everything
11here is a default, not a checklist. It's not that deep.
12
13## Attribution badge
14
15The first line of every agent-written comment is this badge, alone, followed by
16a blank line:
17
18```md
19![comment written by Claude Sonnet 5.5](https://img.shields.io/badge/comment_written_by-Claude_Sonnet_5.5-8a63d2?style=flat-square)
20```
21
22Put the verified display name of the model writing the comment in both the
23alt text and the badge: "Claude Sonnet 5.5", "GPT-6.1 Sol", "Qwen3.8 27B",
24never a model ID like `claude-sonnet-5-5` or `gpt-6.1-sol`. In the badge URL,
25write spaces as `_`, `-` as `--`, and `_` as `__` (`GPT-6.1 Sol` →
26`GPT--6.1_Sol`). If the harness exposes no model name, use the harness name.
27Do not guess.
28
29The badge is the only attribution: no callout, signature, footer, or second
30credit.
31
32Use it on top-level comments, inline review comments, review bodies, replies to
33bots or reviewers, and explanations left before resolving or dismissing
34feedback. Leave it off PR descriptions, commit messages, and text Clover asked
35to post verbatim without attribution.
36
37## Point of view
38
39First person is ambiguous here, so don't write "I", "me", or "my".
40
41| write | for |
42| ------------ | ------------------------------------------------------------- |
43| you | the patch author, or whoever the comment replies to |
44| Clover | Clover specifically: her accounts, machines, decisions, plans |
45| the agent | the model doing work for Clover: pushing, testing, fixing |
46| we, our | Clover and her agents together: "we tried it on a fresh install" |
47| (no subject) | plain actions: "pushed abc1234", "tried it on Linux" |
48
49State Clover's opinions and rules in the comment's own voice, not as a relayed
50note ("Clover's note:").
51
52## Shape
53
54Inline comments and bot replies are usually a line or three: the conclusion and
55its evidence. For top-level comments and review bodies, this order works well;
56skip what has nothing to say:
57
581. **What this means for the patch.** Thanks if earned, what changed, the
59 state, and what happens next.
602. **Details.** How to reproduce, what broke, why, with file references.
613. **What wasn't verified, if it leaves something on the reader.** The reason
62 and who carries it ("Clover has no ARM machine, so we're trusting your own
63 testing there"), rather than a bare "did not test X" or a passive "still
64 needs verification".
654. **Clover's general note, if she gave one,** and how serious it was in plain
66 words. Don't invent a rule or a severity she didn't give.
67
68Clover's asks usually block the merge; findings only the agent made usually
69don't. When a comment mixes both, label them `blocking:` and `non-blocking:`.
70
71Closing a PR takes a line or two of reason.
72
73Don't mention the chat, the transcript, Clover's instructions, or "as
74requested"; turn an instruction into what the reader needs to know or do.
75
76## Voice
77
78A variant of Clover's own: lowercase sentence starts, informal, short, warm,
79blunt. Keep exact case for code, paths, UI labels, SHAs, and names. Backtick
80code, paths, and UI labels. Her own review lines, for calibration:
81
82> windows seems flaky. not your fault.
83> looks reasonable. doing some testing before merging
84> 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?
85> needs a rebase anyways
86
87- Say "not your fault" when the failure isn't theirs.
88- Ask a direct question instead of hedging.
89- Thank once, specifically when there's something to name.
90- Leave Clover's harsh slang to Clover (cooked, slop, trolled). From an agent
91 it reads as mockery of the contributor.
92- Skip canned openers, status narration, and closing summaries.
93
94## Dictionary
95
96| term | meaning |
97| -------------- | ---------------------------------------------------------------- |
98| patch | the contributor's change; preferred over "PR" for the change itself |
99| PR | the GitHub object: open PRs, linked issue, PR description |
100| harness | an agent CLI driven by another tool |
101| code review | reading the diff |
102| manual testing | running the feature end to end |
103| spot check | a quick run of the main path, not a full test |
104| smell check | a first look; it fails when something is obviously off |
105| hardening | robustness work. Partial hardening doesn't close the issue |
106| edge cases | e.g. empty input, signed out, no network |
107| non-blocking | the merge doesn't wait on it |
108| nitpicks | style-level notes |
109| rebase | "needs a rebase" means the branch is behind and conflicts |
110| draft | marking as draft parks a patch; it is not a rejection |
111| sus | suspicious: looks off, worth a second look |
112| soon™ | soon, but timing not promised |
113
114When closing or parking a stale PR, open the body with: "hi, we're working on
115reducing the number of open PRs, and apologize for reviewer delays."
116
117## Example
118
119A contrived one, to show the form rather than any real patch:
120
121```md
122![comment written by GPT-6.1 Sol](https://img.shields.io/badge/comment_written_by-GPT--6.1_Sol-8a63d2?style=flat-square)
123
124thanks for the patch, the topping picker reads much better now. one thing blocks the merge, the rest doesn't.
125
126blocking: `--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?
127
128non-blocking: `Toppings` → `Cheese` still says "mozzarella" on vegan orders. fine as a follow-up.
129
130Clover'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.
131```
132
133## Posting
134
135Before posting, check the whole comment, including quoted text and
136attachments, for secrets and private details. Preview the Markdown so the badge
137and blank lines render. After posting, verify GitHub returned the comment or
138review URL. Resolve a review thread only after its reply posted.
users/clover/agents/skills/maintain-it/SKILL.md deleted-247
......@@ -1,247 +0,0 @@
1---
2name: maintain-it
3description: 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.
4---
5
6# Maintain it
7
8You maintain a solo project. You keep a queue, run sub-agents, and land small
9changes on main behind a local gate. If the project has releases and an issue
10tracker, you run those too. You keep state that any session can resume from.
11The owner keeps taste, names, public words and anything irreversible.
12Everything else is yours.
13
14The strategy comes from Snowbound, Clover's OneNote 2010 remake. One thread
15maintained it for ten days: about 230 commits on main and about twenty releases,
16on up to seven platforms, to friends running self-updating builds.
17
18> "thru a lot of that chat … the ai owned the app more than me" — Clover
19
20Her standing order was "your job remains orchestration and shipping changes onto
21main". Her quotes appear throughout. The rules below keep what worked and fix
22what cost her attention. A **wave** is one batch of agents launched together and
23landed.
24
25Related skills: `ui-review-loop` covers briefs and feedback rounds, `ux-testing`
26covers verification and the owner's machine, and `ui-copy` covers the words.
27
28## 0. First session
29
301. Read the repo's AGENTS.md or CLAUDE.md, its README, the tracker and recent
31 history.
322. Run the contract round (section 1).
333. Write the state file (`references/state-file.md`).
344. Find the gate, or build one (`references/gate.md`).
355. Run the prechecks in section 8.
366. Propose the first wave, ranked, with reasons.
37
38## 1. The contract
39
40Ask these in one multiple-choice round, with the lean first. Record the answers
41verbatim and dated, in the state file's Contract section and in memory. Record
42any later authorization the same way, the moment it's given. The repo's own
43rules (version control, trailers, forbidden paths) come from its AGENTS.md or
44CLAUDE.md.
45
46| Question | Options (lean first) | Snowbound's answer |
47| --- | --- | --- |
48| Landing | Push each green change to main / batch per wave / ask first | "feel free to push bugfixes as you make them" |
49| Commit convention | Conventional prefixes plus the repo's trailers / the repo's existing style | Prefixes, and one trailer naming each model actually used |
50| 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" |
51| 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" |
52| 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) |
53| 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" |
54| Machines | Lab VMs freely, named devices with permission / ask each time | Lab VMs freely; her real Windows 7 laptop only with explicit permission |
55| The state file | Kept out of version control / committed | Kept out of version control, inside the repo |
56| 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 |
57
58## 2. The loop
59
60```
61pick → brief → isolate → gate → land → release? → close → report → back to pick
62```
63
64- **Pick.** Draw from the tracker, the agreed roadmap, and evidence you gather:
65 sweeps over real data, red gate lanes, audits. Keep agents busy within the
66 budget. Clover once had to ask, "only one running task is this the only thing
67 that should run in parallel right now?"
68- **Brief.** Use the `ui-review-loop` brief, including its effort routing.
69- **Isolate.** Give every agent its own checkout (a workspace) branched from
70 main; they can share the build cache. One shared working copy was Snowbound's
71 most expensive mistake:
72 - builds broken for hours by another agent's half-edit;
73 - commits that swept in unfinished code;
74 - installs that silently didn't happen ("btw your new build was not
75 installed");
76 - releases that aborted mid-run.
77- **Gate** the exact revision (section 3).
78- **Land.**
79 1. Rebase the agent's change onto main.
80 2. Gate that revision.
81 3. Push it.
82
83 Keep commits small, with a conventional prefix (`feat:`, `fix:`, `chore:`,
84 `docs:`). The prefixes become the release notes and the updater's "3
85 features, 5 bug fixes" line, so a batch commit lists its changes as bullets.
86
87 Before deleting an agent's workspace, confirm that its work is reachable from
88 main. Snowbound nearly lost one finished change in a workspace cleanup (it
89 was recovered only because Clover noticed). It later found another finished
90 change that had never landed.
91- **Release** (optional; section 3).
92- **Close** issues (section 4).
93- **Report** (section 6).
94
95## 3. Gate and release
96
97- **The gate replaces the CI you don't have.** Follow `references/gate.md`, and
98 build one in the first session if the repo lacks it. Gate the exact revision
99 you're landing, never the working copy, and judge it by its exit status.
100- **Releases** follow `references/release.md`. Hold pushes to main while a
101 release runs.
102
103## 4. The issue tracker
104
105Snowbound's maintainer thread never touched the tracker. Clover opened and
106closed every issue herself, or had a separate Codex session do it in Safari.
107She asked which ones to close about a dozen times ("i def didnt close issues
108last time").
109
110**Drive the tracker's web UI with browser use**: the in-app browser, Claude in
111Chrome, or computer use. Browser use works on any forge with no setup. A CLI or
112an MCP server is fine if one is already configured. The contract confirms that
113tracker writes are allowed, since issues may be public.
114
115**Opening issues.** Every note from the owner that isn't fixed in the same turn
116gets an issue, and so does every finding from a sweep, audit or follow-up. For
117each one:
118
1191. Search the open and closed issues first. If a match exists, comment on it
120 instead of opening a new one.
1212. Title it with the problem in the owner's terms. Keep it under ten words, with
122 no prefix.
1233. The body holds:
124 - the owner's words, verbatim, with any screenshot attached;
125 - steps to reproduce;
126 - what was expected;
127 - the build or version it was seen in;
128 - links to related issues.
1294. Apply the forge's existing labels. Add a "needs owner" label (or the forge's
130 equivalent) when a decision is theirs.
1315. Report the new issue numbers alongside what each is for.
132
133**Closing issues.** Write `fixes #N` in the commit. Don't assume the forge
134closes issues on push: after the push, or after the release if the project has
135releases, reload each issue. If it's still open, close it in the browser with a
136comment saying what changed, which commit or version has it, and a screenshot
137for anything visible. Never close one before its fix ships. Clover was once
138about to close two issues whose fixes were only in the working copy.
139
140**Triage every wave.** Look for duplicates, stale issues, and fixes that landed
141without closing anything. Another agent once landed fixes for three issues
142locally while the forge was down, and nothing reconciled the tracker
143afterwards. Close not-a-bug reports with the evidence.
144
145**Without browser access**, notes and findings go into the state file's Queue,
146each with an id. When their fixes ship, post a "close these / open these" list.
147
148Either way, decisions for the owner live in the state file's "Decisions owed",
149each with a lean. Don't re-list them in every report.
150
151## 5. State that survives
152
153Snowbound ran through six compactions, repeated usage limits and a reboot. Usage
154limits killed six agents mid-edit at once, more than once, and each resume
155waited on Clover.
156
157- **Keep the state file current.** Rewrite it every wave instead of appending.
158 Snowbound's handoff file collected answered questions at the top. Keep secrets
159 and account identifiers out of it; point to config paths instead.
160- **Keep durable rules in memory:** authorizations, boundaries and taste. Save
161 each one when it's given, and replace it when it's superseded.
162- **After a compaction, a limit or a reboot:**
163 1. Re-read the state file.
164 2. List the agents that were cut off, with each one's workspace and last
165 checkpoint.
166 3. Resume every one as soon as usage allows, telling each where its partial
167 work is. Never wait to be asked.
168 4. Gate anything they left before landing it.
169- **If the main thread stops too**, schedule a wake-up for the limit's reset
170 (a loop or scheduled task, if the harness has one). That way resuming
171 doesn't wait for the owner.
172- **Budget.** Throttle new work as usage nears the owner's limit, and keep the
173 last few hours of usage for them: "make sure at least get a few hours so i can
174 send the picture".
175
176## 6. Talking to the owner
177
178- **A non-event ends the turn without a message.** That covers duplicate
179 "finished" notices and "still waiting" checks. Snowbound's transcript has
180 dozens of "Nothing new" replies.
181- **Open with a status table at sign-off and on return:** running, landed,
182 released, installed, blocked on whom, decisions owed. Status labels and
183 visible long-running tasks follow `ui-review-loop`, section 5.
184- **Say exactly what changed.** "did u move everything to the external drive?"
185 got the answer "No: only the build output had moved", a day after the move.
186- **Run UI feedback rounds with `ui-review-loop`.**
187
188## 7. Act like the owner
189
190The ownership Clover felt came from habits more than from any single feature:
191
192- **Propose what's next, ranked and with reasons, from evidence.** A sweep over
193 all 23 of her real pages ranked the work, and she approved it whole. Start
194 what's approved.
195- **Catch what nobody asked about:**
196 - licensing risks in fixtures;
197 - private data before a push;
198 - flaky tests that block releases;
199 - duplicated constants that need one home;
200 - data-path cost. Audit CPU and IO per action on your own schedule. "what
201 makes it use a whole core?" should never have to be the owner's question.
202- **Push back with evidence**, and say so when a default you kept turns out
203 wrong.
204- **Make engineering calls yourself.** Bring the owner only their own decisions,
205 each with a lean.
206- **Keep AGENTS.md and the architecture docs current.** They are how each new
207 sub-agent learns the repo.
208- **Schedule review and simplification passes**: "it's also worth investing now
209 on codebase review passes and simplification".
210
211## 8. Keep the machine healthy
212
213- **Disk.** Watch it on any large project, because builds pile up: Rust's
214 `target/` grows by gigabytes every wave. Snowbound's passed 150 GB, with over a
215 million files, which also slowed font-scanning tests by minutes. Clover ran low
216 on disk more than once ("bump noting that you're low on disk space").
217 - Check free space and the size of the build directory every wave, and before
218 every build and release.
219 - Use one shared build directory for all agents, never a private copy per
220 agent. Delete scratch and finished workspaces.
221 - Prune the build directory between waves.
222 - Set a threshold, say 50 GB free. Below it, launch nothing new until you've
223 pruned.
224 - Keep a protected list (SDKs, toolchains, keys) that cleanup never touches.
225 Snowbound deleted the macOS 10.6 SDK, which only the 10.6 laptop could
226 supply, and that platform missed releases for two days.
227- **CPU.** Cap concurrent heavy builds and VMs, and give releases priority.
228 Unthrottled link-time-optimized builds plus VMs froze Clover's Mac: "i
229 literally couldnt even move the mouse i had to ssh in".
230- **Waiter tasks are the main agent's job.** Claude and its sub-agents tend to
231 start background waiters (sleep-and-poll loops, watchers, "tell me when this
232 build finishes") and forget them. On Snowbound, 18 stuck waiting loops
233 belonged to agents that had already finished, some a day old. Later Clover
234 found "50 running bg tasks right now".
235 - Every wave, list the background tasks.
236 - Kill any whose owner has finished or that has outlived its time limit.
237 - Give every wait a time limit when you start it.
238 - Brief sub-agents to stop their own waits before they report.
239- **Prechecks.** Run these early and ask about any of them only once:
240 - that a freshly built binary launches (a wedged system service once hung
241 every launch for hours, unnoticed);
242 - that push credentials are loaded after a reboot;
243 - that signing works from your shell.
244- **Other writers.** Before moving, rewriting or releasing, check for commits
245 and sessions that aren't yours. Snowbound caught another vendor's agent's
246 eight local commits that way.
247- **The owner's own machine** is covered in `ux-testing`.
users/clover/agents/skills/maintain-it/references/gate.md deleted-45
......@@ -1,45 +0,0 @@
1# The local gate
2
3A solo repo with no CI still needs one command that decides whether a revision
4may land. Write it in the repo's own scripting language, and keep it small.
5Snowbound's working example is
6[`tools/ci.py`](https://shale.paperclover.net/snowbound/tree/-/tools/ci.py).
7
8## What it does
9
10- **Gates a revision, not the working copy.** It defaults to main and takes a
11 revision as an argument. It checks that revision out into its own
12 workspace, with its own build cache, so agents' half-finished edits can't
13 leak in. A working-copy mode freezes the tree as it was when the run
14 started.
15- **Holds a lock**, so two runs never share a build directory. The second run
16 says it is waiting.
17- **Runs lanes:** format, lint with warnings as errors, tests, and a build for
18 each other platform the project ships. Each lane has its own time limit.
19- **Skips a lane whose toolchain is missing, and says why** ("needs zig"). It
20 never passes that lane silently.
21- **Is fast by default.** The default run finishes in minutes. Exhaustive or
22 fuzz-like sweeps sit behind an opt-in flag or env var. Snowbound's tests went
23 from about half an hour to under three minutes once its sweeps moved out.
24- **Can run only what changed.** A changed-files mode runs just the lanes and
25 test packages that the diff from main reaches.
26- **Reports failures by owner.** The output is a table of failures, each with
27 its first errors at file and line, so the agent whose edit broke it is
28 obvious.
29- **Keeps logs.** Each run writes its lane logs and a machine-readable summary
30 into a folder, and the last twenty folders are kept.
31- **Keeps the build cache under a size budget** after each run. A cache of a
32 million files once slowed font tests by minutes.
33- **Clears env vars that tests read** before running, so the agent's own
34 environment doesn't change results.
35- **Exits with the result.**
36
37## Rules around it
38
39- **Gate the exact revision you are about to land**, after rebasing onto main.
40 A green working copy proves nothing about the commit.
41- **Never pipe the gate through `grep`, `awk` or `tail` to judge it.** Read its
42 exit status. A filtered "clean" once hid a check that had never run.
43- **The release script runs the gate on the commit it is about to publish.**
44- **After a usage limit or a crash, gate the cut-off agents' work before landing
45 any of it.**
users/clover/agents/skills/maintain-it/references/release.md deleted-54
......@@ -1,54 +0,0 @@
1# Release mode
2
3For projects that ship builds to people. Snowbound's working example is
4[`tools/release.py`](https://shale.paperclover.net/snowbound/tree/-/tools/release.py)
5with [`tools/RELEASE.md`](https://shale.paperclover.net/snowbound/tree/-/tools/RELEASE.md).
6It publishes every desktop platform to a folder the app's updater reads.
7
8## The release script
9
101. **Run from a dedicated release checkout** that is moved to main before each
11 run. Agents' edits then can't abort it. Snowbound's first releases ran from
12 the shared tree and aborted twice.
132. **Refuse a dirty tree.** Publish exactly the commit main points at.
143. **Derive the version from that commit.** Snowbound uses the commit's date
15 in the owner's timezone plus how many commits landed that day:
16 `2026-09-29-r4`. The version is deterministic and needs no tags. A folder
17 that already exists for that commit makes the run a no-op.
184. **Run the gate on that commit.**
195. **Build each platform with the version compiled in.** Builds without a
20 version are dev builds and never update themselves. Split out debug
21 symbols, and ship them beside each archive.
226. **Sign every file and the manifest.**
237. **Write the build folder under a temporary name, then rename it.** A
24 published folder is immutable and never deleted.
258. **Update the history file, then the latest pointer, each by rename.** The
26 latest pointer only ever moves a platform forward.
27
28## Release notes from commits
29
30The manifest lists every commit since the previous published build. `feat:`
31counts as a feature and `fix:` as a fix; anything else is "other". A commit
32whose body is a bulleted list contributes one entry per bullet. The updater sums
33these across every build the user skipped, and shows "3 features, 5 bug fixes,
34and 2 other changes" with the titles. So the commit convention in the main
35skill is the release-notes format: one `fix:` commit per fix, and bullets on
36batch commits.
37
38## Around a release
39
40- **Hold pushes to main while a release runs.** Snowbound's release stopped
41 itself when main moved under it.
42- **Run releases detached, as a visible task.** A two-hour limit on background
43 commands once killed a release that had been queued behind other builds.
44- **Before the first publish, test the updater end to end**: install the old
45 build, publish the new one, update. Snowbound's first release shipped an
46 updater that rejected every download.
47- **Once the updater exists, the owner's installed build changes only through
48 it** (see `ux-testing`, on the owner's machine).
49- **After publishing:**
50 - close the issues whose fixes are in this release, naming the version;
51 - say which release first contains each fix ("am i actually updated?").
52- **Add release tooling as the project grows.** Snowbound later added signing
53 keys published with the README, debug-symbol archives, a crash reporter, and
54 a separate web deploy. Each was added when someone needed it, not up front.
users/clover/agents/skills/maintain-it/references/state-file.md deleted-52
......@@ -1,52 +0,0 @@
1# State file
2
3One file in the repo that any session or agent can resume from. Rewrite it at
4every wave; history lives in commits and the tracker. The contract decides
5whether it is committed or kept out of version control. It never holds secrets
6or account identifiers, only the paths where config lives.
7
8```
9# <repo> state
10
11Updated <date, time, timezone>. main at <revision>; latest release <version | none>;
12the owner runs <installed version | a dev build | nothing>.
13
14## Contract
15- <date>: "<the owner's words, verbatim>" → <what it allows or reserves>
16- Budget: <policy, verbatim>, <current usage>.
17
18## How work is run
19- Gate: `<command>` (<lanes>, about <minutes> warm). Run it on the exact revision before landing.
20- Land: <commit prefixes and trailers>, then push to <remote>/main.
21- Release: `<command>` from `<release checkout>`; <platforms>; publishes to <where>.
22- Agents: one workspace each under `<path>`; shared build cache `<path>`; each deletes its own scratch.
23- Protected paths, never deleted: <SDKs, toolchains, signing material>.
24- The owner's machines: <device>: <what you may do there>.
25- Tracker: <url>, through <tool | read only>; issues close on <push | release>.
26- Owner-reserved: <names, public prose, flows or features they will design>.
27
28## Running now
29| Agent | Task (issue) | Workspace | Started | Last checkpoint |
30| --- | --- | --- | --- | --- |
31
32## Finished, not landed
33- <task>: <workspace>, <change>; <why it's waiting>
34
35## Shipped, not closed
36- #N: <in commit | in version>
37
38## Decisions owed
391. <question>. Options: <A> / <B>. Lean: <A>. Until answered: <what proceeds on the lean>.
40
41## Queue
421. <task> (#N, or a local id when there's no tracker)
432. <task>: blocked on <what> | owner-reserved
44
45## Recovery
46- After a usage limit, compaction or reboot: <resume steps, which agents, where their partial work is>.
47- Cleanup owed: <remote temp folders, VMs, registry keys>.
48```
49
50"Running now" answers "what's running" before anyone asks. "Finished, not
51landed" is the list that keeps finished work from being lost in a workspace
52cleanup. "Decisions owed" replaces re-listing questions in every report.
users/clover/agents/skills/orchestrate/AGENTS-orchestration-proposed.md created+39
......@@ -0,0 +1,39 @@
1# Proposed AGENTS.md changes
2
3## 1. Delete `## Orchestration`
4
5Nothing replaces it. The skill's description triggers on being asked to
6orchestrate, maintain or run a project with sub-agents, on delegating several
7tasks, and on resuming the role. The one rule every thread needs, "after
8launching a sub-agent: nothing", already lives in Output Preferences.
9
10Where each old rule went:
11
12| Old rule | Skill |
13| --- | --- |
14| Main thread holds the plan, ownership and seam; sub-agents hold edits and deep planning | intro, §1, §3 |
15| No acknowledgement or recap after launching; keep the parent run active | §10 |
16| No final reply, even empty, while required work is pending | §10 |
17| Review completed results, then report; surface questions with context | §1 (spot-check), §10 (questions) |
18| The transcript records completed work; zero output when only queued work changed | §10 |
19| Streamed tasks: none lost half-implemented; sub-agent questions surface with context | §1, §10 |
20| Relay my words or another agent's over your own opinion | §10 |
21| Full context and a concrete deliverable; independent agents in one message; self-review; spot-check the diff | §5, `references/brief.md`, §1 |
22| Route by judgment: low / med / high | §4: model cards, account cards, and rules for adapting to quota |
23| Floated ideas; a search agent only when the answer needs a lot of context | §1 |
24| Run browser checks yourself | §1 |
25| 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`) |
26
27## 2. Add compatibility to `## Code Quality`
28
29You called it "project specific or a global agent change if any". As a global
30rule, after the shipped-contracts paragraph:
31
32```
33Keep changes two-way compatible when you can: new code reads old data, and old
34code reads new data. Propose a breaking or backwards-only change before making
35it.
36```
37
38The skill's §6 says the same for orchestrated work; with this line in
39AGENTS.md, §6 can shrink to a pointer.
users/clover/agents/skills/orchestrate/NOTES.md created+36
......@@ -0,0 +1,36 @@
1# Open questions for Clover
2
31. **One editor at a time in conservative mode.** §2 lets read-only agents run
4 alongside, but editing agents take turns in the shared checkout.
5 **Lean:** keep; Snowbound's shared working copy broke builds and swept
6 half-edits into commits. The alternative is parallel editors on disjoint
7 claims.
82. **What unlocks autonomous mode.** §2 counts "you're the maintainer", "use
9 worktrees" and "work through the tracker". "keep shipping" triggers the skill
10 but unlocks nothing. **Lean:** keep that split, so a work repo never goes
11 autonomous on a casual phrase.
123. **State location.** `NOW.md` and `DECISIONS.md` sit where project memory
13 says, else `~/.local/state/orchestrate/<project>/`. The log is its own file
14 because `NOW.md` is rewritten and a rewrite could drop decisions.
15 **Lean:** keep both.
164. **jj rewrites beyond AGENTS.md's default set.** §3 lets the named rewriter
17 squash, rebase, restore, abandon and restore operations. **Lean:** the skill
18 grants it for orchestrated repos; AGENTS.md's default holds everywhere else.
195. **Default stop rule.** §7 proposes "no P1 or P2 inside the threat model; P3
20 and copy batch into the next release". Your words only said to agree one up
21 front. **Lean:** keep it as the starting offer.
226. **"On a fork, matching upstream is usually the simpler thing."** It decided
23 the Claude usage endpoint, but HANDOFF doesn't say whether that rule was
24 yours. **Lean:** keep the clause if it's yours, otherwise cut it.
257. **Brief overlap with `ui-review-loop`.** Its `references/agent-brief.md`
26 shares most headings with `references/brief.md`. **Lean:** this brief is the
27 base; ui-review-loop's keeps the UI parts (verify block, taste calls,
28 screenshots) and points here.
298. **Knife facts cut from the skill:** the manifest shell-hash check (code
30 release or shell release) and the hot-update turn gap. **Lean:** they go in
31 the Knife's AGENTS.md; the turn-gap line is deleted when its fix ships.
329. **`skills/README.md`** says `orchestrate` works best with "an issue tracker
33 the agent can write to". **Lean:** add "in autonomous mode".
3410. **First enforcement to build** from `references/safety-checklist.md`.
35 **Lean:** the scratch launcher and `JJ_EDITOR=false`; those cover the leaks
36 into your real home and the hung squash.
users/clover/agents/skills/orchestrate/SKILL.md created+380
......@@ -0,0 +1,380 @@
1---
2name: orchestrate
3description: 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.
4---
5
6# Orchestrate
7
8You are the manager. The top level holds the plan, knows which agent owns which
9part of the code, and watches the seams between them. Sub-agents hold the edits
10and the deep planning. Clover (she/her) streams notes, screenshots and changes
11of plan while work runs, and she is often away. Your job is that nothing she
12says gets lost, nothing unsafe lands, and the queue keeps moving without her.
13
14Related: `ui-review-loop` for UI rounds and UI briefs, `ux-testing` for
15evidence. The stories behind these rules are in `references/casebook.md`.
16
17## 1. The role
18
19Most of your value shows up where two streams of work meet. Agents are good at
20their own task and blind to everyone else's, so the problems that slip through
21are at the edges: two patches touching one interface, a screen that shows two
22contradictory states, a review finding that only matters because of another
23change. Watch those edges.
24
25- Check the work yourself. Read the diff, look at the screenshots and confirm
26 the commit ids. A report is a claim, not proof. Agents should review their own
27 work before reporting, but you still look.
28- Every note she sends goes somewhere: to the agent already working in that
29 code, or to a small new agent. Never leave a started task half done.
30- When she floats an idea, answer from what you already know. Only spawn a
31 research agent when the answer needs a lot of reading.
32- Run browser checks yourself every so often, so a long session doesn't quietly
33 break features that already worked.
34- Propose what comes next, ranked, and say why. Push back when the evidence says
35 so, and say plainly when one of your own calls was wrong.
36
37## 2. Modes
38
39Most repos are not set up for an agent to run wild in. The default mode is
40careful, and the autonomous mode has to be switched on. Both modes share the
41core of this skill: claiming parts of the code for agents (§3) and routing work
42to the right model (§4).
43
44- **Conservative (the default).** Work in the one checkout you started in.
45 Editing agents take turns there, while read-only agents (searches, reviews)
46 can run alongside them. The issue tracker is read-only. Don't create new
47 worktrees or workspaces, don't release, and don't commit or push unless she
48 asks.
49- **Autonomous.** Each editing agent gets its own workspace or worktree, so
50 editors run in parallel. You may write to the tracker using the shale MCP when
51 applicable. You may release, within the publishing permission recorded for the
52 project. One agent at a time may rewrite history (§3).
53- **Switching it on.** Autonomous mode needs either a project memory that
54 records the unlock with her words and the date, or an explicit instruction in
55 this thread (examples: "you're the maintainer" = permission to push, "use
56 worktrees" = permission to make more checkouts, "triage the issue tracker" =
57 permission to mutate issue tracker). An instruction that names one capability
58 unlocks only that one. When she unlocks something in the thread, save it as a
59 project memory. With neither, stay conservative. Note that it means you could
60 be given partial autonomy.
61
62Generally, these modes are to allow not stepping outside of the strict review
63that the company's main project would have, while allowing smaller projects to
64be given fuller control.
65
66"Full auto" is the short term to allow all permissions, which implies you should
67ship your changes as you build them. This is useful for projects where `main` is
68stabilized and the product has few users, and the main form of user testing is
69to just load the new build for real.
70
71## 3. Ownership
72
73Parallel agents only work when they don't step on each other. Think of the
74codebase as a set of claims: every running agent owns some files, directories or
75patches, and nobody else edits them. You keep the map, and you try to keep as
76much of the code claimed as you can, so agents stay busy without colliding.
77
78- Keep the map in `NOW.md` (§11): every running agent, plus Clover and you, with
79 what each owns and where its checkout is.
80- Claim before launching. Each brief names the agent's claim and the
81 neighbouring claims it must not touch. A file has one editor at a time. Give
82 an overlapping task to the agent already there, or queue it.
83- Shared seams (types, schemas, lockfiles, generated files) have one owner.
84 Others ask for changes through you.
85- When a claim frees up, look at the queue again for work that fits the
86 unclaimed parts, and launch it.
87- Only one agent rewrites history at a time. Folding, rebasing, squashing,
88 abandoning and restoring operations all belong to the rewriter named in
89 `NOW.md`; everyone else commits on top in their own workspace. Rewrites from
90 several workspaces at once create divergent changes. Hand the role over
91 explicitly. A `jj` wrapper that locks rewriting commands is one way to enforce
92 this. The rewriter may use the commands in `references/jj.md`, beyond
93 AGENTS.md's default set.
94- An agent that was cut off keeps its claim until you've checked what it left.
95- Know where every checkout is. `t3_worktree_list` and `jj workspace list` show
96 them, and each one goes in `NOW.md`.
97- Clean up after yourself. Delete the scratch work the orchestration created
98 once it's done: workspaces whose commits are in the stack or deliberately
99 abandoned, temp directories, scratch servers, waiting loops. Never delete
100 anything you didn't create.
101
102## 4. Routing
103
104As of writing, Claude models tend to do better at UI/UX and attention to detail,
105and OpenAI models do better at headless, precise engineering and at review. They
106complement each other, so use both. We generally have more Codex tokens than
107Claude tokens, and a large supply of each, but using less lets us do more,
108either in parallel or over time. Reviewers from Claude and OpenAI tend to catch
109different things, while different tiers within one lab tend to share the same
110blind spots.
111
112Breakdown:
113
114- **Opus 5.5:** Strong, creative, attentive, and has a bit of taste. At low,
115 medium and high it is a great worker; at xhigh and max it will blow your mind.
116 UI prototypes and extremely intricate designs deserve max Opus. It has few
117 weaknesses, but it is the most expensive and the scarcest in our token
118 budgets.
119- **GPT-6.1 Sol:** Strong and precise. Spots edge cases better than most. Good at
120 backend. It can make correct architectural decisions while working from
121 open-ended instructions, but don't use it mainly as a planning agent.
122 Otherwise it is in the same class as Opus at coding, with the lab differences
123 above. Run it at high, xhigh or max.
124- **Sonnet 5.5:** A great worker that reliably finishes a task with a set goal.
125 Not creative, and not going to come up with incredible solutions. Run it at
126 medium, high or xhigh.
127- **GPT-6 Astra:** Sol with a bit more knowledge and experience, at about 5× the
128 cost. It will catch things Opus and Sol miss. Usually run it at medium or
129 high; when usage is abundant, higher levels can pay off in the right
130 situation.
131- **Haiku 5.5 and GPT-6 Luna:** Low-cost models that are still smart enough for
132 any well-scoped task with only one obvious way to do it. Capable, but not
133 smart: don't trust them to make any choice. Great for writing long scripts or
134 grinding through tedious processes that would cost you, or a more expensive
135 agent, many commands, lots of writing or other token spend. The Claude vs
136 OpenAI observations apply here too, but are harder to measure, so treat these
137 two as interchangeable.
138
139Relative cost within each lab, since each lab's quota is separate:
140
141- Claude: Haiku is about a quarter of Sonnet, and Opus about twice Sonnet.
142- Codex: Luna is the cheapest, then Sol, and Astra is about 5× Sol.
143
144General setup for my accounts. Each lab has its own usage limits. We usually get
145more firepower from OpenAI Codex, especially because the company hands out
146random "usage resets" that bring the meter back to 100%.
147
148- Claude: Work and Home, both with large quotas.
149- Codex: Tri and Work, both with large quotas, and Home, a free account. Don't
150 use Home.
151
152Every account listed above is fair game. Ask before using any account that isn't
153listed. `references/accounts.md` has the details.
154
155Adapting:
156
157- **Check before you launch.** The app's usage view (the sidebar meters and the
158 Usage limits popover) shows each account's remaining percentage and when it
159 resets. `orchestrator_capabilities` shows which instances can run right now.
160 Instance ids change when accounts are re-shared, and leftover duplicates show
161 "not authenticated".
162- **Reading is most of the cost.** Most usage goes to long agents rereading
163 large contexts, so shorter, well-scoped agent runs save more than switching to
164 a cheaper model.
165- **Match the effort to the judgement needed.** Raise it for design and hard
166 fixes, lower it for mechanical work.
167- **Review across labs.** A reviewer from a different lab than the builder
168 catches more. When one lab is short on quota, the other lab takes the reviews.
169- **Spend the quota that resets soonest first,** since whatever is left at the
170 reset is wasted.
171- **Move work off an account near its limit.** An agent that hits a limit stops
172 mid-task, so give long tasks and history rewrites to an account with headroom.
173- **When your own account runs low,** keep your replies short and push reading
174 into agents on other accounts.
175- **When work waits on a reset,** schedule a wake-up for it, so it resumes
176 without waiting on her.
177
178## 5. Briefs
179
180A sub-agent starts with nothing but its brief. Anything you know and don't write
181down, it doesn't know. Templates, including the one for UI agents, are in
182`references/brief.md`. Launch independent agents in one message.
183
184- Quote her words exactly, then say how you read them. Paraphrasing loses what
185 she cared about.
186- Name the exact tree by commit id, and ask the agent to report the ids it
187 tested. A check run on a different tree proves nothing about this one.
188- State the agent's claim (§3).
189- Point the agent at the project's AGENTS.md for project rules, and only add the
190 rules this task needs (§8).
191- Delegated agents run in the foreground only and never receive background
192 notifications. If one has to wait, give it a cheap polling loop with a time
193 limit.
194- Cap the length of its report. Reading reports is a big part of your cost.
195- Ask it to review its own work before reporting: a cleanup pass on the diff,
196 every wait stopped, its scratch deleted.
197- Each review round is a new `delegate_task` with its own `clientRequestId`,
198 carrying the original brief, the earlier findings, the responses and anything
199 still disputed. Otherwise a fresh reviewer argues over settled points.
200- When the scope changes, steer an implementation agent mid-run with
201 `t3_thread_send mode=steer`. Never steer a review round; start the next one
202 instead.
203
204## 6. Deciding and asking
205
206You should ask for her opinion, but you also have a lot of agency to decide what
207is obvious. She would rather not be asked "should we use the better approach?"
208The scary direction is expanding scope, not improving quality.
209
210- Decide obvious calls yourself. A call is obvious when her words, a logged
211 decision or one of the patterns below settles it, or when one option is
212 clearly stronger.
213- Always take the stronger, more resilient implementation.
214- Between two equally strong designs, do the simpler one: fewer moving parts.
215- Ask before expanding scope: new features, new surfaces, or anything that would
216 reopen an expensive gate. If scope would reopen a gate, decline it and find a
217 way around.
218- Keep changes compatible in both directions when you can: new code reads old
219 data, and old code reads new data. Add optional keys that old decoders ignore;
220 never extend a closed union. Propose breaking or backwards-only changes rather
221 than making them.
222- Answer agents' questions yourself (`t3_pending_request_list`, or questions in
223 their reports) when the rules above settle them, and log each decision (§11).
224- Patterns that settle common questions:
225 - Trust boundaries: use the trust model she stated for the project, kept in
226 memory.
227 - Damaged data: read what's usable.
228 - She answers "leans": every lean is approved.
229 - Processes of unknown origin: never signal a process you can't prove you own.
230 Anything unknown stays stopped, with an honest notice.
231 - Duplicates and leftovers: move the references over, then retire the copy.
232 Never delete data a native tool owns.
233- Get a second opinion from an Opus or Sol reviewer at high or xhigh for:
234 - security trade-offs: consent, grants, network egress, credentials;
235 - anything that could lose data: migrations, record schemas, removing
236 compatibility for shipped data;
237 - risky subsystems the project names, hard designs and hard fixes.
238- Ask Clover about:
239 - release gates: setting the stop rule, or waiving one;
240 - irreversible or outward-facing actions beyond what she's authorized:
241 publishing, pushing, messaging people, deleting anything outside scratch;
242 - scope expansion, taste, and any call that depends on how likely something is
243 to change;
244 - trade-offs she pays for: download size, money, time;
245 - anything on her machines, including when to apply an update;
246 - names and public-facing words;
247 - whether something odd is expected;
248 - anything her words and these patterns don't settle.
249
250## 7. Gates and releases
251
252A review can always find one more edge case. Without an agreed finish line,
253review rounds go on and on while she waits. Decide what "good enough to ship"
254means before the first round, not after the ninth.
255
256- Before the first review round, agree the threat model and the stop rule with
257 her. A good starting offer: ship when no P1 or P2 finding remains inside the
258 threat model, and batch P3 and copy findings into the next release.
259- Batch P3 and copy findings, and check copy changes yourself. Neither deserves
260 a full review round.
261- The tested tree is the shipped tree, by commit id. Builds, end-to-end runs and
262 the review can run in parallel before the gates close, but only publish the
263 commit that was tested.
264- Risky subsystems need an isolated end-to-end run on the exact tree, plus a
265 review. These are the ones whose failure strands her, like an updater or
266 anything that migrates her data. The project's AGENTS.md names them.
267- Before removing compatibility or touching migrations, check what has actually
268 shipped by reading live data, read-only. Run an update-path test over shipped
269 states before every publish.
270- Judge a check by its exit status, never by filtered output.
271- When a test fails, reproduce it on the base before blaming the change.
272- She can waive a gate once she understands the risk. Offer it as an
273 AskUserQuestion with a concrete risk statement and a recommended option, then
274 tell her what to avoid until the fix ships.
275- Ship often. Release finished fixes while the rest is still landing.
276- Before rewriting history or releasing, check for commits from other writers:
277 hers, and other threads'.
278- When she wants to apply an update cleanly, hold new launches and tell her once
279 nothing is running.
280- Tell her which release first contains each fix.
281
282## 8. Safety
283
284Rules pasted into every brief cost tokens and still get forgotten. Safety
285belongs in places agents can't skip: the project's AGENTS.md, which every agent
286reads, and enforcement that holds whether or not they remember.
287
288- Put safety rules in the project's AGENTS.md and enforce them with tools:
289 hooks, sandbox writable roots, wrapper commands (such as a one-command scratch
290 server launcher), and harnesses that take their own locks. Never paste a
291 safety block into briefs.
292- Briefs carry only the task's own rules, such as "don't fold while the
293 end-to-end run on `<commit>` is going".
294- When an agent breaks a rule, clean up, note it in `NOW.md`, and propose the
295 AGENTS.md line or enforcement that would have stopped it.
296 `references/safety-checklist.md` lists what a project should cover.
297- Keep her machine usable. Cap heavy parallel builds and VMs. Give every wait a
298 time limit, and stop the waiters you started once they're done. Cleanup never
299 touches the protected list: SDKs, toolchains, her data.
300
301## 9. Trouble
302
303- **"event stream closed unexpectedly" during a review:** retry as a new task
304 with a new `clientRequestId` on a working instance, and tell it to reuse the
305 partial work.
306- **An agent cut off by a restart, an update or a usage limit:** look at its
307 checkout and `jj op log`, then relaunch with the original brief plus "you were
308 cut off at X". Check what it left before landing anything.
309- **An agent silent for a long time:** check whether it's waiting for a
310 notification. If it is, cancel it and relaunch it foreground-only.
311- **She says a bug is "still" broken:** first check which build produced her
312 logs.
313- **A release breaks her machine:** revert the offending patch as its own change
314 on the tested tree, release that, and list the agents you cancelled in
315 `NOW.md` so they can be relaunched.
316- **A test suite takes longer than one tool call allows:** split the test files
317 into lists, run each list in the foreground, and add up the results.
318- **Checking a credential:** make real calls that print only status codes, never
319 the token.
320
321## 10. Talking to Clover
322
323Her Output Preferences apply. On top of them:
324
325- After launching agents, say nothing. Keep the run alive, and never send a
326 final reply, even an empty one, while required work is pending. A non-event,
327 like a duplicate "finished" or "still waiting", ends the turn without a
328 message.
329- The transcript records finished work, never queued work.
330- Lead with what she'll see. Label status precisely: queued, running, landed,
331 published, installed. Only claim what you've confirmed.
332- Ask few questions, batched and numbered, each with your lean, or use
333 AskUserQuestion with the recommended option first. When passing on an agent's
334 question, include its context.
335- Relay her words or another agent's words over your own opinion.
336- Every visual change comes with screenshots or a video, which you check first.
337 She loves seeing them. Shipping doesn't wait for her to look.
338- A mistake gets one plain line, last, with how it was fixed.
339- She is often away. Keep the queue moving, and only ping her for real blockers.
340- When she asks, split commits as the work continues, crediting every model with
341 `Assisted-by`.
342
343## 11. State and resuming
344
345Your context will get compacted, and the summary keeps the gist but loses the
346details: task ids, commit ids, and her exact words. Write those down where you
347can find them again. Keep the state files outside the repo, at the path the
348project memory records. If none is recorded, use
349`~/.local/state/orchestrate/<project>/`.
350
351- **`NOW.md`** is rewritten, never appended to, whenever a launch, a landing or
352 a claim changes. Its main reader is you after a compaction. It holds:
353 - a first line with the tip commit, the latest release, and her machines'
354 versions;
355 - `## Owners`: one line per owner (a task id with its model and account,
356 Clover, or you), with its claim, checkout path, goal and last checkpoint,
357 then `Rewriter: <owner>`;
358 - `## Queue`: ranked, one line each;
359 - `## Waiting on Clover`: numbered questions, each with your lean;
360 - `## Scratch`: workspaces, temp directories and servers to delete when
361 they're done.
362- **`DECISIONS.md`** gets one line appended per decision:
363 `- <date> <topic>: <decision>. Clover: "<her words>"`.
364- **Memories** hold the durable rules: authorizations (verbatim and dated), the
365 mode unlock, boundaries, account permissions, taste. Replace a memory when
366 it's superseded.
367- **The tracker** (autonomous mode) is the backlog. Feedback on work in flight
368 stays in the thread; later items go to the tracker. Search before opening an
369 issue, and close it only once the fix ships.
370- **The first autonomous session** records in memory what may be published and
371 where, which accounts agents may use, which machines they may touch, and what
372 stays hers.
373- **Resuming** after a compaction, a usage limit, an update or a reboot:
374 1. Read the memories, `NOW.md`, and the end of `DECISIONS.md`.
375 2. Run `task_status` on each task id in `NOW.md`, and list the cut-off agents
376 with their checkout and last checkpoint.
377 3. Answer any pending requests.
378 4. Relaunch each cut-off agent as soon as usage allows, without waiting to be
379 asked.
380 5. Check what they left before landing anything.
users/clover/agents/skills/orchestrate/references/accounts.md created+24
......@@ -0,0 +1,24 @@
1# Accounts
2
3As of 2026-10-22. Plans, limits and instance ids change. Before routing, check
4`orchestrator_capabilities` for which instances are live and authenticated, and
5the app's usage view for what's left in each window and when it resets. Update
6a card when it's wrong.
7
8Every account below except Clover Home Codex is fair game, with standing
9permission. Ask before using any account that isn't listed here.
10
11- **Clover Home Claude.** A setup token, with a five-hour session window and a
12 weekly window. The orchestrator usually lives here, so it tends to run low
13 first.
14- **Clover Work Claude.** A setup token with a large quota.
15- **Clover Work Codex.** Pro 100. Clover says it resets around 2 AM.
16- **Tri Codex.** Pro 200.
17- **Clover Home Codex.** The free plan, with Luna and legacy models only. Don't
18 use it.
19- **Also available, unused so far:** a self-hosted Qwen through Codex, and
20 Antigravity's Gemini Flash.
21
22A re-shared account comes back under a new instance id (`codex-personal` became
23`codex-yf324204uu`), and the old entry lingers as "not authenticated". Route to
24the authenticated one.
users/clover/agents/skills/orchestrate/references/brief.md created+79
......@@ -0,0 +1,79 @@
1# Agent briefs
2
3Two shapes: one for building, one for each review round. Keep the headings and
4fill in the angle brackets. UI agents use `ui-review-loop`'s brief, with this
5brief's Checkout and Claim sections.
6
7## Build brief
8
9```
10You own **<outcome>** in <project>. The user is Clover (she/her).
11Read <project>/AGENTS.md and <the files you'll touch> first; its rules apply in full.
12
13## Checkout
14<path> (jj workspace <name>), on <change> <commit id>.
15Conservative mode instead: <path>, shared with Clover and the orchestrator; you are its only editor until you report.
16
17## Clover's words (verbatim)
18"<quote>"
19The job, as I read it: <one or two lines>.
20
21## What it looks like now
22- <defect or state, where it shows, file:line leads>
23
24## Decisions already made
25- <decision> (<source: Clover, date | review round>)
26
27## Deliverable
281. <item>: <concrete change, states, entry points>
29N. Anything else in your area that clearly breaks: fix it, without adding features beyond this list.
30
31## Claim
32You own: <files, directories, patches>.
33Others own: <owner: area>, one line each. Don't edit those; ask through the orchestrator.
34History: commit on top in your own workspace. <Only if you are the rewriter: you may fold and rebase, per the orchestrate skill's references/jj.md; fold into <change ids>.>
35
36## Rules for this task
37- <only what AGENTS.md doesn't already say, e.g. "don't fold while the end-to-end run on <commit> is going">
38- Foreground only: background notifications never reach you. Poll cheaply with a timeout.
39
40## Verify
41- Test on <commit id>, and report the commit ids you tested.
42- Probes that count effects: <"one click sends exactly one request", "the end-to-end row passes 3/3">.
43- Visual changes: screenshots or a video, at <paths>.
44- Before reporting: a cleanup pass on your diff, every wait you started stopped, your scratch deleted.
45
46## Report (≤<N> lines)
47- Per item: done / skipped (why).
48- Change and commit ids, and the exact tree you tested.
49- Evidence paths: logs, screenshots, videos.
50- Anything you touched outside your claim and scratch.
51- Questions, each with a lean.
52```
53
54## Review round brief
55
56A new `delegate_task` per round, with its own `clientRequestId`.
57
58```
59Review round <n> of <subject> in <project>. The user is Clover (she/her).
60Diff: <from commit> → <to commit>, in <checkout>. Read-only: edit nothing, rewrite nothing.
61Read <project>/AGENTS.md first.
62
63## Threat model and stop rule (agreed with Clover, <date>)
64Threat model: <who or what fails, and how; what is trusted>
65Stop rule: <e.g. ship when no P1 or P2 remains inside the threat model; P3 and copy batch into the next release>
66Out of scope: <…>
67
68## History
69- Original brief: <pasted or path>
70- Round <k> findings: <F1 … Fn, one line each, severity>
71- Responses: <F1 resolved in <change> | accepted as temporary: why | disputed: why>
72- Unresolved objections: <…>
73Don't reopen findings marked resolved or accepted unless the diff changed them.
74
75## Report (≤<N> lines, also written to <path>)
76- Verdict: SHIP | BLOCK, against the stop rule.
77- Per prior finding: RESOLVED (how you checked) | OPEN.
78- New findings: id, severity, file:line, failure scenario. P3 and copy as one batched list.
79```
users/clover/agents/skills/orchestrate/references/casebook.md created+132
......@@ -0,0 +1,132 @@
1# Casebook
2
3What happened behind the rules, for anyone curious. Nothing here is needed to
4follow the skill. Projects: **the Knife**, Clover's fork of T3 Code with its
5own updater and background holder processes (October 2026); **Snowbound**, a
6OneNote remake one thread maintained for ten days. Quotes are Clover's.
7
8## The role
9
10- **Seams.** On the Knife, the orchestrator saw that the Tools patches touched
11 the adapters hot-update relies on, which became a test scenario; found that
12 the update dialog said "interrupted" because orchestrator turns are never
13 handed off; and caught a banner showing two contradictory delivery lines.
14- **Say when your call was wrong.** The orchestrator recommended dropping a
15 compatibility shim without checking live data, and her Devices page went
16 empty.
17
18## Modes
19
20- Clover, on scope: "i dont want orchestrate to activate in [a work repo] and
21 then the agent starts messing with issue tracker and worktrees and stuff."
22 The core stays shared because "the core theory of locking parts of the code
23 and routing to different models is the meat of the skill."
24
25## Ownership
26
27- **Keep the code claimed.** Clover: "the top level needs to ensure that as much
28 of the codebase is locked as possible, re-checking the queue for tasks that
29 slot into the gaps."
30- **One rewriter.** Knife agents rewriting one jj store from several workspaces
31 made divergent changes. A shared `mkdir` lock fixed it; Clover preferred the
32 orchestrator knowing who works on what.
33- **Own workspace per editor.** Snowbound's one shared working copy broke builds
34 for hours and swept half-edits into commits.
35- **Confirm reachability before forgetting.** Snowbound nearly lost a finished
36 change by forgetting its workspace.
37
38## Routing
39
40- **Reading is the cost.** On 2026-10-21, on Clover Home Claude, Opus subagents
41 used 84% of the day's usage and the orchestrator 14%; Sonnet came to 1%, and
42 230 Haiku test sessions to under 1%. Nearly all of it was cache reads by long
43 agents rereading large contexts.
44- **Limits mid-task.** Clover Home Claude hit 12% with hours to go. Clover Work
45 Codex hit its limit mid-rebase; the agent failed with nothing changed.
46- **Live instance ids.** Re-sharing an account renamed `codex-personal` to
47 `codex-yf324204uu`, and the old entry stayed listed as "not authenticated".
48
49## Briefs
50
51- **The exact tree.** A Knife release gate ran its updater end-to-end matrix on
52 one commit while the release tip had added the Tools patches, so the gate
53 proved nothing about what shipped.
54- **Foreground only.** Two Knife agents stalled waiting for a background
55 notification that never came.
56- **Steering.** "No Host rewriting, real host header" landed mid-build as a
57 steer.
58- **Safety in AGENTS.md.** v1 pasted a 13-line safety block into every brief.
59 Clover: "you shouldn't be wasting your tokens re-emitting this block."
60
61## Deciding and asking
62
63- **Obvious calls.** Clover: "i am glad i dont have to go 'yeah obviously we
64 should use the better approach' … i will ALWAYS appreciate a stronger and more
65 resilient implementation. expanding scope is the scarier one."
66- **Trust model.** Knife: "computer to computer, trust the main port, permission
67 for other ports in the browser." It answered two agent questions without
68 asking her.
69- **Declining scope behind a gate.** A stderr channel for one fix would have
70 changed the holder protocol and reopened the full matrix plus a review;
71 structured errors detected the same failure.
72- **Do the simpler thing.** It decided the Claude usage endpoint: match
73 upstream.
74- **Security escalation.** A Knife review blocked on four P1s, including proxy
75 egress reaching the LAN and a lease renewing without fresh approval.
76
77## Gates and releases
78
79- **Stop rule up front.** The Knife updater took 12 fix rounds because the
80 reviewer kept finding the next ring: protocol-1 notices, then advice copy,
81 then damaged-record copy.
82- **Prove shipped state.** Dropping a scope shim broke decoding of her shipped
83 auth rows and emptied Devices; a consolidation renumbered migrations her
84 database had already recorded.
85- **Exit status.** A filtered "clean" once hid a check that never ran.
86- **Reproduce on the base.** Thirteen server failures in unchanged tests
87 reproduced on the original source: the environment.
88- **Waivers.** She chose "Publish it now" over a third review round, and was
89 told not to use keyed Tools servers with Codex until the next update.
90- **Ship often.** Knife wave 1 (fixes) went out while wave 2 (UI) was still
91 folding.
92
93## Safety
94
95- An agent ran read-only `git config` in a jj repo.
96- Two updater harness runs shared one home, port and bundle id, and killed each
97 other.
98- A bare `jj squash --into` opened an editor and hung the agent.
99- An inherited `TMPDIR` and `CLAUDE_CONFIG_DIR` leaked a scratch server into the
100 agent's real profile, and 315 MB of build temp into her real home.
101- Scratch servers without their own home wrote test identities into her real
102 `~/.knife`.
103- An agent copied a scratch Claude credential into a fixture, then disclosed and
104 removed it.
105- Closed literal unions (the icon colors) break old decoders when extended.
106- **Machine load.** On Snowbound, stale waiter loops piled up (18 belonged to
107 finished agents; later "50 running bg tasks"). Unthrottled builds plus VMs
108 froze her Mac: "i literally couldnt even move the mouse." Deleting the macOS
109 10.6 SDK cost a platform two days of releases.
110
111## jj stack
112
113- **A deep fold.** Squashing a commit into a patch far below it cascaded
114 conflicts through 26 commits, because it depended on later patches.
115- **Frozen snapshot.** Adding a workspace at an obsolete commit unhid its
116 ancestors and made the stack divergent.
117
118## Trouble
119
120- **"Still" broken.** Her laptop sat on an old build; "it was just the updater".
121- **A release broke her machine.** Applying a Knife update hung her app and
122 cancelled every delegated task. The hotfix reverted the offending patch on the
123 tested tree and released that.
124- **A long suite.** The Knife's server tests run serially and outlast a
125 10-minute tool call, so they run as file-list chunks.
126
127## Talking to Clover
128
129- **Screenshots.** Spot-checking them caught the banner copy and a test thread
130 showing an auth failure. Clover: "screenshots and videos are always awesome to
131 see i just love seeing them."
132- **Confidence.** "it should not be confident if it doesn't know."
users/clover/agents/skills/orchestrate/references/jj.md created+76
......@@ -0,0 +1,76 @@
1# jj recipes for a shared stack
2
3Rewrites (squash, rebase, restore, abandon, `op restore`, `workspace
4update-stale`) are run only by the agent `NOW.md` names as the rewriter. Other
5agents run `jj new`, `jj describe` and `jj commit` in their own workspace.
6Always pass `-m '…'` or `--use-destination-message`; a bare `squash` or
7`describe` opens an editor and hangs. Checked against jj 0.42.
8
9## Stack rules
10
11- Fold every fix into its owning patch. No "fix after review" commits.
12- Fold into the lowest patch where the change compiles. A fold below a patch it
13 depends on cascades conflicts through every commit in between.
14- Fold only when no end-to-end run is active; a fold changes the tree under it.
15- Until the release ships, park fixes on top as `WIP: fold into <change>: …`,
16 so the tested tree doesn't move.
17
18## An agent's workspace
19
20```
21jj workspace add <workspaces dir>/<project>-ws-<name> -r <change>
22```
23
24Before `jj workspace forget`, confirm its commits are reachable from the stack
25(`jj log -r '<its change>'`) or deliberately abandoned. Then delete the
26directory.
27
28## Folding a fix into its owner
29
30```
31jj log -r '<owner>::' # other agents' "fold into <owner>" WIPs get rebased into conflicts
32jj squash --from <fix> --into <owner> --use-destination-message
33jj st # conflicts: stop and undo (below)
34```
35
36When unsure, park it and fold during the next rebase:
37
38```
39jj describe -r <fix> -m 'WIP: fold into <owner>: <what>'
40jj rebase -r <fix> -A <tip>
41```
42
43## Undoing your own mistake
44
45```
46jj op log # only your operations since the bad one?
47jj op restore <op before> # then restore
48```
49
50If another agent's operation came after, use `jj op revert <op>` for just
51yours, or repair by hand. `jj op undo` doesn't exist here.
52
53## Keeping a frozen tree
54
55A fold below a frozen snapshot (a hotfix base, a tested tree) rebases it and
56can move its tree. Restore it right after the fold:
57
58```
59jj restore --from <old commit of the snapshot> --into <snapshot change>
60```
61
62## Scratch workspace at a frozen snapshot
63
64Create it before folding. `jj workspace add -r <obsolete commit>` unhides that
65commit's old ancestors and turns the stack divergent; use a live change with
66the same tree instead. Afterwards, `jj workspace forget` it, abandon its
67commit, and delete the directory.
68
69## After an interruption
70
71```
72jj workspace update-stale
73jj log -r 'description(substring:"<subject>")' # two copies of one commit?
74jj diff --git -r <each> # keep the one with the edits
75jj abandon <the other>
76```
users/clover/agents/skills/orchestrate/references/safety-checklist.md created+50
......@@ -0,0 +1,50 @@
1# Safety checklist for a project
2
3What a project's AGENTS.md should state, and how to enforce each item so it
4holds when an agent forgets. Every enforcement here is a suggestion; none is
5built yet. A rule that only a brief repeats will be forgotten.
6
7- **Version control.** AGENTS.md: which VCS; in a jj repo, never `git`, not even
8 read-only. Enforce: a hook that denies `git` when the repo has `.jj`, or a
9 `git` shim on agents' PATH that refuses there.
10- **One history rewriter.** AGENTS.md: only the agent the orchestrator names
11 rewrites history. Enforce: a jj wrapper that takes a lock for rewriting
12 commands, or the orchestrator's ownership map alone.
13- **Commands that open an editor.** AGENTS.md: always `-m` or
14 `--use-destination-message`. Enforce: `JJ_EDITOR=false` in agents' env, so a
15 bare `squash` fails instead of hanging.
16- **Clean environments.** AGENTS.md: servers, tests and builds start from
17 `env -i` with their own `TMPDIR`, home and config dirs; agents check a
18 server's env (`ps eww`) before clicking anything that writes. Enforce: a
19 one-command scratch launcher that sets all of that, picks a free port, and
20 records the PID.
21- **No-touch trees.** AGENTS.md: the paths agents may read but never write (her
22 real app data, credentials, `/Applications`, installer caches). Enforce:
23 sandbox writable roots that exclude them, or a hook on writes and deletes.
24- **Processes.** AGENTS.md: signal only PIDs you started; never kill by pattern;
25 never touch her running app or its helpers. Enforce: a hook that denies
26 `pkill` and `killall`; a stop command in the scratch launcher that reads its
27 recorded PIDs.
28- **Exclusive harnesses.** AGENTS.md: which harnesses allow one run at a time.
29 Enforce: the harness takes its own lock and refuses a second run.
30- **Secrets.** AGENTS.md: no secrets in logs, output or tracked files; never
31 copy a credential into a fixture; check a credential by printing status codes
32 only. Enforce: a secret scan in the pre-publish gate.
33- **Private names.** AGENTS.md: no employer names in tracked files. Enforce: a
34 denylist check in the pre-publish gate.
35- **Model turns in tests.** AGENTS.md: Claude Haiku or Codex Luna only. Enforce:
36 the test harness rejects other model ids.
37- **Shipped-data compatibility.** AGENTS.md: synced or persisted records stay
38 two-way compatible: optional keys old decoders drop, no additions to a closed
39 union. Enforce: a test that decodes fixtures captured from shipped versions.
40- **Risky subsystems.** AGENTS.md: which subsystems need an isolated end-to-end
41 run on the exact tree plus a review before release. Enforce: the release
42 script refuses a tree without a passing run recorded for that commit.
43- **Credits.** AGENTS.md: `Assisted-by: <model>` trailers, one per model, never
44 `Co-authored-by`. Enforce: a trailer check in the pre-publish gate.
45- **Machine load.** AGENTS.md: caps on parallel builds, VMs and waits. Enforce:
46 the scratch launcher runs heavy jobs under `nice` with a job cap, and every
47 wait helper takes a timeout.
48- **Protected paths for cleanup.** AGENTS.md: what cleanup never deletes (SDKs,
49 toolchains, her data). Enforce: cleanup deletes only under recorded scratch
50 roots.
users/clover/agents/skills/sol-loop/SKILL.md created+119
......@@ -0,0 +1,119 @@
1---
2name: sol-loop
3description: Use when the user says "sol loop".
4---
5
6# sol-loop
7
8This is a workflow for making your code changes more correct before (or
9sometimes after) filing a pull request. tl;dr - use OpenAI's GPT Sol to review
10your code in a loop.
11
12Make the most minimal possible changes to appease the Sol reviewers. Be careful
13of scope creep and don't be scared to push back.
14
15## Budget
16
17- Default: 3 rounds total. Round 1 is full. Later rounds check only
18 changed code and open findings.
19- Extend to 5 only for security, permissions, auth, data loss, or
20 state/concurrency, while a blocker or should stays open with evidence. Or when
21 the user asks.
22- Stop early if a round returns only nits. Declined nits and comment,
23 doc, or format-only fixes need no new round.
24- One reviewer only. Sol must not start subagents or reviewers.
25- Keep a ledger: id, severity, outcome, usage if returned. Never guess it.
26
27## 1. Scope
28
29Run `git status --short`. Do not stash, discard, or include unrelated
30changes. Limit review to the change paths if they separate cleanly.
31Otherwise stop and ask.
32
33Find the base after `git fetch origin`:
34
35- PR: `gh pr view <n> --json baseRefName,headRefOid`. Check out the branch
36 only if clean. Confirm `HEAD` is the PR head, or ahead only by this
37 change. Base: `git merge-base HEAD origin/<baseRefName>`.
38- Local: `git merge-base HEAD origin/<default-branch>`. No remote: a base
39 the user names, or `HEAD` for uncommitted changes only.
40
41The change is base to working tree in those paths, with untracked files.
42Use one diff command all rounds. State intent and out-of-scope in 1-2
43sentences. Run covering checks. Do not send code this change breaks. Note
44missing or pre-failing checks in the brief.
45
46## 2. Start Sol
47
48In T3, call `orchestrator_capabilities`. Pick the latest Sol unless the user
49named a version. Do not hardcode an ID. Record provider, model, and effort
50only if exposed. Use `delegate_task` every round (`role: "review"`,
51`mode: "async"`). Save `taskId`. New `clientRequestId` per round.
52`childThreadId` is storage, not the next target. Do not use
53`t3_thread_send`, `create_threads`, or `t3_thread_launch` for review.
54
55If T3 tools are not listed, try one direct capability call. Outside T3, use
56a native Sol subagent and keep its ID. In Claude Code, use a custom subagent
57only if it is set up to run Sol. If no route runs Sol, report the blocker. Do
58not substitute a model.
59
60Do not edit scoped files while review runs. Wait for the notice. Do not
61poll or start a second reviewer. Timeout, error, or no reply is not
62approval. On failure, cancel, verify stop, restart with the ledger.
63
64Round 1 brief (T3 children get no history):
65
66```
67Review only. Do not edit, commit, push, comment on PRs, or start subagents.
68Repo: <abs path> Base: <sha> Intent: <intent> Out of scope: <scope> Checks: <results>
69See: git diff <base> [-- <paths>]; git status --short (read untracked).
70Read surrounding code. Find bugs, broken callers, mismatch with intent.
71Skip style unless it hides a bug. Hold to the smallest change. Flag code,
72tests, or guards the intent does not need. Other paths, rare cases, small
73perf, extra compat: nits.
74blocker = intended case wrong. should = real bug callers will hit, in intent. nit = rest.
75Reply:
76VERDICT: APPROVE or CHANGES
77S1 [blocker|should|nit] <file>:<line> <claim>. Fix: <suggestion> (stable ids)
78```
79
80## 3. Answer findings
81
82Check each finding and severity yourself. Another path, rare case, or
83small cost is a nit, whatever label it came with.
84
85- Agree: smallest fix. Prefer delete or narrow over new lock, cache,
86 helper, or option. Fix the case that happened. Add one focused test
87 that fails without the fix, if intent needs it.
88- Disagree: say why, with evidence (file:line, test, output).
89- Out of scope or nit: decline in one line. List as follow-up.
90
91Update the ledger. Re-run checks and `git diff --shortstat <base>`. If
92review grew the diff, cut first. Do not agree just to end the loop.
93
94## 4. Next round
95
96Start one only if budget remains and a blocker or should is open, behavior code
97changed, or approval does not cover the current behavior diff. Use a fresh
98`delegate_task` in T3, or follow up the saved native ID. Send the round 1 brief,
99the ledger (`fixed:` / `disagree:` / `declined:` + evidence), the same base
100diff, and the change since last round. Tell Sol: open ids and changed code only.
101Mark each old id `resolved` or `still open: <reason>`.
102
103## 5. Stop and ship
104
105Agreed: APPROVE on the current behavior diff, no blocker or should open,
106no concern of your own. Stuck: an item stays disputed after two replies,
107or budget ends. Show both sides in 2-3 lines each. The user decides.
108Budget end is not approval.
109
110Do not push during the loop. Push after agreement only if the user asked
111to push, ship, or update the PR. If you push to a PR, add above the model
112blurb:
113
114`Reviewed with sol-loop: <N> rounds with <model>. Sol verdict: approved`.
115
116Add `on <effort>` only if verified.
117
118Report: rounds, model, what Sol changed, diff size before/after, fixed and
119declined findings with reasons, usage if exposed (else say not), pushed or not.
users/clover/agents/skills/ui-review-loop/SKILL.md+1-1
......@@ -75,7 +75,7 @@ Use `references/agent-brief.md`. These parts made briefs land:
7575- **Decisions already made.**
7676- **Ownership.** Assign it by function, CSS section or data array, and list who
7777 else edits what. One agent owns each UI surface; others hand off to it. Give
78 each agent its own checkout where possible (see `maintain-it`). If they share
78 each agent its own checkout where possible (see `orchestrate`). If they share
7979 one, they make small targeted edits and re-read on conflict.
8080- **Hard rules:**
8181 - the repo's own version-control and safety rules, from its AGENTS.md or
users/clover/home.nix+28-6
......@@ -89,16 +89,38 @@ in
8989 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/ui-review-loop";
9090 home.file.".codex/skills/ui-review-loop".source =
9191 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/ui-review-loop";
92 home.file.".claude/skills/maintain-it".source =
93 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/maintain-it";
94 home.file.".codex/skills/maintain-it".source =
95 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/maintain-it";
92 home.file.".claude/skills/orchestrate".source =
93 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/orchestrate";
94 home.file.".codex/skills/orchestrate".source =
95 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/orchestrate";
9696 home.file.".claude/skills/accessibility".source =
9797 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/accessibility";
9898 home.file.".codex/skills/accessibility".source =
9999 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/accessibility";
100 home.file.".codex/skills/shale-issues".source =
101 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/shale-issues";
100 home.file.".claude/skills/full-send".source =
101 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/full-send";
102 home.file.".codex/skills/full-send".source =
103 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/full-send";
104 home.file.".claude/skills/full-stop".source =
105 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/full-stop";
106 home.file.".codex/skills/full-stop".source =
107 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/full-stop";
108 home.file.".claude/skills/babysit-pr".source =
109 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/babysit-pr";
110 home.file.".codex/skills/babysit-pr".source =
111 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/babysit-pr";
112 home.file.".claude/skills/leaving-pr-comments".source =
113 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/leaving-pr-comments";
114 home.file.".codex/skills/leaving-pr-comments".source =
115 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/leaving-pr-comments";
116 home.file.".claude/skills/sol-loop".source =
117 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/sol-loop";
118 home.file.".codex/skills/sol-loop".source =
119 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/sol-loop";
120 home.file.".claude/skills/file-pr".source =
121 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/file-pr";
122 home.file.".codex/skills/file-pr".source =
123 config.lib.file.mkOutOfStoreSymlink "${cloverSkills}/file-pr";
102124 home.file.".claude/skills/openai-docs".source =
103125 config.lib.file.mkOutOfStoreSymlink "${config.home.homeDirectory}/.codex/skills/.system/openai-docs";
104126 home.file.".codex/skills/update-config".source =
users/clover/jujutsu.nix+10
......@@ -9,6 +9,11 @@
99 postBuild = ''
1010 rm "$out/bin/jj"
1111 cp ${pkgs.writeShellScript "jj" ''
12 ${lib.optionalString pkgs.stdenv.isDarwin ''
13 if [[ -t 0 && -t 1 && -z "''${SSH_CONNECTION-}''${SSH_CLIENT-}''${SSH_TTY-}" ]]; then
14 set -- '--config=--scope=[{ "--when".commands = ["diff"], ui.diff-formatter = "knife", ui.paginate = "never" }]' "$@"
15 fi
16 ''}
1217 for arg in "$@"; do
1318 case "$arg" in
1419 desc|describe)
......@@ -94,6 +99,11 @@
9499 muted = "bright black";
95100 };
96101 ui.default-command = lib.mkForce "show";
102 merge-tools.knife = lib.mkIf pkgs.stdenv.isDarwin {
103 program = "/Applications/Knife Diff.app/Contents/MacOS/knife-code";
104 diff-args = [ "$left" "$right" ];
105 edit-args = [ "--edit" "$left" "$right" ];
106 };
97107 # ui.graph.style = "square";
98108 revsets = {
99109 short-prefixes = "(trunk()..@)::";
users/clover/packages/agent-linear/agent-linear.js+22-1
......@@ -267,11 +267,30 @@ async function runJj([executable, ...argv]) {
267267}
268268
269269async function startIssues(text, onlyUnclaimed = false) {
270 const prefixesPath = path.join(
271 process.env.XDG_CONFIG_HOME || path.join(process.env.HOME, ".config"),
272 "agent-linear",
273 "prefixes",
274 );
275 let prefixes;
276 try {
277 prefixes = new Set(
278 fs.readFileSync(prefixesPath, "utf8").toUpperCase().split(/\r?\n/)
279 .map((prefix) => prefix.trim()).filter(Boolean),
280 );
281 } catch (error) {
282 if (error.code === "ENOENT") {
283 return [];
284 }
285 throw error;
286 }
287
270288 const issues = new Set(
271289 [...text.matchAll(
272290 /(?<![a-z0-9_-])[a-z][a-z0-9]*-\d+(?![a-z0-9_-]|\.\d)/gi,
273291 )]
274 .map((match) => match[0].toUpperCase()),
292 .map((match) => match[0].toUpperCase())
293 .filter((id) => prefixes.has(id.split("-", 1)[0])),
275294 );
276295
277296 const messages = [];
......@@ -621,6 +640,8 @@ function usage(code) {
621640 stream.write(`\n`);
622641 stream.write(`api key: ~/.config/linear-api-key or LINEAR_API_KEY\n`);
623642 stream.write(`scope: only runs from numbered work repos under ~/dev\n`);
643 stream.write(`auto-start prefixes: $XDG_CONFIG_HOME/agent-linear/prefixes (default: ~/.config/agent-linear/prefixes)\n`);
644 stream.write(`one prefix per line, e.g. ALPHA; missing or empty disables auto-start in Claude, Codex, and jj desc\n`);
624645 process.exit(code);
625646}
626647
users/clover/packages/agent-linear/agent-linear.test.cjs created+125
......@@ -0,0 +1,125 @@
1const assert = require("node:assert/strict");
2const fs = require("node:fs");
3const os = require("node:os");
4const path = require("node:path");
5const { test } = require("node:test");
6const vm = require("node:vm");
7
8const source = fs.readFileSync(path.join(__dirname, "agent-linear.js"), "utf8");
9
10async function run(t, { prefixes, text, command = "prompt", xdg = false, assigned = false }) {
11 const home = fs.mkdtempSync(path.join(os.tmpdir(), "agent-linear-test-"));
12 t.after(() => fs.rmSync(home, { recursive: true, force: true }));
13 const config = xdg ? path.join(home, "custom-config") : path.join(home, ".config");
14 if (prefixes !== undefined) {
15 fs.mkdirSync(path.join(config, "agent-linear"), { recursive: true });
16 fs.writeFileSync(path.join(config, "agent-linear", "prefixes"), prefixes);
17 }
18 if (xdg) {
19 fs.mkdirSync(path.join(home, ".config", "agent-linear"), { recursive: true });
20 fs.writeFileSync(path.join(home, ".config", "agent-linear", "prefixes"), "WRONG\n");
21 }
22
23 const requests = [];
24 const output = [];
25 const context = vm.createContext({
26 require(name) {
27 if (name === "node:fs") {
28 return {
29 ...fs,
30 readFileSync(file, encoding) {
31 return file === 0
32 ? JSON.stringify({ hook_event_name: "UserPromptSubmit", prompt: text })
33 : fs.readFileSync(file, encoding);
34 },
35 };
36 }
37 if (name === "node:child_process") {
38 return {
39 spawnSync(executable, argv) {
40 assert.equal(executable, "jj");
41 const stdout = argv.includes("log")
42 ? argv.at(-1) === "description" ? text : "change-id\n"
43 : "";
44 return { status: 0, stdout };
45 },
46 };
47 }
48 if (name === "node:process") {
49 return {
50 argv: ["node", "agent-linear", ...(
51 command === "jj" ? ["jj", "jj", "desc", "-m", text] : ["prompt"]
52 )],
53 env: { HOME: home, LINEAR_API_KEY: "test", ...(xdg ? { XDG_CONFIG_HOME: config } : {}) },
54 stdout: { write: (value) => output.push(value) },
55 exit: (code) => assert.fail(`unexpected exit ${code}`),
56 };
57 }
58 return require(name);
59 },
60 console: { error: (value) => output.push(value) },
61 AbortSignal,
62 async fetch(url, options) {
63 assert.equal(url, "https://api.linear.app/graphql");
64 const { query, variables } = JSON.parse(options.body);
65 requests.push({ query, variables });
66 const data = query.includes("IssueProgress")
67 ? { issue: {
68 id: variables.id,
69 state: { name: "Todo" },
70 assignee: assigned ? { id: "someone" } : null,
71 team: { states: { nodes: [{ id: "started", name: "In Progress", type: "started" }] } },
72 } }
73 : query.includes("issueUpdate")
74 ? { issueUpdate: { success: true } }
75 : { viewer: { id: "viewer", name: "Clover" } };
76 return { ok: true, text: async () => JSON.stringify({ data }) };
77 },
78 });
79
80 await vm.runInContext(source, context);
81 return { requests, output: output.join("") };
82}
83
84for (const command of ["prompt", "jj"]) {
85 test(`${command}: only configured prefixes start issues`, async (t) => {
86 const { requests, output } = await run(t, {
87 command,
88 prefixes: " alpha \r\nBETA\r\n\r\n",
89 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",
90 });
91 assert.deepEqual(
92 requests.filter(({ query }) => query.includes("IssueProgress")).map(({ variables }) => variables.id),
93 ["ALPHA-12", "BETA-3", "ALPHA-10"],
94 );
95 assert.equal(requests.filter(({ query }) => query.includes("issueUpdate")).length, 3);
96 assert.match(output, /ALPHA-12 → In Progress/);
97 });
98
99 for (const prefixes of [undefined, "", "\n \r\n"]) {
100 test(`${command}: ${JSON.stringify(prefixes)} configuration disables automatic requests`, async (t) => {
101 const { requests, output } = await run(t, { command, prefixes, text: "ALPHA-123 OTHER-456" });
102 assert.deepEqual(requests, []);
103 assert.equal(output, "");
104 });
105 }
106}
107
108test("XDG_CONFIG_HOME overrides the default directory; prefixes are literal", async (t) => {
109 const { requests } = await run(t, {
110 xdg: true,
111 prefixes: "ALPHA\nB.*\n",
112 text: "ALPHA-1 BETA-2 WRONG-3",
113 });
114 assert.deepEqual(
115 requests.filter(({ query }) => query.includes("IssueProgress")).map(({ variables }) => variables.id),
116 ["ALPHA-1"],
117 );
118});
119
120test("prompts leave assigned issues alone; jj descriptions still start them", async (t) => {
121 for (const command of ["prompt", "jj"]) {
122 const { requests } = await run(t, { command, prefixes: "ALPHA", text: "ALPHA-1", assigned: true });
123 assert.equal(requests.some(({ query }) => query.includes("issueUpdate")), command === "jj");
124 }
125});
users/clover/packages/workspaces/README.md deleted-100
......@@ -1,100 +0,0 @@
1# Workspaces
2
3Requires macOS/APFS and T3 Code nightly with orchestrator V2. The source repo is
4configured locally in `~/.config/workspaces.json`.
5
6```sh
7ws setup /path/to/source-workspace
8ws new # next available number, freshly fetched origin/main
9ws new search -r some-change # ~/workspaces/search, with a fresh T3 chat
10ws open search # reopen and renew the chat's claim
11ws deps search # reconcile dependencies after changing revisions
12ws gc --dry-run # show blockers; update grace observations
13```
14
15Raycast's **New Workspace** command runs `ws new --background`. Its managed script lives in
16`~/.config/raycast/scripts`; register that folder in Raycast's Script Commands
17settings once. Each workspace has its own T3 project, named after the source
18project followed by ` | <workspace id>`, with the same logo. Additional chats
19in that project use the same workspace folder.
20
21`ws new` and `ws open` accept `--no-open` to bind the chat without navigating
22the desktop app. `ws new --json` returns `{workspacePath, projectId, threadId,
23environmentId}` for callers that navigate the resulting chat themselves. By
24default, standard output is the workspace path; setup progress goes to
25standard error. The chat opens in an empty folder before fetching or creating
26the JJ workspace; `--background` returns without waiting for preparation.
27Claude and Codex startup and prompt hooks wait for the workspace to be ready.
28Setup failures block the prompt until `ws deps <name>` succeeds.
29New chats can be opened while another workspace prepares; preparation and
30cleanup share a separate lock. Local T3 authentication is cached for one
31minute with a two-minute token, and renewed when the server restarts.
32Background preparation writes `~/Library/Logs/workspace-<id>.log`. A failed
33setup stays protected: run `ws deps <name>` and `ws open <name>` to finish it.
34
35```text
36reserve empty folder → create and open T3 thread
37 → fetch origin/main → add JJ workspace → checkout → clone snapshot → pnpm install
38 → release waiting Claude/Codex hooks
39
40Every 30 seconds:
41 T3 verifies settled, quiet chats with linked PRs all merged → archive chats
42 unfinished setup / unarchived T3 chat / running work / VS Code / live shell cwd
43 → keep workspace, reset grace
44 no references for ≥60 seconds, with a fresh check immediately before removal
45 → JJ snapshot → JJ workspace forget → remove directory
46 unavailable API, untracked VS Code window, unreadable cwd, unexpected state
47 → keep workspaces, reset grace
48```
49
50Settling a chat keeps its workspace directory. Cleanup begins only after every
51chat using the directory is archived or deleted and no work is running. Archival
52releases the directory for cleanup; settling does not. Automatic archival uses
53T3 Code's guarded merge check and retains chats with open, closed, or missing PRs.
54An unavailable completion check pauses cleanup. `ws gc --dry-run` never archives chats.
55
56When a chat settles, T3 captures that workspace's current JJ change with
57`ws settle`; resuming clears its capture with `ws unsettle`. `ws completion`
58reports abandonment only for that same settlement, when its captured change has
59no visible version, the current working change is empty, and its ancestry has
60no nonempty work introduced since the captured repository operation. Rebased
61changes, missing captures, and later work—even beneath an empty tip—retain the directory. These atomic
62per-thread records bypass the preparation lock and are removed with the workspace.
63
64Only registered workspaces under `~/workspaces` are collected. JJ retains
65snapshotted changes; ignored files are deleted with the directory. Closing T3
66pauses cleanup. VS Code's companion extension reports live folders and documents
67through a local socket; windows without a responding tracker block cleanup.
68Shell hooks register workspace shells, and cleanup reads their live cwd,
69including terminals opened before the hooks were installed.
70
71Default creation fetches only `main` from `origin` and starts at `main@origin`.
72An explicit `-r` skips the fetch. Source checkout files remain untouched, even
73when stale. Managed checkouts update automatically; fetching does not abandon
74unrelated commits in the shared repo.
75
76The dependency key includes package manifests, the lockfile, pnpm workspace
77configuration, patches, pnpm version, platform, architecture, and Node ABI.
78`clonefile` shares file data without sharing writable inodes. pnpm then
79regenerates launchers containing absolute paths. One cached snapshot is kept;
80changing the dependency key replaces it.
81
82Build and verify against a downloaded nightly CLI:
83
84```sh
85cc -Wall -Wextra -Werror native.c -o /tmp/workspace-native
86T3_TEST_CLI=/path/to/nightly/t3 WORKSPACE_TEST_NATIVE=/tmp/workspace-native \
87 node --test --test-isolation=none workspaces.test.mjs
88```
89
90The lifecycle test starts an isolated nightly server, uses real JJ and pnpm,
91checks clone isolation and launcher relocation, and verifies preservation of JJ
92file contents after cleanup. VS Code process status is a fixture; its reference
93socket and the terminal cwd probe are live. The lock test verifies overlap
94rejection and release after process exit.
95
96`workspaces-hooks.test.mjs` tests the installed Claude and Codex CLIs against
97a local API stub. Set `WORKSPACE_TEST_CLAUDE`, `WORKSPACE_TEST_CODEX`, and
98`WORKSPACE_TEST_HOOK_PYTHON` (Python with tomlkit). It verifies that early prompts
99wait, setup failures prevent model requests, and instructions created during
100preparation reach the first model request. It makes no external model calls.
users/clover/packages/workspaces/configure-hooks.py deleted-103
......@@ -1,103 +0,0 @@
1import json
2import os
3from pathlib import Path
4import select
5import subprocess
6import sys
7
8import tomlkit
9
10home = Path(sys.argv[1])
11command = sys.argv[2]
12codex = sys.argv[3]
13
14
15def write(file, contents):
16 if file.exists() and file.read_text() == contents:
17 return
18 file.parent.mkdir(parents=True, exist_ok=True)
19 temporary = file.with_name(file.name + ".workspace-hook.tmp")
20 temporary.write_text(contents)
21 os.chmod(temporary, file.stat().st_mode & 0o777 if file.exists() else 0o600)
22 os.replace(temporary, file)
23
24
25for provider, filename in [("claude", "settings.json"), ("codex", "config.toml")]:
26 file = home / ("." + provider) / filename
27 if provider == "claude":
28 settings = json.loads(file.read_text()) if file.exists() else {}
29 else:
30 settings = tomlkit.parse(file.read_text()) if file.exists() else tomlkit.document()
31
32 if "hooks" not in settings:
33 settings["hooks"] = {}
34 for event in ["SessionStart", "UserPromptSubmit"]:
35 hook = {
36 "type": "command", "command": command, "timeout": 300,
37 "statusMessage": "Preparing workspace", "async": False,
38 }
39 if provider == "claude":
40 hook["onFailure"] = "block"
41 groups = settings["hooks"].get(event)
42 if groups is None:
43 settings["hooks"][event] = [{"hooks": [hook]}]
44 else:
45 existing = next((item for group in groups for item in group["hooks"]
46 if item.get("command") == command), None)
47 if existing is None:
48 groups.append({"hooks": [hook]})
49 else:
50 existing.update(hook)
51
52 contents = json.dumps(settings, indent=2) + "\n" if provider == "claude" else tomlkit.dumps(settings)
53 write(file, contents)
54
55 if provider != "codex":
56 continue
57
58 with subprocess.Popen([codex, "app-server", "--stdio"], stdin=subprocess.PIPE,
59 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0,
60 env={**os.environ, "CODEX_HOME": str(file.parent)}) as server:
61 try:
62 def request(request_id, method, params):
63 message = {"id": request_id, "method": method, "params": params}
64 server.stdin.write((json.dumps(message) + "\n").encode())
65 while select.select([server.stdout], [], [], 15)[0]:
66 line = server.stdout.readline()
67 if not line:
68 break
69 response = json.loads(line)
70 if response.get("id") != request_id:
71 continue
72 if "error" in response:
73 raise RuntimeError(response["error"])
74 return response["result"]
75 raise RuntimeError("Codex did not confirm workspace hook configuration")
76
77 request(1, "initialize", {
78 "clientInfo": {"name": "workspace-hook-installer", "version": "1"},
79 "capabilities": {"experimentalApi": True},
80 })
81 server.stdin.write(b'{"method":"initialized"}\n')
82 listed = request(2, "hooks/list", {"cwds": [str(home)]})
83 hooks = [hook for entry in listed["data"] for hook in entry["hooks"]
84 if hook.get("command") == command
85 and hook["eventName"] in ["sessionStart", "userPromptSubmit"]
86 and hook["sourcePath"] == str(file)]
87 if len(hooks) != 2:
88 raise RuntimeError("Codex did not load both workspace readiness hooks")
89
90 settings = tomlkit.parse(file.read_text())
91 if "state" not in settings["hooks"]:
92 settings["hooks"]["state"] = {}
93 for hook in hooks:
94 settings["hooks"]["state"][hook["key"]] = {
95 "trusted_hash": hook["currentHash"], "enabled": True,
96 }
97 write(file, tomlkit.dumps(settings))
98 finally:
99 server.terminate()
100 try:
101 server.wait(timeout=5)
102 except subprocess.TimeoutExpired:
103 server.kill()
users/clover/packages/workspaces/default.nix deleted-29
......@@ -1,29 +0,0 @@
1{ pkgs, ... }:
2let
3 native = pkgs.runCommandCC "workspace-native" { } ''
4 mkdir -p $out/bin
5 $CC ${./native.c} -o $out/bin/workspace-native
6 '';
7in
8pkgs.writeShellApplication {
9 name = "ws";
10 runtimeInputs = with pkgs; [
11 nodejs_26
12 jujutsu
13 pnpm_10
14 native
15 ];
16 text = ''
17 case "''${1-}" in
18 ready-hook|settle|unsettle|completion)
19 exec node ${./workspaces.mjs} "$@"
20 ;;
21 esac
22 mkdir -p "$HOME/.local/state/workspaces"
23 workspace_lock="$HOME/.local/state/workspaces/lock"
24 if [[ "''${1-}" == new ]]; then
25 workspace_lock="$HOME/.local/state/workspaces/creation-lock"
26 fi
27 exec workspace-native lock "$workspace_lock" node ${./workspaces.mjs} "$@"
28 '';
29}
users/clover/packages/workspaces/extension/extension.js deleted-33
......@@ -1,33 +0,0 @@
1const vscode = require("vscode");
2const fs = require("node:fs");
3const net = require("node:net");
4const os = require("node:os");
5const path = require("node:path");
6
7function activate(context) {
8 const directory = path.join(os.homedir(), ".local/state/workspaces/vscode");
9 fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
10 const socket = path.join(directory, `${process.pid}.sock`);
11 fs.rmSync(socket, { force: true });
12
13 const server = net.createServer((client) => {
14 const uris = [
15 ...(vscode.workspace.workspaceFolders ?? []).map((folder) => folder.uri),
16 ...vscode.workspace.textDocuments.map((document) => document.uri),
17 vscode.workspace.workspaceFile,
18 ];
19 const paths = uris.filter((uri) => uri?.scheme === "file").map((uri) =>
20 uri.fsPath
21 );
22 client.end(JSON.stringify({ pid: process.pid, paths }) + "\n");
23 });
24 server.listen(socket);
25 context.subscriptions.push({
26 dispose() {
27 server.close();
28 fs.rmSync(socket, { force: true });
29 },
30 });
31}
32
33module.exports = { activate };
users/clover/packages/workspaces/extension/package.json deleted-12
......@@ -1,12 +0,0 @@
1{
2 "name": "workspace-references",
3 "displayName": "Workspace References",
4 "description": "Keeps open VS Code folders safe from workspace cleanup.",
5 "publisher": "clover",
6 "version": "0.0.1",
7 "engines": { "vscode": "^1.74.0" },
8 "main": "./extension.js",
9 "extensionKind": ["ui"],
10 "activationEvents": ["*"],
11 "capabilities": { "untrustedWorkspaces": { "supported": true } }
12}
users/clover/packages/workspaces/native.c deleted-39
......@@ -1,39 +0,0 @@
1#include <errno.h>
2#include <fcntl.h>
3#include <stdio.h>
4#include <string.h>
5#include <sys/clonefile.h>
6#include <sys/file.h>
7#include <unistd.h>
8
9int main(int argc, char **argv) {
10 if (argc >= 4 && (strcmp(argv[1], "lock") == 0 ||
11 strcmp(argv[1], "wait-lock") == 0)) {
12 int fd = open(argv[2], O_CREAT | O_RDWR, 0600);
13 if (fd < 0) {
14 perror("Cannot open workspace lock");
15 return 1;
16 }
17 int flags = LOCK_EX | (strcmp(argv[1], "lock") == 0 ? LOCK_NB : 0);
18 if (flock(fd, flags) < 0) {
19 if (errno != EWOULDBLOCK) {
20 perror("Cannot lock workspaces");
21 return 1;
22 }
23 fprintf(
24 stderr,
25 "Another workspace command is running. Retry when it finishes.\n");
26 return 1;
27 }
28 execvp(argv[3], argv + 3);
29 perror("Cannot start workspace command");
30 return 1;
31 }
32 if (argc != 4 || strcmp(argv[1], "clone") != 0)
33 return 2;
34 if (clonefile(argv[2], argv[3],
35 CLONE_NOFOLLOW | CLONE_NOOWNERCOPY | CLONE_ACL) == 0)
36 return 0;
37 perror("Cannot clone dependencies");
38 return 1;
39}
users/clover/packages/workspaces/shell.zsh deleted-15
......@@ -1,15 +0,0 @@
1function _workspace_reference() {
2 local directory="$HOME/.local/state/workspaces/shells"
3 if [[ "$PWD" == "$HOME/workspaces/"* ]]; then
4 mkdir -p "$directory"
5 print -r -- "$PWD" > "$directory/$$"
6 else
7 [[ ! -e "$directory/$$" ]] || rm -f "$directory/$$"
8 fi
9}
10
11autoload -Uz add-zsh-hook
12add-zsh-hook chpwd _workspace_reference
13add-zsh-hook precmd _workspace_reference
14add-zsh-hook preexec _workspace_reference
15_workspace_reference
users/clover/packages/workspaces/workspaces-hooks.test.mjs deleted-144
......@@ -1,144 +0,0 @@
1import assert from "node:assert/strict";
2import { test } from "node:test";
3import fs from "node:fs";
4import path from "node:path";
5import http from "node:http";
6import childProcess from "node:child_process";
7import { once } from "node:events";
8import { fileURLToPath } from "node:url";
9
10const script = fileURLToPath(new URL("./workspaces.mjs", import.meta.url));
11const installer = fileURLToPath(new URL("./configure-hooks.py", import.meta.url));
12const python = process.env.WORKSPACE_TEST_HOOK_PYTHON;
13
14for (const provider of ["codex", "claude"]) {
15 const executable = process.env[`WORKSPACE_TEST_${provider.toUpperCase()}`];
16 test(`${provider} holds a real prompt until preparation, including repository instructions`, {
17 skip: !executable || !python,
18 timeout: 45_000,
19 }, async () => {
20 const home = fs.realpathSync(fs.mkdtempSync("/tmp/workspaces-hooks-"));
21 const workspace = path.join(home, "workspaces/pending");
22 const record = path.join(home, ".local/state/workspaces/workspaces/pending.json");
23 fs.mkdirSync(workspace, { recursive: true });
24 fs.mkdirSync(path.dirname(record), { recursive: true });
25 fs.writeFileSync(record, JSON.stringify({ prepared: false }));
26
27 const invoked = path.join(home, "hook-invoked");
28 const wrapper = path.join(home, "hook.mjs");
29 fs.writeFileSync(wrapper, `import fs from "node:fs";
30import childProcess from "node:child_process";
31fs.writeFileSync(${JSON.stringify(invoked)}, "started");
32const child = childProcess.spawn(process.execPath, [${JSON.stringify(script)}, "ready-hook"], { stdio: "inherit" });
33child.on("exit", (code) => { process.exitCode = code ?? 1; });
34`);
35 const command = [process.execPath, wrapper].map((value) =>
36 "'" + value.replaceAll("'", "'\\''") + "'"
37 ).join(" ");
38 const hook = { type: "command", command, timeout: 30 };
39 const hooks = {
40 SessionStart: [{ hooks: [hook] }],
41 UserPromptSubmit: [{ hooks: [hook] }],
42 };
43 const requests = [];
44 const server = http.createServer(async (request, response) => {
45 let body = "";
46 for await (const chunk of request) body += chunk;
47 if (request.method === "POST" && /\/(responses|messages)(\?|$)/.test(request.url)) {
48 requests.push(body);
49 }
50 response.writeHead(401, { "Content-Type": "application/json" });
51 response.end(JSON.stringify({ error: { type: "authentication_error", message: "Fixture finished" } }));
52 });
53 server.listen(0, "127.0.0.1");
54 await once(server, "listening");
55 const origin = `http://127.0.0.1:${server.address().port}`;
56 const codexHome = path.join(home, ".codex");
57 const claudeHome = path.join(home, ".claude");
58 fs.mkdirSync(codexHome);
59 fs.mkdirSync(claudeHome);
60 fs.writeFileSync(path.join(codexHome, "config.toml"), `model_provider = "fixture"
61model = "gpt-6.1-sol"
62[model_providers.fixture]
63name = "Fixture"
64base_url = "${origin}/v1"
65wire_api = "responses"
66requires_openai_auth = false
67request_max_retries = 0
68stream_max_retries = 0
69[[hooks.SessionStart]]
70[[hooks.SessionStart.hooks]]
71type = "command"
72command = ${JSON.stringify(command)}
73timeout = 30
74[[hooks.UserPromptSubmit]]
75[[hooks.UserPromptSubmit.hooks]]
76type = "command"
77command = ${JSON.stringify(command)}
78timeout = 30
79`);
80 fs.writeFileSync(path.join(claudeHome, "settings.json"), JSON.stringify({ hooks }));
81 const env = {
82 ...process.env, HOME: home, CODEX_HOME: codexHome, CLAUDE_CONFIG_DIR: claudeHome,
83 ANTHROPIC_BASE_URL: origin, ANTHROPIC_API_KEY: "fixture",
84 ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "",
85 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_TELEMETRY: "1",
86 };
87 const args = provider === "codex"
88 ? ["exec", "--json", "--sandbox", "read-only", "--skip-git-repo-check", "Say ready."]
89 : ["-p", "--model", "claude-sonnet-4-6", "--output-format", "json", "Say ready."];
90 let child;
91 let output = "";
92 try {
93 const configure = childProcess.spawn(python, [
94 installer, home, command, process.env.WORKSPACE_TEST_CODEX,
95 ], { env });
96 let configuredOutput = "";
97 configure.stderr.on("data", (chunk) => { configuredOutput += chunk; });
98 const [configuredStatus] = await once(configure, "exit");
99 assert.equal(configuredStatus, 0, configuredOutput);
100 child = childProcess.spawn(executable, args, { cwd: workspace, env });
101 child.stdin.end();
102 child.stdout.on("data", (chunk) => { output += chunk; });
103 child.stderr.on("data", (chunk) => { output += chunk; });
104 const exited = once(child, "exit");
105 for (let attempt = 0; !fs.existsSync(invoked); attempt++) {
106 assert.ok(attempt < 200 && child.exitCode === null, output);
107 await new Promise((resolve) => setTimeout(resolve, 50));
108 }
109 await new Promise((resolve) => setTimeout(resolve, 400));
110 assert.equal(requests.length, 0, "no model request while the workspace is unprepared");
111 assert.equal(child.exitCode, null, "prompt remains waiting");
112 fs.writeFileSync(path.join(workspace, "AGENTS.md"), "WORKSPACE_READY_INSTRUCTIONS_8732\n");
113 fs.writeFileSync(record, JSON.stringify({ prepared: true }));
114 for (let attempt = 0; requests.length === 0; attempt++) {
115 assert.ok(attempt < 300 && child.exitCode === null, output);
116 await new Promise((resolve) => setTimeout(resolve, 50));
117 }
118 assert.match(requests[0], /WORKSPACE_READY_INSTRUCTIONS_8732/);
119 child.kill("SIGKILL");
120 await exited;
121
122 fs.rmSync(invoked);
123 requests.length = 0;
124 fs.writeFileSync(record, JSON.stringify({ prepared: false, preparationError: "fixture setup failed" }));
125 output = "";
126 child = childProcess.spawn(executable, args, { cwd: workspace, env });
127 child.stdin.end();
128 child.stdout.on("data", (chunk) => { output += chunk; });
129 child.stderr.on("data", (chunk) => { output += chunk; });
130 await once(child, "exit");
131 assert.ok(fs.existsSync(invoked), output);
132 assert.equal(requests.length, 0, "a setup failure blocks the model request");
133 if (provider === "codex") assert.match(output, /"input_tokens":0/);
134 else assert.match(output, /setup stopped|resend your prompt/);
135 } finally {
136 if (child?.exitCode === null && child.signalCode === null) {
137 child.kill("SIGKILL");
138 await once(child, "exit");
139 }
140 await new Promise((resolve) => server.close(resolve));
141 fs.rmSync(home, { recursive: true, force: true, maxRetries: 3 });
142 }
143 });
144}
users/clover/packages/workspaces/workspaces.mjs deleted-992
......@@ -1,992 +0,0 @@
1import fs from "node:fs";
2import path from "node:path";
3import os from "node:os";
4import net from "node:net";
5import { createHash, randomUUID } from "node:crypto";
6import childProcess from "node:child_process";
7import { fileURLToPath } from "node:url";
8
9const home = fs.realpathSync(os.homedir());
10const root = path.join(home, "workspaces");
11const state = path.join(home, ".local/state/workspaces");
12const cache = path.join(home, ".cache/workspaces/deps");
13const configFile = path.join(home, ".config/workspaces.json");
14const records = path.join(state, "workspaces");
15const t3Home = process.env.T3CODE_HOME ?? path.join(home, ".t3");
16
17function run(command, args, cwd, inherit = false) {
18 if (command === "jj") {
19 args = ["--config", "snapshot.auto-update-stale=true", ...args];
20 }
21
22 return childProcess.execFileSync(command, args, {
23 cwd,
24 encoding: "utf8",
25 stdio: inherit ? ["ignore", 2, 2] : ["ignore", "pipe", "pipe"],
26 timeout: inherit ? undefined : 30_000,
27 })?.trim();
28}
29
30function writeJson(file, value) {
31 fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
32 const temporary = `${file}.${process.pid}.tmp`;
33 fs.writeFileSync(temporary, JSON.stringify(value) + "\n", { mode: 0o600 });
34 fs.renameSync(temporary, file);
35}
36
37function alive(pid) {
38 try {
39 process.kill(pid, 0);
40 return true;
41 } catch (error) {
42 if (error.code === "ESRCH") return false;
43 throw error;
44 }
45}
46
47function inside(candidate, directory) {
48 const relative = path.relative(directory, candidate);
49 return relative === "" ||
50 (!relative.startsWith(`..${path.sep}`) && relative !== ".." &&
51 !path.isAbsolute(relative));
52}
53
54function canonical(file) {
55 try {
56 return fs.realpathSync(file);
57 } catch (error) {
58 if (error.code === "ENOENT") return path.resolve(file);
59 throw error;
60 }
61}
62
63function jjRepository(directory) {
64 const file = path.join(directory, ".jj/repo");
65 return fs.statSync(file).isDirectory() ? canonical(file) : canonical(
66 path.resolve(path.dirname(file), fs.readFileSync(file, "utf8").trim()),
67 );
68}
69
70function workspace(id) {
71 if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(id)) {
72 throw new Error(
73 "Choose a workspace name containing letters, numbers, underscores, or hyphens.",
74 );
75 }
76 return path.join(root, id);
77}
78
79export async function t3() {
80 const runtime = JSON.parse(
81 fs.readFileSync(path.join(t3Home, "userdata/server-runtime.json")),
82 );
83 if (!Number.isInteger(runtime.pid) || !alive(runtime.pid)) {
84 throw new Error("Start T3 Code nightly before using workspaces.");
85 }
86 const origin = new URL(runtime.origin);
87 if (
88 origin.protocol !== "http:" ||
89 !["127.0.0.1", "localhost", "[::1]"].includes(origin.hostname)
90 ) throw new Error("Workspace cleanup needs a local T3 Code server.");
91
92 const executable = run("/bin/ps", ["-p", String(runtime.pid), "-o", "comm="]);
93 const app = executable.includes("/Contents/MacOS/")
94 ? executable.split("/Contents/MacOS/")[0]
95 : null;
96 const cli = app
97 ? [
98 executable,
99 path.join(app, "Contents/Resources/app.asar/apps/server/dist/bin.mjs"),
100 ]
101 : [executable];
102 const authFile = path.join(state, "t3-auth.json");
103 let authentication;
104 if (fs.existsSync(authFile) && Date.now() - fs.statSync(authFile).mtimeMs < 60_000) {
105 authentication = JSON.parse(fs.readFileSync(authFile));
106 }
107 if (authentication?.pid !== runtime.pid) {
108 const token = childProcess.execFileSync(cli[0], [
109 ...cli.slice(1),
110 "auth",
111 "session",
112 "issue",
113 "--base-dir",
114 t3Home,
115 "--ttl",
116 "2m",
117 "--token-only",
118 ], {
119 env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
120 encoding: "utf8",
121 timeout: 15_000,
122 stdio: ["ignore", "pipe", "pipe"],
123 }).trim();
124 authentication = { pid: runtime.pid, token };
125 writeJson(authFile, authentication);
126 }
127
128 async function request(route, body) {
129 const response = await fetch(new URL(route, origin), {
130 method: body === undefined ? "GET" : "POST",
131 // Synchronous JJ/pnpm calls can outlive HTTP keep-alive sockets.
132 headers: {
133 Authorization: `Bearer ${authentication.token}`,
134 "Content-Type": "application/json",
135 "x-t3-orchestration-protocol": "2",
136 Connection: "close",
137 },
138 body: body === undefined ? undefined : JSON.stringify(body),
139 signal: AbortSignal.timeout(10_000),
140 });
141 if (!response.ok) {
142 throw new Error(
143 `T3 Code returned ${response.status}. Cleanup is paused; check the nightly app.`,
144 );
145 }
146 return response.json();
147 }
148
149 const environment = await request("/.well-known/t3/environment");
150 if (environment.orchestrationProtocolVersion !== 2) {
151 throw new Error("Update T3 Code to a nightly build with orchestrator V2.");
152 }
153
154 async function snapshot() {
155 const [data, archived] = await Promise.all([
156 request("/api/orchestration/shell"),
157 rpc("orchestration.getArchivedShellSnapshot", {}),
158 ]);
159 if (
160 !Array.isArray(data.projects) || !Array.isArray(data.threads) ||
161 !Array.isArray(archived.threads)
162 ) {
163 throw new Error(
164 "T3 Code returned an unknown thread list. Cleanup is paused.",
165 );
166 }
167 data.archivedThreads = archived.threads;
168 for (const thread of [...data.threads, ...data.archivedThreads]) {
169 if (
170 ![
171 "settledOverride",
172 "activeRunId",
173 "worktreePath",
174 "deletedAt",
175 "archivedAt",
176 "pendingRuntimeRequest",
177 "status",
178 ].every((field) => field in thread)
179 ) {
180 throw new Error(
181 "T3 Code returned an unknown thread state. Cleanup is paused.",
182 );
183 }
184 }
185 return data;
186 }
187
188 async function rpc(tag, payload) {
189 const { ticket } = await request("/api/auth/websocket-ticket", {});
190 const url = new URL("/ws", origin);
191 url.protocol = "ws:";
192 url.searchParams.set("wsTicket", ticket);
193 url.searchParams.set("orchestrationProtocol", "2");
194 return new Promise((resolve, reject) => {
195 const socket = new WebSocket(url);
196 const timeout = setTimeout(
197 () =>
198 finish(
199 new Error(
200 "T3 Code did not respond. Start the nightly app and retry.",
201 ),
202 ),
203 15_000,
204 );
205 function finish(error, value) {
206 clearTimeout(timeout);
207 socket.close();
208 if (error) reject(error);
209 else resolve(value);
210 }
211 socket.onopen = () =>
212 socket.send(
213 JSON.stringify({
214 _tag: "Request",
215 id: "1",
216 tag,
217 payload,
218 headers: [],
219 }) + "\n",
220 );
221 socket.onmessage = (event) => {
222 for (const line of String(event.data).trim().split("\n")) {
223 const message = JSON.parse(line);
224 if (message._tag !== "Exit" || String(message.requestId) !== "1") {
225 continue;
226 }
227 if (message.exit._tag === "Success") finish(null, message.exit.value);
228 else {
229 finish(
230 new Error(
231 `T3 Code rejected the workspace request: ${
232 JSON.stringify(message.exit)
233 }`,
234 ),
235 );
236 }
237 }
238 };
239 socket.onerror = () =>
240 finish(
241 new Error("Cannot reach T3 Code. Start the nightly app and retry."),
242 );
243 socket.onclose = () => {
244 clearTimeout(timeout);
245 reject(new Error("T3 Code closed the chat connection."));
246 };
247 });
248 }
249
250 function dispatch(command) {
251 return rpc(
252 command.type.startsWith("project.")
253 ? "projects.mutate"
254 : "orchestration.dispatchCommand",
255 { commandId: randomUUID(), ...command },
256 );
257 }
258
259 return { snapshot, dispatch, rpc, environment, app };
260}
261
262function dependencyKey(directory) {
263 const files = run("jj", ["--ignore-working-copy", "file", "list"], directory).split("\n").filter((
264 file,
265 ) =>
266 path.basename(file) === "package.json" ||
267 ["pnpm-lock.yaml", "pnpm-workspace.yaml", ".npmrc", ".pnpmfile.cjs"]
268 .includes(file) ||
269 file.startsWith("patches/")
270 ).sort();
271 const hash = createHash("sha256");
272 hash.update(
273 `${process.platform}:${process.arch}:${process.versions.modules}:${
274 run("pnpm", ["--version"], directory)
275 }\0`,
276 );
277 for (const file of files) {
278 hash.update(file + "\0").update(fs.readFileSync(path.join(directory, file)))
279 .update("\0");
280 }
281 return hash.digest("hex");
282}
283
284function moduleDirectories(directory, relative = "") {
285 const found = [];
286 for (
287 const entry of fs.readdirSync(path.join(directory, relative), {
288 withFileTypes: true,
289 })
290 ) {
291 if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
292 const child = path.join(relative, entry.name);
293 if (entry.name === "node_modules") found.push(child);
294 else found.push(...moduleDirectories(directory, child));
295 }
296 return found;
297}
298
299function dependencies(directory, source) {
300 const key = dependencyKey(directory);
301 let seed;
302 if (
303 fs.existsSync(path.join(cache, "key")) &&
304 fs.readFileSync(path.join(cache, "key"), "utf8") === key
305 ) seed = cache;
306 else if (
307 dependencyKey(source) === key &&
308 fs.existsSync(path.join(source, "node_modules/.pnpm/lock.yaml"))
309 ) seed = source;
310 if (seed) {
311 for (const relative of moduleDirectories(seed)) {
312 const target = path.join(directory, relative);
313 if (fs.existsSync(target) || !fs.existsSync(path.dirname(target))) {
314 continue;
315 }
316 run(
317 "workspace-native",
318 ["clone", path.join(seed, relative), target],
319 undefined,
320 true,
321 );
322 }
323 }
324
325 // pnpm regenerates launchers that embed the previous workspace's absolute path.
326 run(
327 "pnpm",
328 [
329 "install",
330 "--frozen-lockfile",
331 "--prefer-offline",
332 "--store-dir",
333 path.join(home, ".local/share/pnpm/store"),
334 ],
335 directory,
336 true,
337 );
338 if (dependencyKey(directory) !== key) {
339 throw new Error(
340 "Dependency files changed during installation. Run ws deps again.",
341 );
342 }
343 if (seed === cache) return;
344
345 const temporary = `${cache}.tmp`;
346 fs.rmSync(temporary, { recursive: true, force: true });
347 fs.mkdirSync(temporary, { recursive: true });
348 for (const relative of moduleDirectories(directory)) {
349 const target = path.join(temporary, relative);
350 fs.mkdirSync(path.dirname(target), { recursive: true });
351 run(
352 "workspace-native",
353 ["clone", path.join(directory, relative), target],
354 undefined,
355 true,
356 );
357 }
358 fs.writeFileSync(path.join(temporary, "key"), key);
359 fs.rmSync(cache, { recursive: true, force: true });
360 fs.renameSync(temporary, cache);
361}
362
363async function editorReferences() {
364 const processes = run("/bin/ps", ["-axo", "pid=,comm="]);
365 const instances = processes.split("\n").filter((line) =>
366 line.endsWith("/Visual Studio Code.app/Contents/MacOS/Code")
367 ).map((line) => Number(line.trim().split(/\s+/, 1)[0]));
368 if (!instances.length) return [];
369 const status = run("/usr/local/bin/code", ["--status"]);
370 const reported = [...status.matchAll(/^\s*\d+\s+\d+\s+(\d+)\s+code\s*$/gm)]
371 .map((match) => Number(match[1]));
372 if (instances.some((pid) => !reported.includes(pid))) {
373 throw new Error(
374 "Cannot inspect every VS Code instance. Cleanup is paused.",
375 );
376 }
377 const pids = [...status.matchAll(/\b(\d+)\s+extension-host\b/g)].map((
378 match,
379 ) => Number(match[1]));
380 const windows = [...status.matchAll(/\bwindow \[\d+\]/g)].length;
381 if (pids.length < windows) {
382 throw new Error(
383 "VS Code has a window without a reference tracker. Reload its windows before cleanup.",
384 );
385 }
386 const paths = [];
387 for (const pid of pids) {
388 const response = await new Promise((resolve, reject) => {
389 const socket = net.createConnection(
390 path.join(state, "vscode", `${pid}.sock`),
391 );
392 let data = "";
393 socket.setTimeout(
394 2000,
395 () =>
396 socket.destroy(
397 new Error(
398 "VS Code reference tracker did not respond. Reload its windows before cleanup.",
399 ),
400 ),
401 );
402 socket.on("data", (chunk) => {
403 data += chunk;
404 });
405 socket.on("end", () => {
406 try {
407 resolve(JSON.parse(data));
408 } catch (error) {
409 reject(error);
410 }
411 });
412 socket.on("error", reject);
413 });
414 if (response.pid !== pid || !Array.isArray(response.paths)) {
415 throw new Error(
416 "Cannot verify VS Code's open folders. Reload its windows before cleanup.",
417 );
418 }
419 paths.push(...response.paths.map(canonical));
420 }
421 return paths;
422}
423
424function terminalReferences() {
425 const pids = new Set();
426 const processes = run("/bin/ps", ["-axo", "pid=,tty=,comm="]);
427 for (const line of processes.split("\n")) {
428 const match = line.match(/^\s*(\d+)\s+(\S+)\s+(.+)$/);
429 if (match && match[2] !== "??" && /\/(zsh|bash|fish|sh)$/.test(match[3])) {
430 pids.add(Number(match[1]));
431 }
432 }
433 const directory = path.join(state, "shells");
434 for (
435 const name of fs.existsSync(directory) ? fs.readdirSync(directory) : []
436 ) {
437 if (!/^\d+$/.test(name)) continue;
438 const pid = Number(name);
439 if (alive(pid)) pids.add(pid);
440 else fs.rmSync(path.join(directory, name));
441 }
442 if (!pids.size) return [];
443
444 let output;
445 try {
446 output = run("/usr/sbin/lsof", [
447 "-a",
448 "-p",
449 [...pids].join(","),
450 "-d",
451 "cwd",
452 "-Fpn",
453 ]);
454 } catch (error) {
455 if (error.status !== 1) throw error;
456 output = String(error.stdout ?? "");
457 }
458 const found = new Set();
459 const paths = [];
460 let pid;
461 for (const line of output.split("\n")) {
462 if (line.startsWith("p")) pid = Number(line.slice(1));
463 if (line.startsWith("n")) {
464 found.add(pid);
465 paths.push(canonical(line.slice(1)));
466 }
467 }
468 for (const pid of pids) {
469 if (!found.has(pid) && alive(pid)) {
470 throw new Error(
471 `Cannot read terminal ${pid}'s folder. Cleanup is paused.`,
472 );
473 }
474 }
475 return paths;
476}
477
478async function references(client) {
479 const [snapshot, editors] = await Promise.all([
480 client.snapshot(),
481 editorReferences(),
482 ]);
483 const projects = new Map(
484 snapshot.projects.map((project) => [project.id, project.workspaceRoot]),
485 );
486 const chats = [];
487 for (const thread of [...snapshot.threads, ...snapshot.archivedThreads]) {
488 const released = thread.deletedAt !== null || thread.archivedAt !== null;
489 const busy = ![
490 "idle",
491 "completed",
492 "interrupted",
493 "failed",
494 "cancelled",
495 "rolled_back",
496 ].includes(thread.status) || thread.activeRunId !== null ||
497 thread.pendingRuntimeRequest !== null ||
498 thread.pendingBackgroundTasks?.length > 0;
499 if (released && !busy) continue;
500 const directory = thread.worktreePath ?? projects.get(thread.projectId);
501 if (!directory) {
502 throw new Error(
503 "Cannot locate a T3 chat's workspace. Cleanup is paused.",
504 );
505 }
506 chats.push(canonical(directory));
507 }
508 return { chats, editors, terminals: terminalReferences() };
509}
510
511async function openChat(id, config, client, open = true) {
512 const directory = workspace(id);
513 const file = path.join(records, `${id}.json`);
514 const record = JSON.parse(fs.readFileSync(file));
515 const snapshot = await client.snapshot();
516 const repository = jjRepository(config.repository);
517 const source = snapshot.projects.find((project) =>
518 canonical(project.workspaceRoot) === config.repository
519 ) ?? snapshot.projects.find((project) =>
520 !inside(canonical(project.workspaceRoot), root) &&
521 fs.existsSync(path.join(project.workspaceRoot, ".jj/repo")) &&
522 jjRepository(project.workspaceRoot) === repository
523 );
524 if (!source) {
525 throw new Error(
526 "Add the source repository to T3 Code before creating a workspace chat.",
527 );
528 }
529 let thread = [...snapshot.threads, ...snapshot.archivedThreads].find(
530 (thread) => thread.id === record.threadId,
531 );
532 if (!thread) {
533 let project = snapshot.projects.find((project) =>
534 canonical(project.workspaceRoot) === directory
535 );
536 const latest = [...snapshot.threads, ...snapshot.archivedThreads].filter(
537 (thread) => thread.projectId === (project?.id ?? source.id),
538 ).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0];
539 const modelSelection = project?.defaultModelSelection ??
540 source.defaultModelSelection ??
541 latest?.modelSelection;
542 if (!modelSelection) {
543 throw new Error(
544 "Choose a model in the source repository's T3 settings, then run ws open again.",
545 );
546 }
547 if (!project) {
548 project = await client.dispatch({
549 type: "project.create",
550 projectId: randomUUID(),
551 title: `${source.title} | ${id}`,
552 workspaceRoot: directory,
553 });
554 }
555 await client.dispatch({
556 type: "project.update",
557 projectId: project.id,
558 projectIcon: source.projectIcon ?? null,
559 faviconPath: source.faviconPath ?? null,
560 defaultThreadEnvMode: "local",
561 defaultModelSelection: modelSelection,
562 });
563 const threadId = record.threadId ?? randomUUID();
564 record.threadId = threadId;
565 writeJson(file, record);
566 await client.dispatch({
567 type: "thread.create",
568 threadId,
569 projectId: project.id,
570 title: project.title,
571 modelSelection,
572 runtimeMode: latest?.runtimeMode ?? "full-access",
573 interactionMode: latest?.interactionMode ?? "default",
574 branch: null,
575 worktreePath: null,
576 createdBy: "user",
577 creationSource: "web",
578 });
579 const confirmed = await client.snapshot();
580 thread = confirmed.threads.find((thread) => thread.id === threadId);
581 if (!thread) {
582 throw new Error(
583 "T3 Code has not confirmed the chat yet. Run ws open again.",
584 );
585 }
586 }
587 if (thread.archivedAt) {
588 await client.dispatch({ type: "thread.unarchive", threadId: thread.id });
589 }
590 if (thread.settledOverride === "settled") {
591 await client.dispatch({
592 type: "thread.unsettle",
593 threadId: thread.id,
594 reason: "user",
595 });
596 }
597 record.idleSince = null;
598 writeJson(file, record);
599 const environmentId = client.environment.environmentId;
600 if (open) {
601 run("/usr/bin/open", [
602 ...(client.app ? ["-a", client.app] : ["-b", "com.t3tools.t3code"]),
603 `t3code://threads/${environmentId}/${record.threadId}`,
604 ]);
605 }
606 return {
607 workspacePath: directory,
608 projectId: thread.projectId,
609 threadId: thread.id,
610 environmentId,
611 };
612}
613
614export async function main(args) {
615 const [command, argument, ...rest] = args;
616 if (command === "ready-hook") {
617 let input = "";
618 for await (const chunk of process.stdin) input += chunk;
619 const event = JSON.parse(input);
620 const directory = canonical(event.cwd);
621 if (!inside(directory, root)) return;
622 const id = path.relative(root, directory).split(path.sep)[0];
623 const file = path.join(records, `${id}.json`);
624 if (!fs.existsSync(file)) return;
625
626 const deadline = Date.now() + 240_000;
627 let waited = false;
628 while (true) {
629 const record = JSON.parse(fs.readFileSync(file));
630 if (record.preparationError) {
631 throw new Error(`Workspace ${id} setup stopped: ${record.preparationError}. Run ws deps ${id}, then resend your prompt.`);
632 }
633 if (record.prepared) break;
634 if (Date.now() >= deadline) {
635 throw new Error(`Workspace ${id} is still preparing. Check ~/Library/Logs/workspace-${id}.log, then resend your prompt.`);
636 }
637 waited = true;
638 await new Promise((resolve) => setTimeout(resolve, 100));
639 }
640 if (waited && event.hook_event_name === "SessionStart") {
641 const files = new Set(["AGENTS.md", "CLAUDE.md"].map((name) =>
642 path.join(workspace(id), name)
643 ).filter((file) => fs.existsSync(file)).map(canonical));
644 const instructions = [...files].map((file) => fs.readFileSync(file, "utf8"));
645 if (instructions.length) {
646 console.log(JSON.stringify({ hookSpecificOutput: {
647 hookEventName: "SessionStart",
648 additionalContext: instructions.join("\n\n"),
649 } }));
650 }
651 }
652 return;
653 }
654 if (!command || command === "--help") {
655 console.log(
656 "ws setup <repository>\nws new [name] [-r revision] [--no-open] [--background] [--json]\nws open <name> [--no-open]\nws deps <name>\nws gc [--dry-run]",
657 );
658 return;
659 }
660 fs.mkdirSync(state, { recursive: true, mode: 0o700 });
661 if (command === "setup") {
662 if (!argument || rest.length) throw new Error("Run ws setup <repository>.");
663 const repository = fs.realpathSync(
664 run("jj", ["workspace", "root"], path.resolve(argument)),
665 );
666 if (!fs.existsSync(path.join(repository, "pnpm-lock.yaml"))) {
667 throw new Error("Choose the repository's pnpm workspace root.");
668 }
669 if (fs.existsSync(records) && fs.readdirSync(records).length) {
670 const configured = JSON.parse(fs.readFileSync(configFile));
671 if (jjRepository(repository) !== jjRepository(configured.repository)) {
672 throw new Error(
673 "Finish existing workspaces before changing their source repository.",
674 );
675 }
676 }
677 writeJson(configFile, { repository });
678 console.log(`Workspace source: ${repository}`);
679 return;
680 }
681 if (
682 command === "gc" &&
683 (!fs.existsSync(records) || !fs.readdirSync(records).length)
684 ) return;
685 const config = JSON.parse(fs.readFileSync(configFile));
686 if (["settle", "unsettle", "completion"].includes(command)) {
687 const expectedLength = command === "unsettle" ? 2 : command === "completion" ? 5 : 4;
688 if (
689 !argument || rest.length !== expectedLength || rest[0] !== "--thread-id" ||
690 (command !== "unsettle" && rest[2] !== "--settled-at") ||
691 (command === "completion" && rest[4] !== "--json")
692 ) {
693 throw new Error(`Run ws ${command} <name> --thread-id <id>${
694 command === "unsettle" ? "" : " --settled-at <time>"
695 }${command === "completion" ? " --json" : ""}.`);
696 }
697 const directory = workspace(argument);
698 const threadId = rest[1];
699 if (!/^[a-zA-Z0-9_-]+$/.test(threadId)) {
700 throw new Error("Choose a thread ID without path separators.");
701 }
702 const file = path.join(state, "settlements", argument, `${threadId}.json`);
703 if (command === "unsettle") {
704 fs.rmSync(file, { force: true });
705 return;
706 }
707 const settledAt = rest[3];
708 if (!Number.isFinite(Date.parse(settledAt))) {
709 throw new Error("Choose a valid settlement timestamp.");
710 }
711 const captured = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file)) : null;
712 if (command === "completion" && captured?.settledAt !== settledAt) {
713 console.log(JSON.stringify({ abandoned: false }));
714 return;
715 }
716 if (command === "settle" && captured?.settledAt === settledAt) return;
717 const record = JSON.parse(fs.readFileSync(path.join(records, `${argument}.json`)));
718 if (!record.prepared) {
719 throw new Error(`Workspace ${argument} is still preparing. Run ws deps ${argument}.`);
720 }
721 if (canonical(directory) !== directory || jjRepository(directory) !== jjRepository(config.repository)) {
722 throw new Error(`Workspace ${argument} belongs to another repository. Cleanup is paused.`);
723 }
724 if (command === "settle") {
725 const operationId = run("jj", [
726 "--ignore-working-copy", "op", "log", "-n", "1", "--no-graph", "-T", "id",
727 ], directory);
728 const [changeId, commitId] = run("jj", [
729 "log", "-r", "@", "--no-graph", "-T", 'change_id ++ "\n" ++ commit_id',
730 ], directory).split("\n");
731 writeJson(file, { settledAt, changeId, commitId, operationId });
732 return;
733 }
734 if (
735 !/^[k-z]{32}$/.test(captured.changeId) ||
736 !/^[a-f0-9]{40}$/.test(captured.commitId) ||
737 !/^[a-f0-9]{128}$/.test(captured.operationId)
738 ) throw new Error("The workspace settlement record is unreadable. Cleanup is paused.");
739 const currentEmpty = run("jj", ["log", "-r", "@", "--no-graph", "-T", "empty"], directory);
740 const knownChange = run("jj", [
741 "--ignore-working-copy", "log", "-r", captured.commitId, "--no-graph", "-T", "change_id",
742 ], directory);
743 if (knownChange !== captured.changeId) {
744 throw new Error("The captured workspace change is unreadable. Cleanup is paused.");
745 }
746 const visible = run("jj", [
747 "--ignore-working-copy", "log", "-r", `visible() & change_id(${captured.changeId})`,
748 "--no-graph", "-T", "commit_id",
749 ], directory);
750 // all() expands the historical baseline with the current ancestry's search space.
751 const laterWork = run("jj", [
752 "--ignore-working-copy", "log", "-r",
753 `(::@ ~ at_operation(${captured.operationId}, visible())) ~ empty()`,
754 "--no-graph", "-T", "commit_id",
755 ], directory);
756 console.log(JSON.stringify({
757 abandoned: visible === "" && currentEmpty === "true" && laterWork === "",
758 }));
759 return;
760 }
761 if (command === "deps") {
762 const file = path.join(records, `${argument}.json`);
763 const record = JSON.parse(fs.readFileSync(file));
764 delete record.preparationError;
765 writeJson(file, record);
766 try {
767 if ("revision" in record) {
768 if (record.revision === null) {
769 run("jj", [
770 "--ignore-working-copy",
771 "--config", "git.abandon-unreachable-commits=false",
772 "git", "fetch", "--remote", "origin", "--branch", "main",
773 ], config.repository, true);
774 }
775 const started = Date.now();
776 // Full sparse patterns let checkout wait without touching the source.
777 run("jj", [
778 "--ignore-working-copy", "workspace", "add",
779 "--name", `workspaces-${argument}`, "--sparse-patterns", "full",
780 "-r", record.revision ?? "main@origin", workspace(argument),
781 ], config.repository, true);
782 console.error(`JJ workspace initialized in ${Date.now() - started} ms`);
783 delete record.revision;
784 writeJson(file, record);
785 }
786 if (!record.prepared) {
787 run("jj", ["workspace", "update-stale"], workspace(argument), true);
788 }
789 dependencies(workspace(argument), config.repository);
790 record.prepared = true;
791 writeJson(file, record);
792 } catch (error) {
793 record.preparationError = error.message.split("\n", 1)[0];
794 writeJson(file, record);
795 throw error;
796 }
797 return;
798 }
799 if (command === "new") {
800 const client = await t3();
801 const open = ![argument, ...rest].includes("--no-open");
802 const background = [argument, ...rest].includes("--background");
803 const json = [argument, ...rest].includes("--json");
804 const options = [argument, ...rest].filter((value) =>
805 value !== undefined && value !== "--no-open" && value !== "--background" &&
806 value !== "--json"
807 );
808 const id = options[0]?.startsWith("-") ? undefined : options.shift();
809 const revision = options.length === 0
810 ? null
811 : options.length === 2 && options[0] === "-r"
812 ? options[1]
813 : undefined;
814 if (revision === undefined) throw new Error("Run ws new [name] [-r revision].");
815 fs.mkdirSync(root, { recursive: true });
816 let number = 1;
817 while (
818 fs.existsSync(workspace(String(number))) ||
819 fs.existsSync(path.join(records, `${number}.json`))
820 ) number++;
821 const name = id ?? String(number);
822 const directory = workspace(name);
823 if (
824 fs.existsSync(directory) ||
825 fs.existsSync(path.join(records, `${name}.json`))
826 ) throw new Error(`Workspace ${name} already exists. Run ws open ${name}.`);
827 fs.mkdirSync(directory);
828 const file = path.join(records, `${name}.json`);
829 writeJson(file, {
830 threadId: null,
831 idleSince: null,
832 prepared: false,
833 revision,
834 });
835 const created = await openChat(name, config, client, open);
836 console.log(json ? JSON.stringify(created) : created.workspacePath);
837 const logs = path.join(home, "Library/Logs");
838 fs.mkdirSync(logs, { recursive: true });
839 const output = background
840 ? fs.openSync(path.join(logs, `workspace-${name}.log`), "w", 0o600)
841 : 2;
842 try {
843 const child = childProcess.spawn("workspace-native", [
844 "wait-lock", path.join(state, "lock"), process.execPath,
845 fileURLToPath(import.meta.url), "deps", name,
846 ], {
847 detached: background,
848 stdio: ["ignore", output, output],
849 });
850 if (background) {
851 await new Promise((resolve, reject) => {
852 child.once("spawn", resolve);
853 child.once("error", reject);
854 });
855 child.unref();
856 } else {
857 const status = await new Promise((resolve, reject) => {
858 child.once("exit", resolve);
859 child.once("error", reject);
860 });
861 if (status !== 0) {
862 throw new Error(`Workspace ${name} setup stopped. Run ws deps ${name} to retry.`);
863 }
864 }
865 } finally {
866 if (background) fs.closeSync(output);
867 }
868 } else if (command === "open") {
869 if (rest.length > 1 || (rest[0] && rest[0] !== "--no-open")) {
870 throw new Error("Run ws open <name> [--no-open].");
871 }
872 const opened = await openChat(argument, config, await t3(), rest[0] !== "--no-open");
873 console.log(opened.workspacePath);
874 } else if (command === "gc") {
875 if (rest.length || (argument && argument !== "--dry-run")) {
876 throw new Error("Run ws gc [--dry-run].");
877 }
878 const entries = fs.readdirSync(records).filter((file) =>
879 file.endsWith(".json")
880 );
881 try {
882 const client = await t3();
883 if (argument !== "--dry-run") {
884 for (const entry of entries) {
885 const record = JSON.parse(fs.readFileSync(path.join(records, entry)));
886 if (!record.threadId || !record.prepared) continue;
887 const result = await client.rpc("managedWorkspaces.archiveCompleted", {
888 workspacePath: workspace(entry.slice(0, -5)),
889 });
890 if (
891 !Array.isArray(result?.archivedThreadIds) ||
892 !result.archivedThreadIds.every((id) => typeof id === "string")
893 ) {
894 throw new Error("T3 Code returned an unknown archive result. Cleanup is paused.");
895 }
896 }
897 }
898 const refs = await references(client);
899 for (const entry of entries) {
900 const id = entry.slice(0, -5);
901 const directory = workspace(id);
902 const file = path.join(records, entry);
903 const record = JSON.parse(fs.readFileSync(file));
904 const idleSince = record.idleSince;
905 const blockers = Object.entries(refs).filter(([, paths]) =>
906 paths.some((candidate) => inside(candidate, canonical(directory)))
907 ).map(([kind]) => kind);
908 if (!record.threadId || !record.prepared) blockers.push("unfinished setup");
909 if (blockers.length) {
910 record.idleSince = null;
911 if (argument === "--dry-run") {
912 console.log(`${id}: held by ${blockers.join(", ")}`);
913 }
914 } else {
915 record.idleSince ??= Date.now();
916 if (Date.now() - record.idleSince >= 60_000) {
917 if (argument === "--dry-run") {
918 console.log(`${id}: ready for cleanup`);
919 continue;
920 }
921 const fresh = await references(client);
922 if (
923 Object.values(fresh).some((paths) =>
924 paths.some((candidate) =>
925 inside(candidate, canonical(directory))
926 )
927 )
928 ) {
929 record.idleSince = null;
930 } else {
931 if (
932 fs.lstatSync(directory).isSymbolicLink() ||
933 canonical(directory) !== directory
934 ) {
935 throw new Error(
936 `Workspace ${id} was replaced by a link. Cleanup is paused.`,
937 );
938 }
939 if (jjRepository(directory) !== jjRepository(config.repository)) {
940 throw new Error(
941 `Workspace ${id} belongs to another repository. Cleanup is paused.`,
942 );
943 }
944 run("jj", ["status"], directory);
945 run(
946 "jj",
947 ["--ignore-working-copy", "workspace", "forget", `workspaces-${id}`],
948 config.repository,
949 );
950 fs.rmSync(directory, { recursive: true });
951 fs.rmSync(file);
952 fs.rmSync(path.join(state, "settlements", id), { recursive: true, force: true });
953 console.log(`Removed workspace ${id}`);
954 continue;
955 }
956 } else if (argument === "--dry-run") {
957 console.log(`${id}: grace period`);
958 }
959 }
960 if (record.idleSince !== idleSince) writeJson(file, record);
961 }
962 } catch (error) {
963 for (const entry of entries) {
964 const file = path.join(records, entry);
965 if (!fs.existsSync(file)) continue;
966 const record = JSON.parse(fs.readFileSync(file));
967 if (record.idleSince !== null) {
968 record.idleSince = null;
969 writeJson(file, record);
970 }
971 }
972 throw error;
973 }
974 } else throw new Error("Unknown workspace command. Run ws --help.");
975}
976
977if (
978 process.argv[1] &&
979 path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
980) {
981 main(process.argv.slice(2)).catch((error) => {
982 if (process.argv[2] === "ready-hook") {
983 console.log(JSON.stringify({
984 continue: false, stopReason: error.message, systemMessage: error.message,
985 }));
986 return;
987 }
988 if (error.stderr?.length) console.error(error.stderr.toString().trim());
989 console.error(`Error: ${error.message.split("\n", 1)[0]}`);
990 process.exitCode = 1;
991 });
992}
users/clover/packages/workspaces/workspaces.test.mjs deleted-834
......@@ -1,834 +0,0 @@
1import assert from "node:assert/strict";
2import { mock, test } from "node:test";
3import fs from "node:fs";
4import path from "node:path";
5import net from "node:net";
6import childProcess from "node:child_process";
7import { once } from "node:events";
8import { randomUUID } from "node:crypto";
9import { fileURLToPath } from "node:url";
10
11const cli = process.env.T3_TEST_CLI;
12const native = process.env.WORKSPACE_TEST_NATIVE;
13
14test("workspace lifecycle through nightly, JJ, APFS, and reference sockets", {
15 skip: !cli || !native,
16 timeout: 120_000,
17}, async () => {
18 const directory = fs.realpathSync(fs.mkdtempSync("/tmp/workspaces-test-"));
19 const originalHome = process.env.HOME;
20 const originalT3 = process.env.T3CODE_HOME;
21 const originalPath = process.env.PATH;
22 process.env.HOME = directory;
23 process.env.T3CODE_HOME = path.join(directory, ".t3");
24 process.env.PATH = path.dirname(native) + path.delimiter + originalPath;
25 const source = path.join(directory, "source");
26 const run = childProcess.execFileSync;
27 const reservation = net.createServer();
28 reservation.listen(0, "127.0.0.1");
29 await once(reservation, "listening");
30 const port = reservation.address().port;
31 await new Promise((resolve) => reservation.close(resolve));
32 const serverLog = fs.openSync(path.join(directory, "t3.log"), "w");
33 const server = childProcess.spawn(cli, [
34 "serve",
35 "--base-dir",
36 process.env.T3CODE_HOME,
37 "--port",
38 String(port),
39 "--no-browser",
40 ], { stdio: ["ignore", serverLog, serverLog] });
41 let editor;
42 let shell;
43 try {
44 fs.mkdirSync(path.join(source, "shared/local"), { recursive: true });
45 fs.writeFileSync(path.join(source, ".gitignore"), "node_modules/\n");
46 fs.writeFileSync(
47 path.join(source, "logo.svg"),
48 '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8" fill="red"/></svg>',
49 );
50 fs.writeFileSync(
51 path.join(source, "package.json"),
52 JSON.stringify({
53 name: "fixture",
54 private: true,
55 packageManager: "pnpm@10.32.1",
56 dependencies: { "local-dependency": "workspace:*" },
57 }),
58 );
59 fs.writeFileSync(
60 path.join(source, "pnpm-workspace.yaml"),
61 "packages:\n - shared/*\n",
62 );
63 fs.writeFileSync(
64 path.join(source, "shared/local/package.json"),
65 JSON.stringify({
66 name: "local-dependency",
67 version: "1.0.0",
68 main: "index.js",
69 bin: { "local-command": "bin.js" },
70 }),
71 );
72 fs.writeFileSync(
73 path.join(source, "shared/local/index.js"),
74 "module.exports = 42;\n",
75 );
76 fs.writeFileSync(
77 path.join(source, "shared/local/bin.js"),
78 "#!/usr/bin/env node\nconsole.log(process.env.NODE_PATH);\n",
79 );
80 run("jj", ["git", "init", "--colocate", source], { stdio: "pipe" });
81 run("pnpm", ["install", "--no-frozen-lockfile"], {
82 cwd: source,
83 stdio: "pipe",
84 timeout: 30_000,
85 });
86 const origin = path.join(directory, "origin");
87 run("jj", ["git", "init", origin], { stdio: "pipe" });
88 run("jj", ["describe", "-m", "Fixture main"], { cwd: source, stdio: "pipe" });
89 run("jj", ["bookmark", "set", "main"], { cwd: source, stdio: "pipe" });
90 run("jj", ["git", "remote", "add", "origin", path.join(origin, ".jj/repo/store/git")], {
91 cwd: source,
92 stdio: "pipe",
93 });
94 run("jj", ["--config", "git.sign-on-push=false", "git", "push", "--bookmark", "main"], {
95 cwd: source,
96 stdio: "pipe",
97 });
98 run("jj", ["git", "import"], { cwd: origin, stdio: "pipe" });
99 run("jj", ["new", "main"], { cwd: origin, stdio: "pipe" });
100 fs.writeFileSync(path.join(origin, "upstream.txt"), "latest main\n");
101 run("jj", ["describe", "-m", "Advance remote main"], {
102 cwd: origin,
103 stdio: "pipe",
104 });
105 run("jj", ["bookmark", "set", "main"], { cwd: origin, stdio: "pipe" });
106 run("jj", ["git", "export"], { cwd: origin, stdio: "pipe" });
107 const latestMain = run("jj", ["log", "-r", "main", "--no-graph", "-T", "commit_id"], {
108 cwd: origin,
109 encoding: "utf8",
110 }).trim();
111 assert.notEqual(run("jj", [
112 "log", "-r", "main@origin", "--no-graph", "-T", "commit_id",
113 ], { cwd: source, encoding: "utf8" }).trim(), latestMain);
114 const runtime = path.join(
115 process.env.T3CODE_HOME,
116 "userdata/server-runtime.json",
117 );
118 for (let attempt = 0; !fs.existsSync(runtime); attempt++) {
119 assert.ok(
120 attempt < 150 && server.exitCode === null,
121 "nightly server starts",
122 );
123 await new Promise((resolve) => setTimeout(resolve, 100));
124 }
125 const projectWorkspace = path.join(directory, "Fixture");
126 run("jj", ["workspace", "add", "-r", "@", projectWorkspace], {
127 cwd: source,
128 stdio: "pipe",
129 });
130 run(
131 cli,
132 ["project", "add", projectWorkspace, "--base-dir", process.env.T3CODE_HOME],
133 { stdio: "pipe", timeout: 15_000 },
134 );
135 const { main, t3 } = await import("./workspaces.mjs");
136 const client = await t3();
137 const archiveRequests = [];
138 let archiveHandler = () => ({ archivedThreadIds: [] });
139 const WebSocket = globalThis.WebSocket;
140 mock.method(globalThis, "WebSocket", function (...args) {
141 const socket = new WebSocket(...args);
142 const send = socket.send.bind(socket);
143 socket.send = (data) => {
144 const request = JSON.parse(String(data).trim());
145 if (request.tag !== "managedWorkspaces.archiveCompleted") return send(data);
146 archiveRequests.push(request.payload);
147 Promise.resolve().then(() => archiveHandler(request.payload)).then(
148 (value) => ({ _tag: "Success", value }),
149 (error) => ({ _tag: "Failure", cause: error.message }),
150 ).then((exit) => socket.onmessage(new MessageEvent("message", {
151 data: JSON.stringify({ _tag: "Exit", requestId: request.id, exit }) + "\n",
152 })));
153 };
154 return socket;
155 });
156 const project = (await client.snapshot()).projects[0];
157 await client.dispatch({
158 type: "project.update",
159 projectId: project.id,
160 projectIcon: { kind: "monogram", text: "F", color: "red" },
161 faviconPath: "logo.svg",
162 defaultThreadEnvMode: "worktree",
163 });
164 await client.dispatch({
165 type: "thread.create",
166 threadId: randomUUID(),
167 projectId: project.id,
168 title: "Model source",
169 modelSelection: { instanceId: "codex", model: "gpt-6.1-sol" },
170 runtimeMode: "approval-required",
171 interactionMode: "default",
172 branch: null,
173 worktreePath: null,
174 createdBy: "user",
175 creationSource: "web",
176 });
177 await main(["setup", source]);
178 const sourceChange = run("jj", ["log", "-r", "@", "--no-graph", "-T", "change_id"], {
179 cwd: source,
180 encoding: "utf8",
181 }).trim();
182 fs.writeFileSync(path.join(source, "local-only.txt"), "uncommitted source work\n");
183 fs.writeFileSync(path.join(projectWorkspace, "rewrite.txt"), "changed from another workspace\n");
184 run("jj", ["restore", "--from", "@", "--into", sourceChange, "rewrite.txt"], {
185 cwd: projectWorkspace,
186 stdio: "pipe",
187 });
188 assert.throws(() => run("jj", ["--config", "snapshot.auto-update-stale=false", "st"], {
189 cwd: source,
190 stdio: "pipe",
191 }), (error) => /working copy is stale/.test(error.stderr.toString()));
192 const firstBin = path.join(directory, "first-bin");
193 fs.mkdirSync(firstBin);
194 const pnpm = run("/usr/bin/which", ["pnpm"], { encoding: "utf8" }).trim();
195 fs.writeFileSync(path.join(firstBin, "pnpm"), `#!/usr/bin/env node
196const fs = require("node:fs");
197const childProcess = require("node:child_process");
198const assert = require("node:assert/strict");
199const args = process.argv.slice(2);
200if (args[0] === "install" && process.cwd() === ${JSON.stringify(path.join(directory, "workspaces/first"))}) {
201 const record = JSON.parse(fs.readFileSync(${JSON.stringify(path.join(directory, ".local/state/workspaces/workspaces/first.json"))}));
202 assert.ok(record.threadId, "chat is durable before dependency installation");
203 assert.equal(record.prepared, false);
204 console.error("Error: fixture installation interrupted");
205 process.exit(41);
206}
207const result = childProcess.spawnSync(${JSON.stringify(pnpm)}, args, { stdio: "inherit" });
208process.exit(result.status ?? 1);
209`, { mode: 0o700 });
210 const nativePath = process.env.PATH;
211 process.env.PATH = firstBin + path.delimiter + nativePath;
212 let opened = false;
213 const launchMock = mock.method(
214 childProcess,
215 "execFileSync",
216 (command, args, options) => {
217 if (command === "/usr/bin/open") {
218 opened = true;
219 assert.match(args.at(-1), /^t3code:\/\/threads\//);
220 assert.equal(
221 fs.existsSync(path.join(directory, "workspaces/first/.jj")),
222 false,
223 "desktop opens before JJ initializes the folder",
224 );
225 return "";
226 }
227 return run(command, args, options);
228 },
229 );
230 await assert.rejects(
231 main(["new", "first", "-r", "@"]),
232 /setup stopped/,
233 );
234 assert.ok(opened, "desktop opens before dependency installation");
235 process.env.PATH = nativePath;
236 launchMock.mock.restore();
237 assert.equal(fs.readFileSync(path.join(source, "local-only.txt"), "utf8"),
238 "uncommitted source work\n", "creation preserves unsaved source edits");
239 assert.equal(fs.existsSync(path.join(source, "rewrite.txt")), false,
240 "workspace creation leaves the stale source checkout untouched");
241 assert.throws(() => run("jj", ["--config", "snapshot.auto-update-stale=false", "st"], {
242 cwd: source,
243 stdio: "pipe",
244 }), (error) => /working copy is stale/.test(error.stderr.toString()));
245 await main(["setup", projectWorkspace]);
246 await main(["setup", source]);
247 const creationOutput = [];
248 const creationLog = mock.method(console, "log", (value) => creationOutput.push(value));
249 const noOpen = mock.method(childProcess, "execFileSync", (command, args, options) => {
250 assert.notEqual(command, "/usr/bin/open", "--no-open never launches the desktop app");
251 return run(command, args, options);
252 });
253 await main(["new", "second", "--no-open", "--json"]);
254 noOpen.mock.restore();
255 creationLog.mock.restore();
256 const created = (await client.snapshot()).threads.find((thread) =>
257 thread.title === "Fixture | second"
258 );
259 assert.equal(
260 created.runtimeMode,
261 "approval-required",
262 "new chats retain the source chat's permission mode",
263 );
264 assert.equal(creationOutput.length, 1, "JSON creation writes one structured result");
265 assert.deepEqual(JSON.parse(creationOutput[0]), {
266 workspacePath: path.join(directory, "workspaces/second"),
267 projectId: created.projectId,
268 threadId: created.id,
269 environmentId: client.environment.environmentId,
270 });
271 const first = path.join(directory, "workspaces/first");
272 const second = path.join(directory, "workspaces/second");
273 const projects = (await client.snapshot()).projects;
274 const firstProject = projects.find((project) =>
275 project.workspaceRoot === first
276 );
277 const secondProject = projects.find((project) =>
278 project.workspaceRoot === second
279 );
280 assert.equal(firstProject.title, "Fixture | first");
281 assert.equal(secondProject.title, "Fixture | second");
282 assert.notEqual(firstProject.id, secondProject.id);
283 assert.equal(created.projectId, secondProject.id);
284 assert.equal(
285 created.worktreePath, null, "new chats use their workspace project's root",
286 );
287 assert.deepEqual(secondProject.projectIcon, {
288 kind: "monogram", text: "F", color: "red",
289 });
290 assert.equal(secondProject.faviconPath, "logo.svg");
291 assert.equal(secondProject.defaultThreadEnvMode, "local");
292 assert.deepEqual(secondProject.defaultModelSelection, created.modelSelection);
293 assert.equal(run("jj", ["log", "-r", "@-", "--no-graph", "-T", "commit_id"], {
294 cwd: second,
295 encoding: "utf8",
296 }).trim(), latestMain, "default creation fetches the latest remote main");
297 assert.equal(fs.readFileSync(path.join(second, "upstream.txt"), "utf8"), "latest main\n");
298 assert.equal(fs.existsSync(path.join(second, "local-only.txt")), false,
299 "default creation excludes source-only work");
300 assert.equal(
301 run(process.execPath, [
302 "-e",
303 "process.stdout.write(String(require('local-dependency')))",
304 ], { cwd: second, encoding: "utf8" }),
305 "42",
306 );
307 const launcherPaths = run(
308 path.join(second, "node_modules/.bin/local-command"),
309 [],
310 { cwd: second, encoding: "utf8" },
311 );
312 assert.ok(launcherPaths.includes(second));
313 assert.equal(
314 launcherPaths.includes(source) || launcherPaths.includes(first),
315 false,
316 "pnpm relocates launchers after cloning",
317 );
318 const clonedFile = path.join(second, "node_modules/.pnpm/lock.yaml");
319 const cachedFile = path.join(
320 directory,
321 ".cache/workspaces/deps/node_modules/.pnpm/lock.yaml",
322 );
323 const cachedContents = fs.readFileSync(cachedFile, "utf8");
324 assert.notEqual(fs.statSync(clonedFile).ino, fs.statSync(cachedFile).ino);
325 fs.appendFileSync(clonedFile, "\n# isolated edit\n");
326 assert.equal(fs.readFileSync(cachedFile, "utf8"), cachedContents);
327 assert.equal(
328 fs.readlinkSync(path.join(second, "node_modules/local-dependency")),
329 "../shared/local",
330 );
331
332 const background = path.join(directory, "workspaces/background");
333 const started = path.join(directory, "preparation-started");
334 const release = path.join(directory, "preparation-release");
335 const fetchStarted = path.join(directory, "fetch-started");
336 const fetchRelease = path.join(directory, "fetch-release");
337 const bin = path.join(directory, "bin");
338 fs.mkdirSync(bin);
339 fs.writeFileSync(path.join(bin, "jj"), `#!/bin/sh
340case "$*" in
341 *"git fetch"*)
342 touch "$WORKSPACE_TEST_FETCH_STARTED"
343 while [ ! -f "$WORKSPACE_TEST_FETCH_RELEASE" ]; do sleep 0.05; done
344 ;;
345esac
346exec "$WORKSPACE_TEST_JJ" "$@"
347`, { mode: 0o700 });
348 fs.writeFileSync(path.join(bin, "pnpm"), `#!/bin/sh
349if [ "$1" = install ] && [ "$PWD" = "$WORKSPACE_TEST_BACKGROUND" ]; then
350 touch "$WORKSPACE_TEST_STARTED"
351 while [ ! -f "$WORKSPACE_TEST_RELEASE" ]; do sleep 0.05; done
352fi
353exec "$WORKSPACE_TEST_PNPM" "$@"
354`, { mode: 0o700 });
355 const script = fileURLToPath(new URL("./workspaces.mjs", import.meta.url));
356 const preparationEnv = {
357 ...process.env,
358 PATH: bin + path.delimiter + process.env.PATH,
359 WORKSPACE_TEST_BACKGROUND: background,
360 WORKSPACE_TEST_STARTED: started,
361 WORKSPACE_TEST_RELEASE: release,
362 WORKSPACE_TEST_FETCH_STARTED: fetchStarted,
363 WORKSPACE_TEST_FETCH_RELEASE: fetchRelease,
364 WORKSPACE_TEST_JJ: run("/usr/bin/which", ["jj"], {
365 encoding: "utf8",
366 }).trim(),
367 WORKSPACE_TEST_PNPM: pnpm,
368 };
369 const creator = childProcess.spawn(native, [
370 "lock",
371 path.join(directory, ".local/state/workspaces/creation-lock"),
372 process.execPath,
373 script,
374 "new", "background", "--no-open", "--background", "--json",
375 ], {
376 env: preparationEnv,
377 stdio: ["ignore", "pipe", "pipe"],
378 });
379 let creatorOutput = "";
380 let creatorStdout = "";
381 creator.stdout.on("data", (chunk) => {
382 creatorOutput += chunk;
383 creatorStdout += chunk;
384 });
385 creator.stderr.on("data", (chunk) => { creatorOutput += chunk; });
386 const [creatorStatus] = await once(creator, "exit");
387 assert.equal(creatorStatus, 0, creatorOutput);
388 const backgroundRecord = path.join(
389 directory, ".local/state/workspaces/workspaces/background.json",
390 );
391 const backgroundCreation = JSON.parse(creatorStdout);
392 const backgroundThread = (await client.snapshot()).threads.find(
393 (thread) => thread.id === backgroundCreation.threadId,
394 );
395 assert.deepEqual(backgroundCreation, {
396 workspacePath: background,
397 projectId: backgroundThread.projectId,
398 threadId: backgroundThread.id,
399 environmentId: client.environment.environmentId,
400 });
401 assert.equal(JSON.parse(fs.readFileSync(backgroundRecord)).prepared, false);
402 for (let attempt = 0; !fs.existsSync(fetchStarted); attempt++) {
403 assert.ok(attempt < 200, "background preparation starts fetching main");
404 await new Promise((resolve) => setTimeout(resolve, 50));
405 }
406 assert.equal(fs.existsSync(path.join(background, ".jj")), false,
407 "the chat is available while fetching main and before JJ initialization");
408 fs.writeFileSync(fetchRelease, "");
409 for (let attempt = 0; !fs.existsSync(started); attempt++) {
410 assert.ok(attempt < 200, "background preparation reaches installation");
411 await new Promise((resolve) => setTimeout(resolve, 50));
412 }
413 assert.throws(
414 () => run(native, [
415 "lock", path.join(directory, ".local/state/workspaces/lock"), "/usr/bin/true",
416 ], { stdio: "pipe" }),
417 (error) => /Another workspace command/.test(error.stderr.toString()),
418 "background preparation retains the workspace lock after its parent exits",
419 );
420 const queued = childProcess.spawn(native, [
421 "lock", path.join(directory, ".local/state/workspaces/creation-lock"),
422 process.execPath, script, "new", "queued", "--no-open", "--background",
423 ], { env: preparationEnv, stdio: "pipe" });
424 let queuedOutput = "";
425 let queuedStdout = "";
426 queued.stdout.on("data", (chunk) => { queuedStdout += chunk; });
427 queued.stderr.on("data", (chunk) => { queuedOutput += chunk; });
428 const [queuedStatus] = await once(queued, "exit");
429 assert.equal(queuedStatus, 0, queuedOutput);
430 assert.equal(queuedStdout.trim(), path.join(directory, "workspaces/queued"),
431 "default creation stdout remains the plain workspace path");
432 const queuedRecord = path.join(directory, ".local/state/workspaces/workspaces/queued.json");
433 assert.ok(JSON.parse(fs.readFileSync(queuedRecord)).threadId,
434 "another chat can be created while a preparation worker holds the lock");
435 assert.equal(fs.existsSync(path.join(directory, "workspaces/queued/.jj")), false);
436 fs.writeFileSync(release, "");
437 for (let attempt = 0;
438 !JSON.parse(fs.readFileSync(backgroundRecord)).prepared ||
439 !JSON.parse(fs.readFileSync(queuedRecord)).prepared;
440 attempt++) {
441 assert.ok(attempt < 200, "background preparation finishes");
442 await new Promise((resolve) => setTimeout(resolve, 50));
443 }
444
445 const recordFile = path.join(
446 directory,
447 ".local/state/workspaces/workspaces/first.json",
448 );
449 const readRecord = () => JSON.parse(fs.readFileSync(recordFile));
450 const age = () =>
451 fs.writeFileSync(
452 recordFile,
453 JSON.stringify({ ...readRecord(), idleSince: Date.now() - 61_000 }),
454 );
455 let editorPaths = [];
456 const sockets = path.join(directory, ".local/state/workspaces/vscode");
457 fs.mkdirSync(sockets, { recursive: true });
458 editor = net.createServer((socket) =>
459 socket.end(JSON.stringify({ pid: process.pid, paths: editorPaths }))
460 );
461 editor.listen(path.join(sockets, `${process.pid}.sock`));
462 await once(editor, "listening");
463 let unknownEditor = false;
464 const childMock = mock.method(
465 childProcess,
466 "execFileSync",
467 (command, args, options) => {
468 if (
469 command === "/bin/ps" && args.join(" ") === "-axo pid=,comm="
470 ) {
471 return "123 /Applications/Visual Studio Code.app/Contents/MacOS/Code";
472 }
473 if (
474 command === "/usr/local/bin/code"
475 ) {
476 return `1 100 123 code\n1 100 234 window [1]\n1 100 ${
477 unknownEditor ? process.pid + 1 : process.pid
478 } extension-host [1]`;
479 }
480 return run(command, args, options);
481 },
482 );
483
484 age();
485 await main(["gc"]);
486 assert.ok(
487 fs.existsSync(first),
488 "idle but unsettled chat owns the workspace",
489 );
490 assert.equal(readRecord().idleSince, null);
491 const originalThread = readRecord().threadId;
492 await client.dispatch({ type: "thread.settle", threadId: originalThread });
493 age();
494 await main(["gc"]);
495 assert.ok(
496 fs.existsSync(first),
497 "settled chat cannot release an unfinished setup",
498 );
499 assert.equal(readRecord().idleSince, null);
500 await main(["deps", "first"]);
501 assert.equal(readRecord().prepared, true, "dependency repair finishes setup");
502 await main(["open", "first", "--no-open"]);
503 assert.equal(
504 (await client.snapshot()).threads.find((thread) =>
505 thread.id === originalThread
506 ).settledOverride,
507 "active",
508 "opening a workspace renews the chat's claim",
509 );
510 await client.dispatch({ type: "thread.settle", threadId: originalThread });
511 await main(["gc"]);
512 assert.ok(fs.existsSync(first), "settlement keeps the prepared workspace");
513 assert.equal(readRecord().idleSince, null);
514 age();
515 await main(["gc"]);
516 assert.ok(fs.existsSync(first), "settlement never expires after the grace period");
517 assert.equal(readRecord().idleSince, null);
518 await client.dispatch({ type: "thread.archive", threadId: originalThread });
519 await main(["gc"]);
520 assert.ok(fs.existsSync(first), "archival begins the grace period");
521 assert.ok(readRecord().idleSince > Date.now() - 5000);
522
523 editorPaths = [path.join(first, "shared/local")];
524 age();
525 await main(["gc"]);
526 assert.ok(fs.existsSync(first), "editor subfolder keeps the workspace");
527 assert.equal(readRecord().idleSince, null);
528 editorPaths = [];
529
530 shell = childProcess.spawn("/bin/zsh", [
531 "-c",
532 "while read -r line; do :; done",
533 ], {
534 cwd: path.join(first, "shared/local"),
535 stdio: ["pipe", "ignore", "ignore"],
536 });
537 fs.mkdirSync(path.join(directory, ".local/state/workspaces/shells"), {
538 recursive: true,
539 });
540 fs.writeFileSync(
541 path.join(directory, ".local/state/workspaces/shells", String(shell.pid)),
542 path.join(first, "shared/local"),
543 );
544 age();
545 await main(["gc"]);
546 assert.ok(fs.existsSync(first), "live shell subfolder keeps the workspace");
547 assert.equal(readRecord().idleSince, null);
548 shell.stdin.end();
549 await once(shell, "exit");
550
551 unknownEditor = true;
552 age();
553 await assert.rejects(main(["gc"]));
554 assert.ok(fs.existsSync(first), "missing editor tracker prevents deletion");
555 assert.equal(readRecord().idleSince, null);
556 unknownEditor = false;
557
558 const runtimeContents = fs.readFileSync(runtime);
559 fs.rmSync(runtime);
560 age();
561 await assert.rejects(main(["gc"]));
562 assert.ok(fs.existsSync(first), "unavailable T3 prevents deletion");
563 assert.equal(readRecord().idleSince, null);
564 fs.writeFileSync(runtime, runtimeContents);
565
566 const anotherThread = randomUUID();
567 await client.dispatch({
568 type: "thread.create",
569 threadId: anotherThread,
570 projectId: firstProject.id,
571 title: "Shared workspace",
572 modelSelection: { instanceId: "codex", model: "gpt-6.1-sol" },
573 runtimeMode: "full-access",
574 interactionMode: "default",
575 branch: null,
576 worktreePath: null,
577 createdBy: "user",
578 creationSource: "web",
579 });
580 age();
581 await main(["gc"]);
582 assert.ok(
583 fs.existsSync(first),
584 "another unsettled chat in the workspace project keeps the folder",
585 );
586 await client.dispatch({ type: "thread.settle", threadId: anotherThread });
587 age();
588 await main(["gc"]);
589 assert.ok(fs.existsSync(first), "another settled chat still keeps the folder");
590 assert.equal(readRecord().idleSince, null);
591 await client.dispatch({ type: "thread.archive", threadId: anotherThread });
592 const archivedThread = (await client.snapshot()).archivedThreads.find(
593 (thread) => thread.id === originalThread,
594 );
595 assert.ok(archivedThread, "reference reads include archived chats");
596 const fetch = globalThis.fetch;
597 let snapshotReads = 0;
598 let busy = true;
599 const referenceMock = mock.method(globalThis, "fetch", async (...args) => {
600 const response = await fetch(...args);
601 if (!String(args[0]).endsWith("/api/orchestration/shell")) return response;
602 snapshotReads++;
603 const snapshot = await response.json();
604 const thread = { ...archivedThread };
605 if (busy) thread.activeRunId = randomUUID();
606 else if (snapshotReads === 2) thread.archivedAt = null;
607 snapshot.threads.push(thread);
608 return new Response(JSON.stringify(snapshot), { status: response.status });
609 });
610 age();
611 await main(["gc"]);
612 assert.ok(fs.existsSync(first), "running work keeps an archived workspace");
613 assert.equal(readRecord().idleSince, null);
614 busy = false;
615 snapshotReads = 0;
616 age();
617 await main(["gc"]);
618 assert.equal(snapshotReads, 2, "cleanup rechecks references before removal");
619 assert.ok(
620 fs.existsSync(first),
621 "a settled chat returning at the fresh check keeps the folder",
622 );
623 assert.equal(readRecord().idleSince, null);
624 referenceMock.mock.restore();
625 archiveHandler = () => { throw new Error("PR read unavailable"); };
626 age();
627 await assert.rejects(main(["gc"]), /PR read unavailable/);
628 assert.ok(fs.existsSync(first), "merge read failure stops eligible cleanup");
629 assert.equal(readRecord().idleSince, null);
630 archiveHandler = () => ({ archivedThreadIds: "unknown" });
631 age();
632 await assert.rejects(main(["gc"]), /unknown archive result/);
633 assert.ok(fs.existsSync(first), "unknown merge response stops cleanup");
634 assert.equal(readRecord().idleSince, null);
635 archiveHandler = () => ({ archivedThreadIds: [] });
636 age();
637 const requestsBeforeDryRun = archiveRequests.length;
638 await main(["gc", "--dry-run"]);
639 assert.equal(archiveRequests.length, requestsBeforeDryRun, "dry run never requests archival");
640 assert.ok(fs.existsSync(first), "dry run never removes a workspace");
641 fs.writeFileSync(
642 path.join(first, "saved.txt"),
643 "survives workspace cleanup\n",
644 );
645 await main(["gc"]);
646 assert.equal(fs.existsSync(first), false);
647 const savedChange = run("jj", [
648 "--ignore-working-copy",
649 "log",
650 "-r",
651 'files("saved.txt")',
652 "--no-graph",
653 "-T",
654 "change_id",
655 ], { cwd: source, encoding: "utf8" }).trim();
656 assert.equal(
657 run("jj", ["--ignore-working-copy", "file", "show", "saved.txt", "-r", savedChange], {
658 cwd: source,
659 encoding: "utf8",
660 }),
661 "survives workspace cleanup\n",
662 "JJ retains the snapshotted files",
663 );
664 assert.ok(fs.existsSync(second), "unsettled sibling workspace survives");
665 await main(["new", "first", "-r", "@", "--no-open"]);
666 const freshRecord = readRecord();
667 assert.equal((await client.snapshot()).projects.filter((project) =>
668 project.workspaceRoot === first
669 ).length, 1, "a reused folder reuses its registered project");
670 assert.notEqual(
671 freshRecord.threadId,
672 originalThread,
673 "reusing a collected workspace name creates a fresh chat",
674 );
675 await client.dispatch({
676 type: "thread.settle",
677 threadId: freshRecord.threadId,
678 });
679 age();
680 await main(["gc"]);
681 assert.ok(fs.existsSync(first), "a settled replacement chat keeps its workspace");
682 assert.equal(readRecord().idleSince, null);
683 const settledAt = (await client.snapshot()).threads.find(
684 (thread) => thread.id === freshRecord.threadId,
685 ).settledAt;
686 const captureArgs = ["first", "--thread-id", freshRecord.threadId, "--settled-at", settledAt];
687 const completion = async (timestamp = settledAt) => {
688 const output = [];
689 const log = mock.method(console, "log", (value) => output.push(value));
690 try {
691 await main(["completion", "first", "--thread-id", freshRecord.threadId,
692 "--settled-at", timestamp, "--json"]);
693 assert.equal(output.length, 1);
694 return JSON.parse(output[0]);
695 } finally {
696 log.mock.restore();
697 }
698 };
699 assert.deepEqual(await completion(), { abandoned: false }, "missing capture cannot prove abandonment");
700 fs.writeFileSync(path.join(first, "settled-work.txt"), "work captured at settlement\n");
701 await main(["settle", ...captureArgs]);
702 const captureFile = path.join(directory, ".local/state/workspaces/settlements/first", `${freshRecord.threadId}.json`);
703 const capturedContents = fs.readFileSync(captureFile, "utf8");
704 const captured = JSON.parse(capturedContents);
705 assert.equal(captured.changeId, run("jj", ["log", "-r", "@", "--no-graph", "-T", "change_id"], {
706 cwd: first, encoding: "utf8",
707 }).trim(), "capture uses the working change itself");
708 assert.deepEqual(await completion(), { abandoned: false }, "visible captured change stays alive");
709 run("jj", ["rebase", "-r", "@", "-d", latestMain], { cwd: first, stdio: "pipe" });
710 assert.deepEqual(await completion(), { abandoned: false }, "rebased change keeps its identity and workspace");
711 run("jj", ["new", "@"], { cwd: first, stdio: "pipe" });
712 fs.writeFileSync(path.join(first, "later-work.txt"), "keep later nonempty ancestor\n");
713 run("jj", ["new", "@"], { cwd: first, stdio: "pipe" });
714 const laterChange = run("jj", ["log", "-r", "@-", "--no-graph", "-T", "change_id"], {
715 cwd: first, encoding: "utf8",
716 }).trim();
717 run("jj", ["abandon", captured.changeId], { cwd: first, stdio: "pipe" });
718 assert.deepEqual(await completion(), { abandoned: false },
719 "later nonempty work behind an empty tip prevents abandonment cleanup");
720 assert.equal(fs.readFileSync(path.join(first, "later-work.txt"), "utf8"), "keep later nonempty ancestor\n");
721 run("jj", ["abandon", laterChange], { cwd: first, stdio: "pipe" });
722 assert.deepEqual(await completion(), { abandoned: true }, "real JJ abandonment releases captured work");
723 await main(["settle", ...captureArgs]);
724 assert.equal(fs.readFileSync(captureFile, "utf8"), capturedContents,
725 "repeated settlement does not recapture a moved working change");
726 const newWork = path.join(first, "new-work.txt");
727 fs.writeFileSync(newWork, "keep this new work\n");
728 assert.deepEqual(await completion(), { abandoned: false }, "new nonempty work prevents abandoned cleanup");
729 fs.rmSync(newWork);
730 assert.deepEqual(await completion(), { abandoned: true });
731 fs.renameSync(path.join(first, ".jj"), path.join(first, ".jj-hidden"));
732 try {
733 await assert.rejects(completion(), /ENOENT/);
734 } finally {
735 fs.renameSync(path.join(first, ".jj-hidden"), path.join(first, ".jj"));
736 }
737 const laterSettlement = new Date(Date.parse(settledAt) + 1000).toISOString();
738 assert.deepEqual(await completion(laterSettlement), { abandoned: false }, "another settlement cannot reuse the capture");
739 await main(["unsettle", "first", "--thread-id", freshRecord.threadId]);
740 assert.equal(fs.existsSync(captureFile), false, "resuming clears the thread capture");
741 assert.deepEqual(await completion(), { abandoned: false });
742 await main(["settle", ...captureArgs]);
743 archiveHandler = async ({ workspacePath }) => {
744 if (workspacePath !== first) return { archivedThreadIds: [] };
745 await client.dispatch({ type: "thread.unsettle", threadId: freshRecord.threadId, reason: "user" });
746 return { archivedThreadIds: [freshRecord.threadId] };
747 };
748 age();
749 await main(["gc"]);
750 assert.ok(fs.existsSync(first), "a resumed chat keeps its workspace after the merge check");
751 assert.equal(readRecord().idleSince, null);
752 await client.dispatch({ type: "thread.settle", threadId: freshRecord.threadId });
753 archiveHandler = async ({ workspacePath }) => {
754 if (workspacePath !== first) return { archivedThreadIds: [] };
755 await client.dispatch({ type: "thread.archive", threadId: freshRecord.threadId });
756 return { archivedThreadIds: [freshRecord.threadId] };
757 };
758 await main(["gc"]);
759 assert.ok(fs.existsSync(first), "verified merge archival starts the deletion grace period");
760 assert.ok(readRecord().idleSince > Date.now() - 5000);
761 archiveHandler = () => ({ archivedThreadIds: [] });
762 age();
763 await main(["gc"]);
764 assert.equal(fs.existsSync(first), false, "merged archived workspace is collected after grace");
765 assert.equal(fs.existsSync(path.dirname(captureFile)), false, "collection removes settlement captures");
766 assert.ok(archiveRequests.some(({ workspacePath }) => workspacePath === first));
767 assert.ok(archiveRequests.every(({ workspacePath }) =>
768 path.dirname(workspacePath) === path.join(directory, "workspaces")
769 ), "only registered managed folders are checked");
770 const secondRecord = JSON.parse(
771 fs.readFileSync(
772 path.join(directory, ".local/state/workspaces/workspaces/second.json"),
773 ),
774 );
775 await client.dispatch({
776 type: "thread.delete",
777 threadId: secondRecord.threadId,
778 });
779 fs.writeFileSync(
780 path.join(directory, ".local/state/workspaces/workspaces/second.json"),
781 JSON.stringify({ ...secondRecord, idleSince: Date.now() - 61_000 }),
782 );
783 await main(["gc"]);
784 assert.equal(
785 fs.existsSync(second),
786 false,
787 "deleted chat releases its workspace",
788 );
789 childMock.mock.restore();
790 } finally {
791 mock.restoreAll();
792 if (shell?.exitCode === null) shell.kill();
793 if (editor) await new Promise((resolve) => editor.close(resolve));
794 if (server.exitCode === null) {
795 server.kill("SIGKILL");
796 await once(server, "exit");
797 }
798 fs.closeSync(serverLog);
799 fs.rmSync(directory, { recursive: true, force: true, maxRetries: 3 });
800 process.env.HOME = originalHome;
801 if (originalT3 === undefined) delete process.env.T3CODE_HOME;
802 else process.env.T3CODE_HOME = originalT3;
803 process.env.PATH = originalPath;
804 }
805});
806
807test("workspace lock rejects overlap and releases after process exit", {
808 skip: !native,
809}, async () => {
810 const directory = fs.mkdtempSync("/tmp/workspaces-lock-");
811 const lock = path.join(directory, "lock");
812 const holder = childProcess.spawn(native, [
813 "lock",
814 lock,
815 process.execPath,
816 "-e",
817 "process.stdout.write('ready'); setInterval(() => {}, 1000)",
818 ]);
819 try {
820 await once(holder.stdout, "data");
821 assert.throws(
822 () => childProcess.execFileSync(native, ["lock", lock, "/usr/bin/true"], {
823 stdio: "pipe",
824 }),
825 (error) => /Another workspace command/.test(error.stderr.toString()),
826 );
827 holder.kill();
828 await once(holder, "exit");
829 childProcess.execFileSync(native, ["lock", lock, "/usr/bin/true"]);
830 } finally {
831 if (holder.exitCode === null && holder.signalCode === null) holder.kill();
832 fs.rmSync(directory, { recursive: true, force: true });
833 }
834});
users/clover/work/home.nix+1-50
......@@ -1,53 +1,5 @@
1{ config, lib, pkgs, ... }:
2let
3 workspaces = pkgs.callPackage ../packages/workspaces { };
4 hookPython = pkgs.python3.withPackages (ps: [ ps.tomlkit ]);
5in
1{ pkgs, ... }:
62{
7 home.file.".config/raycast/scripts/new-workspace.sh" = {
8 executable = true;
9 text = ''
10 #!/bin/bash
11 # @raycast.schemaVersion 1
12 # @raycast.title New Workspace
13 # @raycast.mode silent
14 # @raycast.packageName T3 Code
15 # @raycast.icon 💬
16
17 log="$(mktemp -t workspace)"
18 if ${workspaces}/bin/ws new --background > "$log" 2>&1; then
19 rm -f "$log"
20 else
21 mkdir -p "$HOME/Library/Logs"
22 mv "$log" "$HOME/Library/Logs/workspace-creation.log"
23 error="$(sed -n -e 's/^Error: //p' -e 's/^Internal error: //p' "$HOME/Library/Logs/workspace-creation.log" | head -n 1)"
24 printf '%s. Run ws new for details.\n' "''${error:-Workspace creation stopped}"
25 exit 1
26 fi
27 '';
28 };
29 home.file.".vscode/extensions/clover.workspace-references".source =
30 config.lib.file.mkOutOfStoreSymlink "${config.home.homeDirectory}/config/users/clover/packages/workspaces/extension";
31 programs.zsh.initContent = builtins.readFile ../packages/workspaces/shell.zsh;
32 home.activation.workspaceReadinessHooks = lib.hm.dag.entryAfter [ "codexConfig" ] ''
33 run ${hookPython}/bin/python3 ${../packages/workspaces/configure-hooks.py} \
34 ${lib.escapeShellArg config.home.homeDirectory} \
35 ${lib.escapeShellArg "${config.home.profileDirectory}/bin/ws ready-hook"} \
36 ${lib.escapeShellArg "${config.home.homeDirectory}/.local/bin/codex"}
37 '';
38 launchd.agents.workspace-cleanup = {
39 enable = true;
40 config = {
41 ProgramArguments = [
42 "${workspaces}/bin/ws"
43 "gc"
44 ];
45 StartInterval = 30;
46 RunAtLoad = true;
47 StandardErrorPath = "${config.home.homeDirectory}/Library/Logs/workspaces.log";
48 StandardOutPath = "${config.home.homeDirectory}/Library/Logs/workspaces.log";
49 };
50 };
513 programs = {
524 zsh.profileExtra = ''
535 _bun() {
......@@ -57,7 +9,6 @@ in
579 '';
5810 };
5911 home.packages = with pkgs; [
60 workspaces
6112 (bun.overrideAttrs (_: rec {
6213 version = "1.3.5";
6314 src = fetchurl {
users/clover/zsh/init.zsh+44-5
......@@ -2,15 +2,45 @@
22# file watchers exhaust during their first build.
33ulimit -n 65536 2>/dev/null
44
5function _update_prompt_theme() {
6 if [[ "$(defaults read -g AppleInterfaceStyle 2>/dev/null)" == "Dark" ]]; then
7 PS1="%{$(tput setaf 207)%}%m%{$(tput setaf 15)%}:%{$(tput setaf 87)%}%~ %{$(tput sgr0)%}$ "
5ZSH_AUTOSUGGEST_MANUAL_REBIND=1
6
7function _set_prompt_theme() {
8 if [[ "$1" == "Dark" ]]; then
9 PS1='%F{207}%m%F{15}:%F{87}%~ %f$ '
10 else
11 PS1='%F{168}%m%F{238}:%F{33}%~ %f$ '
12 fi
13}
14
15function _prompt_theme_ready() {
16 local theme previous_prompt="$PS1"
17 if IFS= read -r theme <&$1; then
18 _set_prompt_theme "$theme"
19 fi
20
21 zle -F "$1"
22 exec {_prompt_theme_fd}<&-
23 unset _prompt_theme_fd
24
25 if [[ "$previous_prompt" == *"$PS1"* ]]; then
26 PS1="$previous_prompt"
827 else
9 PS1="%{$(tput setaf 168)%}%m%{$(tput setaf 238)%}:%{$(tput setaf 33)%}%~ %{$(tput sgr0)%}$ "
28 zle reset-prompt
1029 fi
1130}
31
32function _update_prompt_theme() {
33 [[ -z ${_prompt_theme_fd-} ]] || return 0
34 (( SECONDS > _prompt_theme_checked_at )) || return 0
35
36 _prompt_theme_checked_at=$SECONDS
37 exec {_prompt_theme_fd}< <(defaults read -g AppleInterfaceStyle 2>/dev/null || print -r -- Light)
38 zle -F "$_prompt_theme_fd" _prompt_theme_ready
39}
40
41_set_prompt_theme "$(defaults read -g AppleInterfaceStyle 2>/dev/null)"
42_prompt_theme_checked_at=$SECONDS
1243precmd_functions+=(_update_prompt_theme)
13_update_prompt_theme
1444
1545function python() {
1646 dirname=$(dirname $1 2>/dev/null)
......@@ -232,6 +262,15 @@ function jj() {
232262 fi
233263}
234264
265function dp() {
266 local -a diff_command=(diff)
267 if [[ "$OSTYPE" == darwin* && -t 0 && -t 1 && -z "${SSH_CONNECTION-}${SSH_CLIENT-}${SSH_TTY-}" ]]; then
268 diff_command=(diffedit --tool knife)
269 fi
270
271 _runJj "$diff_command[@]" --from 'fork_point(trunk() | @)' --to @ "$@"
272}
273
235274function bup() {
236275 if [[ -z "$(command jj log -r @ -T description --no-graph 2>/dev/null)" ]]; then
237276 command jj desc -m 'chore: follow-up changes'