// generated by hxc 1.0.0-acgt-compiler from src/continuation.hlx -- do not edit by hand
#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
if !ok {
eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
}
ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
c
}
// hlx:2
use super::check::json::{self, J};
// hlx:3
use std::{collections::BTreeMap, fs, io::Read, path::Path};
// hlx:4
fn field<'a>(v: &'a J, key: &str) -> Option<&'a J> {
if let J::Obj(fields) = v {
fields.iter().find(|(k, _)| k == key).map(|(_, v)| v)
} else {
None
}
}
// hlx:5
fn text<'a>(v: &'a J, key: &str) -> Option<&'a str> {
if let Some(J::Str(s)) = field(v, key) {
Some(s)
} else {
None
}
}
// hlx:6
fn clean_id(id: &str) -> bool {
!id.is_empty()
&& id.len() <= 128
&& id
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"-_".contains(&c))
}
// hlx:7
#[derive(Debug)]
struct Task {
id: String,
status: String,
blocked: Vec<String>,
external: bool,
}
// hlx:8
fn task(v: &J) -> Result<Task, String> {
let id = text(v, "id")
.filter(|s| clean_id(s))
.ok_or("invalid task id")?;
let status = text(v, "status").ok_or("missing task status")?;
if !matches!(status, "pending" | "in_progress" | "completed" | "deleted") {
return Err("unknown task status".into());
}
let blocked = match field(v, "blockedBy") {
None => vec![],
Some(J::Arr(a)) => a
.iter()
.map(|x| {
if let J::Str(s) = x {
if clean_id(s) {
Ok(s.clone())
} else {
Err("invalid dependency")
}
} else {
Err("invalid dependency")
}
})
.collect::<Result<Vec<_>, _>>()?,
_ => return Err("invalid blockedBy".into()),
};
let external = field(v, "metadata")
.and_then(|m| text(m, "continuation_blocked_reason"))
.is_some_and(|s| !s.trim().is_empty());
Ok(Task {
id: id.into(),
status: status.into(),
blocked,
external,
})
}
// hlx:9
fn read_tasks(dir: &Path) -> Result<BTreeMap<String, Task>, String> {
let meta = fs::symlink_metadata(dir).map_err(|_| "task directory unavailable")?;
if !meta.is_dir() || meta.file_type().is_symlink() {
return Err("task directory must be a real directory".into());
}
let mut tasks = BTreeMap::new();
let mut scanned = 0;
let mut total = 0;
for entry in fs::read_dir(dir).map_err(|_| "cannot read task directory")? {
scanned += 1;
if scanned > 1024 {
return Err("task scan limit".into());
}
let entry = entry.map_err(|_| "task entry unavailable")?;
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
let Some(stem) = name.strip_suffix(".json") else {
continue;
};
if !clean_id(stem) {
return Err("invalid task filename".into());
}
let meta = entry.file_type().map_err(|_| "task metadata unavailable")?;
if !meta.is_file() || meta.is_symlink() {
return Err("task file must be regular".into());
}
let mut bytes = Vec::new();
fs::File::open(entry.path())
.map_err(|_| "task read failed")?
.take(65537)
.read_to_end(&mut bytes)
.map_err(|_| "task read failed")?;
total += bytes.len();
if bytes.len() > 65536 || total > 4 * 1024 * 1024 {
return Err("task byte limit".into());
}
let t = task(&json::parse(&bytes)?)?;
if t.id != stem || tasks.insert(t.id.clone(), t).is_some() {
return Err("task identity mismatch".into());
}
}
Ok(tasks)
}
// hlx:10
fn actionable(tasks: &BTreeMap<String, Task>) -> Vec<String> {
let mut out: Vec<_> = tasks
.values()
.filter(|t| {
matches!(t.status.as_str(), "pending" | "in_progress")
&& !t.external
&& t.blocked.iter().all(|id| {
tasks
.get(id)
.is_some_and(|d| matches!(d.status.as_str(), "completed" | "deleted"))
})
})
.collect();
out.sort_by(|a, b| {
let ai = a.status == "in_progress";
let bi = b.status == "in_progress";
bi.cmp(&ai)
.then_with(|| match (a.id.parse::<u64>(), b.id.parse::<u64>()) {
(Ok(x), Ok(y)) => x.cmp(&y),
_ => a.id.cmp(&b.id),
})
});
out.into_iter().map(|t| t.id.clone()).collect()
}
// hlx:11
fn decision(event: &J, session: &str, dir: &Path) -> Result<Option<String>, String> {
if text(event, "session_id") != Some(session) {
return Ok(None);
}
if text(event, "hook_event_name") != Some("Stop") {
return Ok(None);
}
match field(event, "stop_hook_active") {
Some(J::Bool(true)) => return Ok(None),
Some(J::Bool(false)) | None => {}
_ => return Err("invalid stop loop flag".into()),
}
let first = read_tasks(dir)?;
let ids = actionable(&first);
if ids.is_empty() {
return Ok(None);
}
let second = read_tasks(dir)?;
if actionable(&second) != ids {
return Err("task state changed during read".into());
}
let shown = ids.iter().take(6).cloned().collect::<Vec<_>>().join(", ");
Ok(Some(format!("{{\"decision\":\"block\",\"reason\":\"Instinct continuation: {} unfinished actionable task(s), IDs: {}. Read TaskGet for task {} and perform its next authorized implementation or verification step now. A review handoff or status summary is not task completion. Do not mark unfinished work complete. If the task is genuinely blocked, record metadata.continuation_blocked_reason with the specific external dependency, then work on another unblocked task. This reminder grants no permissions and never overrides a user stop/pause request or a security/approval boundary.\"}}",ids.len(),shown,ids[0])))
}
// hlx:12
pub(crate) fn cli(args: &[String]) -> Result<(), String> {
if args == ["--help"] {
println!("usage: instinct continue-tasks --session SESSION_ID --tasks-dir ABS_DIRECTORY\nExplicit opt-in Stop hook. Reads only this selected task list; no transcripts or bank.\nUse metadata.continuation_blocked_reason for a real external blocker. Recursive Stop hooks are silent.");
return Ok(());
}
let (mut session, mut dir) = (None, None);
let mut i = 0;
while i < args.len() {
let slot = match args[i].as_str() {
"--session" => &mut session,
"--tasks-dir" => &mut dir,
_ => return Err("unknown continue-tasks option".into()),
};
if slot.is_some() {
return Err("duplicate continue-tasks option".into());
}
i += 1;
*slot = Some(args.get(i).ok_or("missing continue-tasks value")?.clone());
i += 1;
}
let session = session
.filter(|s| clean_id(s))
.ok_or("explicit valid --session required")?;
let dir = dir.ok_or("explicit --tasks-dir required")?;
if !Path::new(&dir).is_absolute() {
return Err("--tasks-dir must be absolute".into());
}
let mut input = Vec::new();
std::io::stdin()
.take(65537)
.read_to_end(&mut input)
.map_err(|_| "cannot read Stop event")?;
if input.len() > 65536 {
return Err("Stop event exceeds 64 KiB".into());
}
let event = json::parse(&input)?;
match decision(&event,&session,Path::new(&dir)){Ok(Some(out))=>println!("{out}"),Ok(None)=>{},Err(_)=>eprintln!("Instinct continuation: task state unavailable or inconsistent; no continuation decision issued")};
Ok(())
}
// hlx:13
#[cfg(test)]
#[path = "continuation_tests.rs"]
mod tests;