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
10 changes: 10 additions & 0 deletions MEMORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@

## 책임과 개발 범위

2026-11-19 구현·로컬 검증 완료: [Run별 capability 범위](docs/development/capability-scope.md), [PR #144](https://github.com/PlateerLab/xgen-cli/pull/144).
`run --capability ID`는 선택한 정의와 instance만 planner/admission에 등록하고 manifest와
실행 profile에 결속한다. 기본 전체 catalog·기존 승인·Receipt를 유지하며 resume은 저장한 범위를
복원한다. 이번 검증 결과·한계는 [ADR-0087](docs/adr/0087-run-capability-scope.md)을 따른다.
초기 별도 호스트의 요청 크기 수치는 PR의 선행 기록이며 실제 모델 품질·운영 채택은 미검증이다.

| 구성 요소 | 책임 | 별도로 추적할 개선 |
| --- | --- | --- |
| xgen CLI | 연결·인증 관리, 도구 호출 계약, 권한·승인, 실행, Receipt, 최종 응답, 사용자 경험 | 연결 흐름, 어댑터, 결과 검증, 배포·자동 실행 |
Expand Down Expand Up @@ -186,3 +192,7 @@
- 알려진 흔들림(기존 main에도 있음): `smoke-inline-tui.py --rapid-resize`의 `heldout-burst-restored`가 burst 중간 크기의 입력창 조각이 화면에 남아 가끔 시간 초과한다. 맥 로컬 main 8회 중 1회, 수정본 14회 중 1회. 원인은 연속 reflow를 프런트엔드가 다 따라가지 못해 지울 위치를 잘못 잡는 것(미해결). 같은 스크립트의 `stty.txt` 읽기 경합(파일 생성 직후 빈 내용 읽음)은 고쳤다.
- TUI 사용성(사용자 요청, 2026-11-03, 미구현): Claude Code `/model`처럼 화살표로 고르는 model 선택기. opencode는 TypeScript/Go라 그대로 못 가져온다. 같은 Rust인 OpenAI Codex CLI TUI(ratatui, Apache-2.0)가 참고·이식 후보 — 셀 단위 diff 렌더링이라 지우고 다시 그리는 깜빡임 구조 자체가 없다. 한 단계씩: 깜빡임 수정 → `/model` 선택기 → 렌더러 교체 여부는 ADR로 따로 판단.
- 18초 응답(사용자 보고, 2026-11-03): 시간 전부가 한 번의 HTTP 호출 안이었다(usage elapsedMillis 18324, 출력 52 token). 같은 경로를 tmux TUI·`xgen run`으로 다시 재면 2~5초, 직접 호출 1.5~2초라 일회성 provider 지연으로 본다(원인 확정 아님).

- xgen-cli 자체 개발 순서(2026-11-19, 사용자 승인): 미완료 #144 검증·정리 후 실행 중 후속 지시 반영을 다음 큰 작업으로 둔다. 독립 Run 병렬 실행·상위 Router는 이후 후보이며 아직 구현하지 않았다.
- #144 정리(구현·로컬 검증 완료): 최초 CI는 test의 빈 String 생성에 대한 Clippy1건에서 중단됐다. 최신 main을 병합해 수정했으며, 범위 밖 도구를 지시하는 안내와 필수 completion 검사 모순도 실제 실행에서 재현해 고쳤다. read/stat 승인·resume, 선택 write의 별도 승인, 숨긴 write 차단, HTTP 원문·요청 크기 검증을 진행한다. 독립 diff 검토 도구는 인증 오류로 이용하지 못했으며 직접 코드 검토와 회귀 검사를 수행한다.
- #144 최종 로컬 검증: Rust798개(4 ignored), Python162개(9 skipped), Clippy·fmt·protocol·문서·workflow 검사 통과. 이전 rc.6의 미완료 HTTP Run을 새 바이너리로 재개해 catalog digest와 API 본문이 유지됨을 두 fixture에서 확인했다. 실제 모델 판단 품질·토큰 금액 절감은 미측정이다. 작업은 기존 `/home/son/projects/xgen-cli-wt/capability-scope`의 `codex/capability-scope`에서 진행했다.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,10 @@ durable completion에 저장해. 기존 기본 출력은 유지해.
검증이 누락·실패했거나 이후 변경으로 낡았으면 완료를 거절해.
[완료 검증 조건](docs/development/receipt-completion-checks.md)을 확인해.

필요한 도구가 정해진 headless 실행은 `run --capability ID`를 반복해 도구 범위를 제한할 수 있다.
모델에 제공하는 목록과 실제 실행 가능한 목록이 함께 제한되며, 재개할 때도 저장된 범위를 사용한다.
각 도구의 승인은 별도로 필요하다. [Run별 capability 범위](docs/development/capability-scope.md).

## 제품 원칙

- 사용자는 `xgen` 하나만 설치합니다.
Expand Down
20 changes: 16 additions & 4 deletions crates/xgen-cli/src/allow_path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl WorkspaceReadAuthorization {
if files.iter().any(|path| directories.contains(path)) {
return Err(WorkspaceReadAuthorizationError::DuplicateEntry);
}
let planner_scope_hint = planner_scope_hint(&files, &directories)?;
let planner_scope_hint = planner_scope_hint(&files, &directories, true)?;
let entries = files
.iter()
.map(|path| CatalogEntry { kind: "file", path })
Expand Down Expand Up @@ -84,6 +84,11 @@ impl WorkspaceReadAuthorization {
&self.planner_scope_hint
}

pub(crate) fn scoped_planner_scope_hint(&self) -> String {
planner_scope_hint(&self.files, &self.directories, false)
.expect("validated path catalog has a bounded serializable hint")
}

pub(crate) fn authorizes_material(
&self,
capability: &CapabilityRef,
Expand Down Expand Up @@ -205,6 +210,7 @@ pub(crate) enum WorkspaceReadAuthorizationError {
fn planner_scope_hint(
files: &BTreeSet<String>,
directories: &BTreeSet<String>,
include_tool_guidance: bool,
) -> Result<String, WorkspaceReadAuthorizationError> {
let directories = directories
.iter()
Expand All @@ -218,9 +224,15 @@ fn planner_scope_hint(
.map_err(|_| WorkspaceReadAuthorizationError::Canonicalization)?;
let files = serde_json::to_string(&files)
.map_err(|_| WorkspaceReadAuthorizationError::Canonicalization)?;
let hint = format!(
"Caller-authorized directory roots (list/search targets and descendant stat/read/write-atomic/apply-patch targets): {directories}. Additional exact files (stat/read only): {files}. write-atomic requires expectedDigest=null for creation or the exact digest previously read for replacement. apply-patch requires the exact whole-file digest previously read (read-text digest or read-text-lines fileDigest) and 1..={MAX_APPLY_PATCH_EDITS} non-overlapping edits; every oldText must occur exactly once."
);
let hint = if include_tool_guidance {
format!(
"Caller-authorized directory roots (list/search targets and descendant stat/read/write-atomic/apply-patch targets): {directories}. Additional exact files (stat/read only): {files}. write-atomic requires expectedDigest=null for creation or the exact digest previously read for replacement. apply-patch requires the exact whole-file digest previously read (read-text digest or read-text-lines fileDigest) and 1..={MAX_APPLY_PATCH_EDITS} non-overlapping edits; every oldText must occur exactly once."
)
} else {
format!(
"Caller-authorized directory roots and descendants: {directories}. Additional exact files (read only): {files}. Use these paths only with the capabilities offered in this Run."
)
};
if hint.len() > MAX_PLANNER_SCOPE_HINT_BYTES {
return Err(WorkspaceReadAuthorizationError::PlannerHintTooLarge);
}
Expand Down
17 changes: 17 additions & 0 deletions crates/xgen-cli/src/allow_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ impl fmt::Debug for ProcessTooling {
pub(crate) struct ProcessExecutionAuthorization {
canonical_resources: BTreeSet<String>,
planner_scope_hint: String,
logical_ids_json: String,
catalog_digest: String,
web_search_enabled: bool,
}
Expand Down Expand Up @@ -191,6 +192,7 @@ impl ProcessExecutionAuthorization {
Ok(Self {
canonical_resources,
planner_scope_hint,
logical_ids_json: encoded_ids,
catalog_digest: sha256_digest(&canonical),
web_search_enabled: ids.contains(WEB_SEARCH_EXECUTABLE_ID),
})
Expand All @@ -208,6 +210,17 @@ impl ProcessExecutionAuthorization {
&self.planner_scope_hint
}

pub(crate) fn scoped_planner_scope_hint(&self, execute_offered: bool) -> String {
if execute_offered {
self.planner_scope_hint().to_owned()
} else {
format!(
"Caller-catalogued process executable logical IDs: {}. Use executable IDs only with the capabilities offered in this Run.",
self.logical_ids_json
)
}
}

pub(crate) fn catalog_digest(&self) -> &str {
&self.catalog_digest
}
Expand All @@ -221,6 +234,7 @@ impl fmt::Debug for ProcessExecutionAuthorization {
.field("web_search_enabled", &self.web_search_enabled)
.field("resources", &"<redacted>")
.field("planner_scope_hint", &"<redacted>")
.field("logical_ids_json", &"<redacted>")
.field("catalog_digest", &self.catalog_digest)
.finish()
}
Expand Down Expand Up @@ -285,6 +299,9 @@ mod tests {
);
assert!(!debug.contains(&executable.to_string_lossy().into_owned()));
assert!(!debug.contains("test-helper"));
let scoped = tooling.authorization().scoped_planner_scope_hint(false);
assert!(scoped.contains("test-helper"));
assert!(!scoped.contains("process.execute"));
assert!(ProcessTooling::build(directory.path(), "primary", ["test=relative"]).is_err());
assert!(
ProcessTooling::build(
Expand Down
100 changes: 100 additions & 0 deletions crates/xgen-cli/src/capability_scope.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//! Optional host-selected capability subset, committed before planning and admission.
use std::collections::BTreeSet;

use xgen_runtime::CapabilityRegistry;

pub(crate) fn normalize(ids: Vec<String>) -> Result<Option<Vec<String>>, ()> {
if ids.is_empty() {
return Ok(None);
}
let mut sorted = ids;
sorted.sort();
if !valid(&sorted) {
return Err(());
}
Ok(Some(sorted))
}

pub(crate) fn valid(ids: &[String]) -> bool {
!ids.is_empty()
&& ids.len() <= 128
&& ids.windows(2).all(|p| p[0] < p[1])
&& ids.iter().all(|id| {
!id.is_empty()
&& id.len() <= 256
&& id
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"._/-:".contains(&c))
})
}

pub(crate) fn validate_available<'a>(
ids: Option<&[String]>,
available: impl Iterator<Item = &'a str>,
) -> Result<(), ()> {
if let Some(ids) = ids {
let available = available.collect::<BTreeSet<_>>();
if !valid(ids) || ids.iter().any(|id| !available.contains(id.as_str())) {
return Err(());
}
}
Ok(())
}

pub(crate) fn apply(
registry: CapabilityRegistry,
ids: Option<&[String]>,
) -> Result<CapabilityRegistry, ()> {
let Some(ids) = ids else { return Ok(registry) };
validate_available(
Some(ids),
registry.definitions().map(|d| d.metadata.id.as_str()),
)?;
let mut scoped = CapabilityRegistry::new();
for definition in registry
.definitions()
.filter(|d| ids.contains(&d.metadata.id))
{
scoped
.register_schema_validated_definition(definition.clone())
.map_err(|_| ())?;
}
for instance in registry
.instances()
.filter(|i| ids.contains(&i.definition.capability_id))
{
scoped
.register_schema_validated_instance(instance.clone())
.map_err(|_| ())?;
}
Ok(scoped)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn default_and_canonical_scope() {
assert_eq!(normalize(vec![]), Ok(None));
assert_eq!(
normalize(vec!["b/read".into(), "a/read".into()]),
Ok(Some(vec!["a/read".into(), "b/read".into()]))
);
for ids in [
vec!["a/read".into(), "a/read".into()],
vec![String::new()],
vec!["a read".into()],
] {
assert!(normalize(ids).is_err());
}
}

#[test]
fn unknown_scope_never_falls_back_to_full_catalog() {
for id in ["missing/read", "missing/write"] {
assert!(validate_available(Some(&[id.into()]), ["a/read"].into_iter()).is_err());
assert!(apply(CapabilityRegistry::new(), Some(&[id.into()])).is_err());
}
}
}
Loading