Harden the app's loop commit gate, agent launch and file writes, and tighten workflow permissions

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-05 11:38:57 -08:00
1 parent 30fd1134ea
commit b17213322c
10 files changed
+240 -42

No files matched your search

+8
View File
@@ -5,6 +5,9 @@ on:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
app:
name: app (${{ matrix.os }})
@@ -99,3 +102,8 @@ jobs:
node-version: 20
- run: npm install
- run: npm test
- name: Metrics tests
working-directory: plan2code-metrics
run: |
npm install
npm test
+13 -1
View File
@@ -14,8 +14,16 @@ on:
push:
tags: ['v*']
# Read-only by default: the build jobs run dependency install scripts and build scripts, so
# only the publish job holds a write token.
permissions:
contents: write
contents: read
# A release published after its tag push starts a second run for the same tag: queue it behind
# the first so two builds never upload over each other.
concurrency:
group: release-app-${{ github.event.release.tag_name || github.ref_name }}
cancel-in-progress: false
jobs:
build:
@@ -34,6 +42,8 @@ jobs:
shell: bash
steps:
- uses: actions/checkout@v4.2.2
with:
persist-credentials: false
- uses: actions/setup-node@v4.4.0
with:
node-version: 22
@@ -83,6 +93,8 @@ jobs:
name: attach to the release
needs: build
runs-on: ubuntu-latest
permissions:
contents: write
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ github.event.release.tag_name || github.ref_name }}
+1
View File
@@ -10,6 +10,7 @@
//! REPORT <json> write <json> as `loopOutcome` into the session's state.json
//! (PLAN2CODE_CONSOLE_HOME and PLAN2CODE_CONSOLE_SID name it), say
//! `REPORT written` (`REPORT unavailable` when either is missing)
//! ENV <name> print the variable as `ENV <name>=<value>`
//! HANG say `HANGING`, then go silent for good (no more lines read)
//! <other> echoed back as `echo: <line>`
//!
+24 -2
View File
@@ -631,8 +631,30 @@ pub fn launch_spec(
spec.args,
&std::env::var("PATH").unwrap_or_default(),
);
spec.program = program;
spec.args = args;
if program == "cmd" && args.first().map(String::as_str) == Some("/c") {
// A shim wrapped for cmd: quote the line, hand it over in a variable
// and keep cmd from trying the project folder before PATH, exactly as
// a custom .cmd agent does (a same-named file in a cloned repo must not
// run in the agent's place). Accepted trade-off: the variable reaches
// everything the agent starts, so a `cmd` it runs as a tool no longer
// finds `gradlew` or `setup.bat` in the project without `.\`; custom
// .cmd agents already behave this way.
let line: Vec<String> = args[1..].iter().map(|arg| quote_for_cmd(arg)).collect();
spec.env.push((CMD_LINE_ENV.to_string(), line.join(" ")));
spec.env.push((
"NoDefaultCurrentDirectoryInExePath".to_string(),
"1".to_string(),
));
spec.args = vec![
"/d".to_string(),
"/c".to_string(),
format!("%{CMD_LINE_ENV}%"),
];
spec.program = program;
} else {
spec.program = program;
spec.args = args;
}
}
spec
}
+7 -2
View File
@@ -366,8 +366,9 @@ pub fn commit(
/// Take what a failed commit left staged out of the index, so a commit the
/// person makes by hand does not carry a mark the loop took back.
pub fn unstage(project: &Path) {
let _ = loop_tools::git_unstage_all(project);
pub fn unstage(project: &Path) -> Option<String> {
let unstaged = loop_tools::git_unstage_all(project);
(!unstaged.ok).then(|| first_line(&unstaged.output))
}
/// The phases the spec shows done (`done`) that the commit log does not hold:
@@ -793,6 +794,10 @@ mod tests {
#[test]
fn commit_stages_the_marked_files_but_leaves_an_ignored_spec_folder_alone() {
if !git_ready() || !node_ready() {
assert!(
std::env::var_os("CI").is_none(),
"git or node is not on PATH"
);
return;
}
let repo = init_repo("commit-ignored");
+30 -9
View File
@@ -2107,10 +2107,19 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
Ok(()) => {}
Err(loop_commit::StageError::Add(failure)) => {
keep_output(ctx, &failure.output);
loop_commit::unstage(&snap.project);
let left_staged = loop_commit::unstage(&snap.project);
let cause = StopCause::Commit;
let detail = format!("git add failed: {}", failure.first_line);
let line = stop_line(&cause, n, &detail, false);
let detail = if failure.first_line == loop_tools::STAGED_TOO_LONG {
failure.first_line.clone()
} else {
format!("git add failed: {}", failure.first_line)
};
let mut line = stop_line(&cause, n, &detail, false);
if let Some(why) = left_staged {
line = format!(
"{line}. The files are still staged ({why}): run git reset before committing by hand"
);
}
return stop(cause, line);
}
Err(loop_commit::StageError::Problem(problem)) => {
@@ -2145,11 +2154,18 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
}
Err(failure) => {
keep_output(ctx, &failure.message);
if snap.setup.commit {
loop_commit::unstage(&snap.project);
}
let left_staged = if snap.setup.commit {
loop_commit::unstage(&snap.project)
} else {
None
};
let staged_note = left_staged
.map(|why| {
format!("; the files are still staged ({why}): run git reset before committing by hand")
})
.unwrap_or_default();
return refused(format!(
"the phase could not be marked done ({})",
"the phase could not be marked done ({}){staged_note}",
one_line(&failure.message)
));
}
@@ -2270,13 +2286,18 @@ fn commit_failed(
keep_output(ctx, &failure.output);
let (cause, line) = match loop_commit::undo(prepared, marked) {
Ok(()) => {
loop_commit::unstage(&snap.project);
let left_staged = loop_commit::unstage(&snap.project);
let cause = StopCause::Commit;
let detail = match failure.stage {
loop_commit::Stage::Add => format!("git add failed: {}", failure.first_line),
loop_commit::Stage::Commit => failure.first_line.clone(),
};
let line = stop_line(&cause, n, &detail, false);
let mut line = stop_line(&cause, n, &detail, false);
if let Some(why) = left_staged {
line = format!(
"{line}. The files are still staged ({why}): run git reset before committing by hand"
);
}
(cause, line)
}
Err(why) => {
+149 -20
View File
@@ -6,6 +6,7 @@
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
@@ -23,6 +24,13 @@ pub struct ToolRun {
/// Output kept per call: the tail, which is where a failure says why.
const OUTPUT_LIMIT: usize = 200 * 1024;
/// What a stop says when too many files are staged to check.
pub const STAGED_TOO_LONG: &str =
"too many changed files to check: add generated folders to .gitignore, then Resume";
/// Output kept for the staged-file list the commit gate checks (far above any real list).
const STAGED_LIST_LIMIT: usize = 64 * 1024 * 1024;
/// The limit for node and git calls.
pub const QUICK_LIMIT: Duration = Duration::from_secs(60);
/// The limit for the person's quick check.
@@ -42,6 +50,8 @@ fn append_tail(buf: &mut Vec<u8>, bytes: &[u8], limit: usize) {
fn pump<R: Read + Send + 'static>(
mut source: R,
sink: Arc<Mutex<Vec<u8>>>,
keep: Keep,
cut: Arc<AtomicBool>,
) -> thread::JoinHandle<()> {
thread::spawn(move || {
let mut chunk = [0u8; 8192];
@@ -50,7 +60,16 @@ fn pump<R: Read + Send + 'static>(
Ok(0) | Err(_) => break,
Ok(n) => {
if let Ok(mut buf) = sink.lock() {
append_tail(&mut buf, &chunk[..n], OUTPUT_LIMIT);
match keep {
Keep::Tail(cap) => append_tail(&mut buf, &chunk[..n], cap),
Keep::Head(cap) => {
let room = cap.saturating_sub(buf.len()).min(n);
buf.extend_from_slice(&chunk[..room]);
if room < n {
cut.store(true, Ordering::Relaxed);
}
}
}
}
}
}
@@ -67,17 +86,45 @@ fn run_limited(cmd: Command, stdin: Option<&str>, limit: Duration) -> ToolRun {
/// `run_limited`, with stderr dropped when `keep_stderr` is false: a list read
/// from stdout must not be mixed with a warning git printed beside it.
fn run_limited_with(
mut cmd: Command,
cmd: Command,
stdin: Option<&str>,
limit: Duration,
keep_stderr: bool,
) -> ToolRun {
run_capped(cmd, stdin, limit, keep_stderr, Keep::Tail(OUTPUT_LIMIT)).0
}
/// Which part of a long output a call keeps.
#[derive(Clone, Copy)]
enum Keep {
/// The last `n` bytes, where a failure says why.
Tail(usize),
/// The first `n` bytes; anything after is read and dropped, and the call
/// reports it was cut. For a list a safety check must read whole.
Head(usize),
}
/// `run_limited_with` with the part kept chosen, and whether output was dropped.
fn run_capped(
mut cmd: Command,
stdin: Option<&str>,
limit: Duration,
keep_stderr: bool,
keep: Keep,
) -> (ToolRun, bool) {
let cut = Arc::new(AtomicBool::new(false));
cmd.env("PATH", crate::node_check::resolved_path());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
}
#[cfg(unix)]
{
// Its own process group, so a timeout can end every descendant at once.
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
cmd.stdin(if stdin.is_some() {
Stdio::piped()
} else {
@@ -92,17 +139,26 @@ fn run_limited_with(
let mut child = match cmd.spawn() {
Ok(child) => child,
Err(e) => {
return ToolRun {
ok: false,
code: None,
output: format!("could not start: {e}"),
}
return (
ToolRun {
ok: false,
code: None,
output: format!("could not start: {e}"),
},
false,
);
}
};
let sink = Arc::new(Mutex::new(Vec::new()));
let readers = [
child.stdout.take().map(|s| pump(s, Arc::clone(&sink))),
child.stderr.take().map(|s| pump(s, Arc::clone(&sink))),
child
.stdout
.take()
.map(|s| pump(s, Arc::clone(&sink), keep, Arc::clone(&cut))),
child
.stderr
.take()
.map(|s| pump(s, Arc::clone(&sink), keep, Arc::clone(&cut))),
];
if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) {
// A child that exits before reading closes the pipe: not an error here.
@@ -148,11 +204,14 @@ fn run_limited_with(
}
output.push_str(&format!("(stopped after {})", describe_limit(limit)));
}
ToolRun {
ok: status.is_some_and(|s| s.success()),
code: status.and_then(|s| s.code()),
output,
}
(
ToolRun {
ok: status.is_some_and(|s| s.success()),
code: status.and_then(|s| s.code()),
output,
},
cut.load(Ordering::Relaxed),
)
}
/// "1 minute", "15 minutes", "2 seconds".
@@ -180,11 +239,14 @@ fn kill_tree(pid: u32) {
}
#[cfg(not(windows))]
{
let _ = Command::new("pkill")
.args(["-KILL", "-P", &pid.to_string()])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
// The child leads its own process group (see run_limited): a negative
// pid ends the whole group, grandchildren included.
if let Ok(pgid) = i32::try_from(pid) {
// SAFETY: kill(2) takes plain integers and touches no memory.
unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
}
}
}
@@ -347,15 +409,26 @@ pub fn git_add_paths(project: &Path, paths: &[&Path]) -> ToolRun {
/// The names of the staged files, as `git diff --cached --name-only -z` prints
/// them: NUL-separated, so no path is quoted.
pub fn git_staged(project: &Path) -> Result<Vec<String>, String> {
let run = run_limited_with(
git_staged_capped(project, STAGED_LIST_LIMIT)
}
/// `git_staged` with the size the list may reach. The secret and size gate
/// reads every staged name, so a list over the cap fails closed rather than
/// being checked in part.
fn git_staged_capped(project: &Path, cap: usize) -> Result<Vec<String>, String> {
let (run, cut) = run_capped(
git(project, &["diff", "--cached", "--name-only", "-z"]),
None,
QUICK_LIMIT,
false,
Keep::Head(cap),
);
if !run.ok {
return Err(run.output.trim().to_string());
}
if cut {
return Err(STAGED_TOO_LONG.to_string());
}
Ok(split_nul(&run.output))
}
@@ -558,6 +631,62 @@ fn parse_json_object(run: &ToolRun) -> Result<serde_json::Value, String> {
mod tests {
use super::*;
#[test]
fn a_capped_run_keeps_the_part_asked_for_and_says_when_output_was_cut() {
if Command::new("node").arg("--version").output().is_err() {
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
return;
}
fn run(keep: Keep, text: &str) -> (ToolRun, bool) {
let mut cmd = Command::new("node");
cmd.args(["-e", &format!("process.stdout.write('{text}')")]);
run_capped(cmd, None, QUICK_LIMIT, false, keep)
}
let (tail, tail_cut) = run(Keep::Tail(4), "aaaabbbb");
assert!(tail.ok);
assert_eq!(tail.output, "bbbb");
assert!(!tail_cut, "a tail keeper never reports a cut");
let (head, head_cut) = run(Keep::Head(4), "aaaabbbb");
assert_eq!(head.output, "aaaa");
assert!(head_cut);
let (whole, whole_cut) = run(Keep::Head(8), "aaaabbbb");
assert_eq!(whole.output, "aaaabbbb");
assert!(!whole_cut);
}
#[test]
fn a_staged_list_over_the_cap_is_refused_not_checked_in_part() {
if Command::new("git").arg("--version").output().is_err() {
assert!(std::env::var_os("CI").is_none(), "git is not on PATH");
return;
}
let repo =
std::env::temp_dir().join(format!("plan2code-staged-cap-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&repo);
std::fs::create_dir_all(&repo).unwrap();
let git_in = |args: &[&str]| {
let status = Command::new("git")
.args(args)
.current_dir(&repo)
.status()
.unwrap();
assert!(status.success(), "git {args:?}");
};
git_in(&["init", "-q"]);
for name in [".env", "a.txt", "b.txt"] {
std::fs::write(repo.join(name), "x").unwrap();
}
git_in(&["add", "-A"]);
// A cap below the list's size: refused, never a list missing its first names.
assert_eq!(
git_staged_capped(&repo, 8),
Err(STAGED_TOO_LONG.to_string())
);
let all = git_staged_capped(&repo, 1024).unwrap();
assert_eq!(all, [".env", "a.txt", "b.txt"]);
let _ = std::fs::remove_dir_all(&repo);
}
#[test]
fn the_commit_message_is_read_from_the_scripts_output_without_a_shell() {
let ok = r#"{"ok":true,"subject":"Add it","message":"Add it\n\nAI Assisted"}"#;
+6 -6
View File
@@ -798,7 +798,7 @@ async fn update_skills(
/// The OS folder picker, shown when no folder is known; a choice becomes the
/// launcher's remembered folder.
#[tauri::command]
#[tauri::command(async)]
fn pick_project_folder(
app: tauri::AppHandle,
state: State<'_, AppState>,
@@ -847,7 +847,7 @@ fn teardown_project(state: &AppState) -> Result<(), String> {
/// fresh for it rather than reusing anything from the one just left. Picking
/// nothing (canceled) leaves the current project untouched. One project per
/// window stays; this replaces it, it does not add a second.
#[tauri::command]
#[tauri::command(async)]
fn change_project(
app: tauri::AppHandle,
state: State<'_, AppState>,
@@ -876,7 +876,7 @@ fn change_project(
/// is `console_setup_start` below: the agent-less `setup` page, which is no
/// dashboard and has no agent to announce it, so the app opens it itself.
/// Nothing to show yet is an error the page words for the person.
#[tauri::command]
#[tauri::command(async)]
fn console_start(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
console_start_impl(&state)
}
@@ -894,7 +894,7 @@ fn console_start_impl(state: &AppState) -> Result<serde_json::Value, String> {
/// The bar's poll: none (never started or stopped on purpose), running, or
/// dead (started but not answering).
#[tauri::command]
#[tauri::command(async)]
fn console_status(state: State<'_, AppState>) -> serde_json::Value {
let Ok(guard) = state.console.lock() else {
return serde_json::json!({ "state": "none", "url": null });
@@ -927,7 +927,7 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
/// on its own), and the URL comes back for the page to frame. When
/// `console.mjs` cannot be found the error names it, and the page shows its
/// plain "skills are missing" checklist row.
#[tauri::command]
#[tauri::command(async)]
fn console_setup_start(
app: tauri::AppHandle,
state: State<'_, AppState>,
@@ -1254,7 +1254,7 @@ fn loop_finalize(state: State<'_, AppState>) -> Result<(), String> {
/// fresh dashboard console in its place. Needs no agent: a dashboard session
/// is only `console.mjs open --workflow dashboard`, which the supervisor runs
/// itself.
#[tauri::command]
#[tauri::command(async)]
fn loop_dashboard(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
let app = state.app.get().cloned().ok_or("no window yet")?;
let origin = window_origin(&app);
+1 -1
View File
@@ -155,7 +155,7 @@ pub fn remember_folder(dir: &Path) -> Result<ProjectDir, String> {
std::fs::create_dir_all(parent).map_err(err)?;
}
let json = serde_json::to_string_pretty(&serde_json::Value::Object(state)).map_err(err)?;
std::fs::write(file, json).map_err(err)?;
crate::loop_driver::write_atomic(&file, &json)?;
Ok(ProjectDir {
dir: dir.to_path_buf(),
source: ProjectSource::Picked,
+1 -1
View File
@@ -153,7 +153,7 @@ fn write(file: &Path, settings: serde_json::Map<String, serde_json::Value>) -> R
}
let json = serde_json::to_string_pretty(&serde_json::Value::Object(settings))
.map_err(|e| e.to_string())?;
std::fs::write(file, json).map_err(|e| e.to_string())
crate::loop_driver::write_atomic(file, &json)
}
#[cfg(test)]