Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Ensure shell scripts and source files keep LF line endings on Windows checkouts
*.sh text eol=lf
*.bash text eol=lf
*.js text eol=lf
*.mjs text eol=lf
*.cjs text eol=lf
*.ts text eol=lf
*.py text eol=lf
*.rs text eol=lf
*.toml text eol=lf
*.json text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.md text eol=lf
Makefile* text eol=lf
Dockerfile* text eol=lf
16 changes: 16 additions & 0 deletions crates/leio-harness/src/acp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,22 @@ pub fn serve(spec: AgentSessionSpec) -> Result<AgentSessionResult> {
"LOGNAME",
"SHELL",
"TMPDIR",
"TEMP",
"TMP",
"SystemRoot",
"SYSTEMROOT",
"WINDIR",
"COMSPEC",
"PATHEXT",
"USERPROFILE",
"APPDATA",
"LOCALAPPDATA",
"PROGRAMDATA",
"PROGRAMFILES",
"PROGRAMFILES(X86)",
"HOMEDRIVE",
"HOMEPATH",
"USERNAME",
"LANG",
"LC_ALL",
"TERM",
Expand Down
1 change: 1 addition & 0 deletions crates/leio-harness/src/agents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ const MIN_CONTEXT_LENGTH: u64 = 100_000;
/// `~/.config/leio-harness/openrouter-models.json` (HOME-dependent).
pub fn models_cache_path() -> Option<std::path::PathBuf> {
std::env::var("HOME")
.or_else(|_| std::env::var("USERPROFILE"))
.ok()
.filter(|home| !home.trim().is_empty())
.map(|home| Path::new(&home).join(".config/leio-harness/openrouter-models.json"))
Expand Down
4 changes: 2 additions & 2 deletions crates/leio-harness/src/delivery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ fn safe_path(path: &Path) -> Result<()> {
fn root(target: &Path) -> Result<PathBuf> {
boundary_path(target)?;
fs::create_dir_all(target)?;
let target = target.canonicalize()?;
let target = crate::process::clean_canonicalize(target)?;
for name in ["releases", "state.jsonld", ".lock"] {
safe_path(&target.join(name))?;
}
Expand Down Expand Up @@ -292,7 +292,7 @@ fn authorization(target: &Path, action: &str, id: &str, current: &State) -> Resu
/// Stage a directory containing actual build output. Does not claim to run a build.
pub fn prepare(source: &Path, target: &Path) -> Result<Value> {
boundary_path(source)?;
let source = source.canonicalize()?;
let source = crate::process::clean_canonicalize(source)?;
let target = root(target)?;
ensure!(
!target.starts_with(&source) && !source.starts_with(&target),
Expand Down
1 change: 1 addition & 0 deletions crates/leio-harness/src/embed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ fn default_config_values() -> std::collections::HashMap<String, String> {
.map(std::path::PathBuf::from)
.or_else(|| {
std::env::var("HOME")
.or_else(|_| std::env::var("USERPROFILE"))
.ok()
.map(|home| std::path::Path::new(&home).join(".config/leio-harness/env"))
});
Expand Down
16 changes: 8 additions & 8 deletions crates/leio-harness/src/merge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ pub(crate) fn validate_merge_target(
target_ref: &str,
) -> Result<std::path::PathBuf> {
let repo_root = canonical_repo_root(repo_root)?;
let worktree = std::fs::canonicalize(worktree)
let worktree = crate::process::clean_canonicalize(worktree)
.with_context(|| format!("canonicalize {}", worktree.display()))?;
assert_linked(&repo_root, &worktree)?;
validate_ref(source_branch)?;
Expand Down Expand Up @@ -174,10 +174,10 @@ fn combined_output(output: &Output) -> String {
}

fn canonical_repo_root(path: &Path) -> Result<std::path::PathBuf> {
let expected =
std::fs::canonicalize(path).with_context(|| format!("canonicalize {}", path.display()))?;
let expected = crate::process::clean_canonicalize(path)
.with_context(|| format!("canonicalize {}", path.display()))?;
let actual = git(&expected, &["rev-parse", "--show-toplevel"])?;
let actual = std::fs::canonicalize(actual.trim())?;
let actual = crate::process::clean_canonicalize(actual.trim())?;
if expected != actual {
bail!("repository root mismatch");
}
Expand All @@ -188,18 +188,18 @@ fn canonical_repo_root(path: &Path) -> Result<std::path::PathBuf> {
/// checkout itself). Prevents merging into an arbitrary directory.
fn assert_linked(repo_root: &Path, worktree: &Path) -> Result<()> {
let top = git(worktree, &["rev-parse", "--show-toplevel"])?;
if std::fs::canonicalize(top.trim())? != worktree {
if crate::process::clean_canonicalize(top.trim())? != worktree {
bail!("worktree is not a git checkout root");
}
let common_raw = git(worktree, &["rev-parse", "--git-common-dir"])?
.trim()
.to_owned();
let common = if Path::new(&common_raw).is_absolute() {
std::fs::canonicalize(&common_raw)?
crate::process::clean_canonicalize(&common_raw)?
} else {
std::fs::canonicalize(worktree.join(&common_raw))?
crate::process::clean_canonicalize(worktree.join(&common_raw))?
};
let repo_git = std::fs::canonicalize(repo_root.join(".git"))?;
let repo_git = crate::process::clean_canonicalize(repo_root.join(".git"))?;
if common != repo_git {
bail!("worktree is not linked to repository root");
}
Expand Down
33 changes: 33 additions & 0 deletions crates/leio-harness/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,23 @@ pub(crate) fn unique_id() -> String {
)
}

/// Strip the Windows verbatim drive prefix (`\\?\C:\...` -> `C:\...`) added by
/// `std::fs::canonicalize` so paths match `git rev-parse --show-toplevel` and
/// Node `fs.realpathSync` on Windows.
pub(crate) fn strip_windows_verbatim(path: PathBuf) -> PathBuf {
if let Some(raw) = path.to_str()
&& let Some(stripped) = raw.strip_prefix(r"\\?\")
&& stripped.as_bytes().get(1) == Some(&b':')
{
return PathBuf::from(stripped);
}
path
}

pub(crate) fn clean_canonicalize(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
std::fs::canonicalize(path).map(strip_windows_verbatim)
}

pub fn run(spec: RunSpec) -> Result<RunResult> {
run_observed(spec, None)
}
Expand Down Expand Up @@ -79,6 +96,22 @@ pub fn run_observed(spec: RunSpec, observer: Option<Arc<dyn RunObserver>>) -> Re
"LOGNAME",
"SHELL",
"TMPDIR",
"TEMP",
"TMP",
"SystemRoot",
"SYSTEMROOT",
"WINDIR",
"COMSPEC",
"PATHEXT",
"USERPROFILE",
"APPDATA",
"LOCALAPPDATA",
"PROGRAMDATA",
"PROGRAMFILES",
"PROGRAMFILES(X86)",
"HOMEDRIVE",
"HOMEPATH",
"USERNAME",
"LANG",
"LC_ALL",
"TERM",
Expand Down
9 changes: 5 additions & 4 deletions crates/leio-harness/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ fn root(repo: &Path) -> Result<PathBuf> {
repo.is_absolute() && repo.is_dir(),
"repo must be an absolute existing directory"
);
Ok(repo.canonicalize()?)
Ok(crate::process::clean_canonicalize(repo)?)
}
fn runs(repo: &Path) -> PathBuf {
repo.join(".leio-code/harness/runs")
Expand Down Expand Up @@ -252,10 +252,11 @@ pub fn submit(
#[cfg(unix)]
let checkout = {
let top_bytes = top.stdout.strip_suffix(b"\n").unwrap_or(&top.stdout);
Path::new(std::ffi::OsStr::from_bytes(top_bytes)).canonicalize()?
crate::process::clean_canonicalize(Path::new(std::ffi::OsStr::from_bytes(top_bytes)))?
};
#[cfg(not(unix))]
let checkout = Path::new(std::str::from_utf8(&top.stdout)?.trim()).canonicalize()?;
let checkout =
crate::process::clean_canonicalize(Path::new(std::str::from_utf8(&top.stdout)?.trim()))?;
ensure!(
repo == checkout,
"task repo must be the Git checkout root ({}); constrain module scope in the task instead of submitting a subdirectory",
Expand Down Expand Up @@ -638,7 +639,7 @@ fn collect(spec: &TaskSpec, dir: &Path, tracker: &Tracker) -> Result<()> {
);
let source = repo.join(relative);
let metadata = std::fs::symlink_metadata(&source)?;
if !metadata.is_file() || !source.canonicalize()?.starts_with(repo) {
if !metadata.is_file() || !crate::process::clean_canonicalize(&source)?.starts_with(repo) {
truncated = true;
continue;
}
Expand Down
12 changes: 8 additions & 4 deletions crates/leio-harness/src/workflow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,12 +153,14 @@ pub fn apply_with_deployment_policy(
let plan: Plan =
serde_json::from_slice(&fs::read(input.context("--input plan required")?)?)?;
validate(&plan)?;
let root = repo.context("--repo required")?.canonicalize()?;
let root = crate::process::clean_canonicalize(repo.context("--repo required")?)?;
ensure!(root.is_dir(), "repository must be a directory");
let id = format!(
"urn:leio:workflow:run:{}",
hex::encode(Sha256::digest(
dir.canonicalize()?.to_string_lossy().as_bytes()
crate::process::clean_canonicalize(dir)?
.to_string_lossy()
.as_bytes()
))
);
let state = Workflow {
Expand Down Expand Up @@ -284,7 +286,9 @@ pub fn apply_with_deployment_policy(
run_id: format!("attempt-{}", state.attempts),
argv: step.argv,
cwd: state.repo.display().to_string(),
output_dir: dir.canonicalize()?.display().to_string(),
output_dir: crate::process::clean_canonicalize(dir)?
.display()
.to_string(),
timeout_ms: step.timeout_ms,
kill_grace_ms: 1000,
max_output_bytes: 1024 * 1024,
Expand All @@ -298,7 +302,7 @@ pub fn apply_with_deployment_policy(
let mut artifacts = Vec::new();
// Failed commands can still produce useful partial artifacts.
for name in step.artifacts {
match state.repo.join(&name).canonicalize().and_then(|path| {
match crate::process::clean_canonicalize(state.repo.join(&name)).and_then(|path| {
if !path.starts_with(&state.repo) { return Err(std::io::Error::other("artifact escapes repository")); }
fs::read(path)
}) {
Expand Down
10 changes: 5 additions & 5 deletions crates/leio-harness/src/worktree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,10 @@ pub fn retire(
}

fn canonical_repo_root(path: &Path) -> Result<PathBuf> {
let expected =
std::fs::canonicalize(path).with_context(|| format!("canonicalize {}", path.display()))?;
let expected = crate::process::clean_canonicalize(path)
.with_context(|| format!("canonicalize {}", path.display()))?;
let actual = git(&expected, &["rev-parse", "--show-toplevel"])?;
let actual = std::fs::canonicalize(actual.trim())?;
let actual = crate::process::clean_canonicalize(actual.trim())?;
if expected != actual {
bail!(
"repository root mismatch: expected {}, got {}",
Expand All @@ -148,10 +148,10 @@ fn canonical_repo_root(path: &Path) -> Result<PathBuf> {

fn normalize_absolute(path: &Path) -> Result<PathBuf> {
if path.exists() {
return Ok(std::fs::canonicalize(path)?);
return Ok(crate::process::clean_canonicalize(path)?);
}
let parent = path.parent().context("path has no parent")?;
let parent = std::fs::canonicalize(parent)?;
let parent = crate::process::clean_canonicalize(parent)?;
Ok(parent.join(path.file_name().context("path has no file name")?))
}

Expand Down
19 changes: 8 additions & 11 deletions hooks/session-context.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,11 @@ if [[ ! -f "$SKILL" ]]; then
printf 'LEIO Code skill missing at %s\n' "$SKILL"
exit 0
fi
python3 - "$SKILL" <<'PY'
from pathlib import Path
import sys

text = Path(sys.argv[1]).read_text()
if text.startswith("---"):
parts = text.split("---", 2)
if len(parts) >= 3:
text = parts[2].lstrip("\n")
print(text, end="")
PY
awk '
{ line = $0; sub(/\r$/, "", line) }
NR == 1 && line == "---" { in_fm = 1; next }
in_fm && line == "---" { in_fm = 0; skip_blank = 1; next }
in_fm { next }
skip_blank && line == "" { next }
{ skip_blank = 0; print line }
' "$SKILL"
8 changes: 5 additions & 3 deletions mcp/harness-review.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {createHash,randomUUID} from 'node:crypto';

Expand All @@ -18,7 +19,7 @@ function directory(target) {

function readRegular(target,max) {
if(fs.realpathSync(path.dirname(target)) !== path.dirname(target)) throw new Error('Review path must not contain symlinks');
const fd=fs.openSync(target,fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
const fd=fs.openSync(target,(fs.constants.O_RDONLY ?? 0) | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0));
try {
const before=fs.fstatSync(fd);
if(!before.isFile() || before.size>max) throw new Error('Review input must be a regular file within the byte limit');
Expand All @@ -42,7 +43,7 @@ console.log(JSON.stringify({selected_files_unchanged:true,files:files.length,sco

export async function captureReview(input,runProcess) {
const git=async(args,cwd=input.repo_root)=>{
const result=await runProcess('git',args,cwd,15000,{GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_CONFIG_COUNT:'0'});
const result=await runProcess('git',args,cwd,15000,{GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:os.devNull,GIT_CONFIG_COUNT:'0'});
if(result.code!==0)throw new Error(result.stderr.trim() || 'Review Git setup failed');
return result.stdout.replace(/\r?\n$/,'');
};
Expand All @@ -59,12 +60,13 @@ export async function captureReview(input,runProcess) {
}
const catalog=path.join(input.repo_root,'.leio-code/harness/reviews');directory(catalog);
const id=`${Date.now()}-${randomUUID()}`,owner=path.join(catalog,id),root=path.join(owner,'snapshot');directory(root);
const emptyHooks=path.join(owner,'empty-hooks');directory(emptyHooks);
for(const file of selected) {
const target=path.join(root,file.path);directory(path.dirname(target));
fs.writeFileSync(target,file.bytes,{flag:'wx',mode:file.mode});
}
await git(['init','-q','--template='],root);
await git(['config','core.hooksPath','/dev/null'],root);
await git(['config','core.hooksPath',emptyHooks],root);
directory(path.join(root,'.git/info'));
fs.writeFileSync(path.join(root,'.git/info/exclude'),'.leio-code/\n');
await git(['--literal-pathspecs','add','--force','--',...selected.map(f=>f.path)],root);
Expand Down
9 changes: 6 additions & 3 deletions mcp/harness-tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,12 @@ function executable(candidate) {
}

export function codexArguments(input, {home = os.homedir(), find = findInstalledBinary, readOnly = false, servers = []} = {}) {
const standaloneDir = path.join(home, '.codex/packages/standalone/current/bin');
const binary = input.codex_binary
? executable(input.codex_binary)
: executable(path.join(home,'.codex/packages/standalone/current/bin/codex')) || executable(find('codex',{homeDir:home,accept:candidate=>Boolean(executable(candidate))}));
: executable(path.join(standaloneDir, 'codex'))
|| (process.platform === 'win32' && (executable(path.join(standaloneDir, 'codex.exe')) || executable(path.join(standaloneDir, 'codex.cmd'))))
|| executable(find('codex',{homeDir:home,accept:candidate=>Boolean(executable(candidate))}));
if (!binary) throw new Error('No executable Codex found; supply codex_binary as an absolute executable path. Existing Codex login is required.');
if(readOnly && servers.some(name=>!/^[-A-Za-z0-9_]+$/.test(name)))throw new Error('Cannot isolate an MCP server name containing dots or special characters with Codex CLI overrides; review was not started');
const constraints = [...DEFAULT_CONSTRAINTS,...(input.constraints ?? [])];
Expand Down Expand Up @@ -70,7 +73,7 @@ export function artifactPreview(repo, id, relative, bytes, tail = false) {
const target = path.join(run,relative);
empty.path = target;
if (fs.realpathSync(path.dirname(target)) !== path.dirname(target)) throw new Error('redirected artifact directory');
fd = fs.openSync(target,fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
fd = fs.openSync(target,(fs.constants.O_RDONLY ?? 0) | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0));
const info = fs.fstatSync(fd);
if (!info.isFile()) throw new Error('artifact is not a regular file');
const count = Math.min(info.size,bytes);
Expand Down Expand Up @@ -107,7 +110,7 @@ function newFilePreviews(task, bytes) {
}
const preview=artifactPreview(task.repoRoot,task.runId,path.join('untracked',relative),remaining);
remaining-=Buffer.byteLength(preview.text);
files.push({file:relative,preview});
files.push({file:relative.split(path.sep).join('/'),preview});
}
return {new_files:files,new_files_incomplete:Boolean(task.untrackedTruncated || files.length<archives.length || files.some(f=>!f.preview.available || f.preview.truncated))};
}
Expand Down
1 change: 1 addition & 0 deletions mcp/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,7 @@ function startDetachedLeio(subcommandArgs, repoRoot, { pidName, logName }) {
const child = spawn(invocation.command, invocation.args, {
cwd: invocation.cwd,
detached: true,
windowsHide: true,
stdio: ["ignore", logFd, logFd],
env: process.env,
});
Expand Down
Loading