Skip to content

armgit / Cairn

Public Imported from GitHub
0

Cairn is a general-purpose AI state-space search engine, validated first on autonomous penetration testing. Sometimes misspelled as Carin.

fix: pass graph snapshots through container files to avoid argv limits

leixiao3e0b1493abff
diff --git a/cairn/src/cairn/dispatcher/runtime/containers.py b/cairn/src/cairn/dispatcher/runtime/containers.py
index 115ef0e..f96ca5e 100644
--- a/cairn/src/cairn/dispatcher/runtime/containers.py
+++ b/cairn/src/cairn/dispatcher/runtime/containers.py
@@ -1,6 +1,9 @@
from __future__ import annotations
+import io
import logging
+from pathlib import PurePosixPath
+import tarfile
import threading
import uuid
@@ -209,6 +212,16 @@ class ContainerManager:
argv.extend(command)
return ManagedProcess(container, argv, env)
+ def write_text_file(self, container_name: str, path: str, content: str) -> None:
+ archive_path, archive = self._text_file_archive(path, content)
+ container = self._require_container(container_name)
+ try:
+ ok = container.put_archive(archive_path, archive)
+ except DockerException as exc:
+ raise RuntimeError(f"failed to write container file {path}: {exc}") from exc
+ if not ok:
+ raise RuntimeError(f"failed to write container file {path}")
+
def remove_container(self, name: str, *, force: bool = True) -> None:
container = self._get_container(name)
if container is None:
@@ -250,3 +263,36 @@ class ContainerManager:
status_code = getattr(getattr(exc, "response", None), "status_code", None)
explanation = str(getattr(exc, "explanation", "") or exc)
return status_code == 409 or "is already in use" in explanation
+
+ @staticmethod
+ def _text_file_archive(path: str, content: str) -> tuple[str, bytes]:
+ target = PurePosixPath(path)
+ if not target.is_absolute() or target.name in ("", ".", ".."):
+ raise ValueError(f"container file path must be absolute: {path}")
+ parts = target.parts[1:]
+ if not parts or any(part in ("", ".", "..") for part in parts):
+ raise ValueError(f"invalid container file path: {path}")
+ if len(parts) == 1:
+ archive_path = "/"
+ archive_parts = parts
+ else:
+ archive_path = f"/{parts[0]}"
+ archive_parts = parts[1:]
+
+ payload = content.encode("utf-8")
+ stream = io.BytesIO()
+ with tarfile.open(fileobj=stream, mode="w") as archive:
+ parent = ""
+ for part in archive_parts[:-1]:
+ parent = f"{parent}/{part}" if parent else part
+ info = tarfile.TarInfo(parent)
+ info.type = tarfile.DIRTYPE
+ info.mode = 0o755
+ archive.addfile(info)
+
+ file_name = "/".join(archive_parts)
+ info = tarfile.TarInfo(file_name)
+ info.size = len(payload)
+ info.mode = 0o644
+ archive.addfile(info, io.BytesIO(payload))
+ return archive_path, stream.getvalue()
diff --git a/cairn/src/cairn/dispatcher/tasks/common.py b/cairn/src/cairn/dispatcher/tasks/common.py
index a028df7..dabf39b 100644
--- a/cairn/src/cairn/dispatcher/tasks/common.py
+++ b/cairn/src/cairn/dispatcher/tasks/common.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import logging
import time
+import uuid
from dataclasses import dataclass
from cairn.dispatcher.config import WorkerConfig
@@ -14,6 +15,7 @@ from cairn.dispatcher.runtime.process import ProcessResult
HEALTHCHECK_COMMUNICATE_GRACE_SECONDS = 10
PROCESS_COMMUNICATE_GRACE_SECONDS = 15
LOG_PREVIEW_LIMIT = 1200
+GRAPH_SNAPSHOT_ROOT = "/tmp/cairn-prompts"
LOG = logging.getLogger(__name__)
@@ -52,6 +54,23 @@ def communicate_timeout(timeout_seconds: int, grace_seconds: int = PROCESS_COMMU
return timeout_seconds + grace_seconds
+def write_graph_snapshot_reference(
+ container_manager: ContainerManager,
+ container_name: str,
+ graph_yaml: str,
+ *,
+ phase: str,
+) -> str:
+ path = f"{GRAPH_SNAPSHOT_ROOT}/{phase}-{uuid.uuid4().hex[:12]}/graph.yaml"
+ container_manager.write_text_file(container_name, path, graph_yaml)
+ return (
+ "The graph YAML snapshot is stored in this file inside the current container:\n\n"
+ f"{path}\n\n"
+ "Before using the graph, read the entire file and treat its contents as the YAML snapshot "
+ "for this Graph section."
+ )
+
+
def run_healthcheck(
container_manager: ContainerManager,
container_name: str,
diff --git a/cairn/src/cairn/dispatcher/tasks/explore.py b/cairn/src/cairn/dispatcher/tasks/explore.py
index deef6c2..db81d2b 100644
--- a/cairn/src/cairn/dispatcher/tasks/explore.py
+++ b/cairn/src/cairn/dispatcher/tasks/explore.py
@@ -19,6 +19,7 @@ from cairn.dispatcher.tasks.common import (
run_healthcheck,
run_worker_process,
write_conclude_result,
+ write_graph_snapshot_reference,
)
from cairn.dispatcher.workers.registry import get_driver
from cairn.server.models import Intent, ProjectDetail
@@ -96,7 +97,12 @@ def run_explore_task(
prompt = render_prompt(
load_prompt(config.runtime.prompt_group, "explore.md"),
{
- "graph_yaml": export_yaml.strip(),
+ "graph_yaml": write_graph_snapshot_reference(
+ container_manager,
+ container_name,
+ export_yaml.strip(),
+ phase="explore_execute",
+ ),
"intent_id": intent.id,
"intent_description": intent.description,
},
@@ -294,7 +300,12 @@ def _try_conclude_fallback(
prompt = render_prompt(
load_prompt(config.runtime.prompt_group, "explore_conclude.md"),
{
- "graph_yaml": export_yaml.strip(),
+ "graph_yaml": write_graph_snapshot_reference(
+ container_manager,
+ container_name,
+ export_yaml.strip(),
+ phase="explore_conclude",
+ ),
"intent_id": intent.id,
"intent_description": intent.description,
},
diff --git a/cairn/src/cairn/dispatcher/tasks/reason.py b/cairn/src/cairn/dispatcher/tasks/reason.py
index f80e219..3897d0e 100644
--- a/cairn/src/cairn/dispatcher/tasks/reason.py
+++ b/cairn/src/cairn/dispatcher/tasks/reason.py
@@ -22,6 +22,7 @@ from cairn.dispatcher.tasks.common import (
preview,
run_healthcheck,
run_worker_process,
+ write_graph_snapshot_reference,
)
from cairn.dispatcher.workers.registry import get_driver
from cairn.server.models import ProjectDetail
@@ -110,7 +111,12 @@ def run_reason_task(
prompt = render_prompt(
load_prompt(config.runtime.prompt_group, "reason.md"),
{
- "graph_yaml": export_yaml.strip(),
+ "graph_yaml": write_graph_snapshot_reference(
+ container_manager,
+ container_name,
+ export_yaml.strip(),
+ phase="reason_execute",
+ ),
"fact_ids": format_fact_ids(allowed_fact_ids),
"open_intents": format_open_intents(open_intents),
"max_intents": str(config.tasks.reason.max_intents),