use serde_json::{json, Value};
use crate::schema_registry::ENVELOPE_SCHEMA_VERSION;
mod template;
pub use crate::schema_registry::PLAN_SCHEMA_VERSION;
const REQUIRED_PLAN_VERSION: &str = "1.0";
const SCHEMA_DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";
fn r(name: &str) -> Value {
json!({ "$ref": format!("#/$defs/{name}") })
}
fn r_doc(name: &str, description: &str) -> Value {
json!({ "$ref": format!("#/$defs/{name}"), "description": description })
}
fn prim(ty: &str, description: &str) -> Value {
json!({ "type": ty, "description": description })
}
fn nonempty_string(description: &str) -> Value {
json!({ "type": "string", "minLength": 1, "description": description })
}
fn constant(value: &str, description: &str) -> Value {
json!({ "type": "string", "const": value, "description": description })
}
fn uint(description: &str) -> Value {
json!({ "type": "integer", "minimum": 0, "description": description })
}
fn array_of(items: Value, min_items: usize, description: &str) -> Value {
json!({
"type": "array",
"items": items,
"minItems": min_items,
"description": description,
})
}
fn object(properties: Value, required: &[&str], description: &str) -> Value {
json!({
"type": "object",
"description": description,
"properties": properties,
"required": required,
"additionalProperties": true,
})
}
fn closed_object(properties: Value, required: &[&str], description: &str) -> Value {
json!({
"type": "object",
"description": description,
"properties": properties,
"required": required,
"additionalProperties": false,
})
}
fn plan_def() -> Value {
object(
json!({
"planVersion": constant(
REQUIRED_PLAN_VERSION,
"계획서 문법 판번호. 실행기는 \"1.0\" 만 받고 그 밖의 값은 exit 2 로 거절한다.",
),
"input": prim("string", "원본 문서 경로 (HWP/HWPX/HML). 실행기는 이 파일을 읽기만 한다."),
"output": prim(
"string",
"산출 경로. 전 step 이 인메모리로 적용되고 단언을 통과한 뒤 **단 한 번** 여기에 쓴다. \
확장자가 산출 형식을 정한다(생략 시 입력 형식 보존).",
),
"steps": array_of(
r("Step"),
1,
"적용할 편집 목록. 선언 순서대로 인메모리에 적용된다. 비어 있으면 exit 2 — \
아무것도 하지 않는 계획은 의도가 아니라 실수다.",
),
"assertions": r_doc(
"Assertions",
"저장 전에 통과해야 하는 단언. 생략하면 기본값으로 판정한다.",
),
"preconditions": r_doc(
"Preconditions",
"[#4378 R22] 실행 전 전제(CAS). 하나라도 어긋나면 실행 0·저장 0 으로 \
거절한다(exit 3 = 판정, preconditionFailed{kind,expected,actual} + nextCall). \
`--dry-run` 도 같은 대조·같은 판정을 낸다.",
),
"dryRun": json!({
"type": "boolean",
"default": false,
"description": "참이면 선검증만 하고 저장하지 않는다(디스크 무변경). 저널 대신 \
preview[] 를 낸다 — 각 항목은 step·action 에 더해 조건이 거짓이면 \
skipped:true·reason 을 싣는다. `run --dry-run` 플래그와 동등하다.",
}),
}),
&["planVersion", "input", "output", "steps"],
"`rhwp run` 이 받는 편집 계획서. 도구 호출을 체이닝하는 대신 의도 하나를 선언하면 \
실행기가 전 step 의 실행 가능성을 먼저 판정하고(불가 시 실행 0·exit 2), \
인메모리 원자 실행 뒤 단언 통과 시에만 저장한다.",
)
}
fn preconditions_def() -> Value {
object(
json!({
"inputSha256": prim(
"string",
"input 파일 전체의 SHA-256(64자리 16진, 대소문자 무관). 실행 시점의 \
실제 해시와 다르면 — 계획 수립 후 다른 에이전트/사람이 문서를 바꿨다는 \
뜻이므로 — 아무것도 적용하지 않고 preconditionFailed{kind,expected,actual} \
+ nextCall(재계획 힌트) + exit 3 으로 거절한다(`--dry-run` 도 같은 판정). \
경합 유실(#3905: 두 exit 0 이 편집 하나를 무신호로 지움)의 \
차단기다. 해시는 `rhwp-agent fingerprint` 또는 sha256sum 으로 얻는다.",
),
}),
&["inputSha256"],
"실행 전 전제. 현재 축은 inputSha256 하나이며, 축 추가는 minor 다.",
)
}
fn assertions_def() -> Value {
object(
json!({
"notFoundEmpty": json!({
"type": "boolean",
"default": true,
"description": "지목한 대상이 하나도 빠지지 않았음을 요구한다. 선검증이 구조적으로 \
보장하므로(없는 대상은 실행 전에 invalid) 저널에 계약 표기로 실린다.",
}),
"verify": json!({
"type": "boolean",
"default": false,
"description": "저장 직전 산출 바이트를 다시 읽어 인메모리 IR 과 대조한다. \
차이가 있으면 exit 3 이고 **디스크는 무변경**이다.",
}),
}),
&[],
"사후 단언 — 실패하면 저장하지 않는다. 계획이 스스로 검증 조건을 들고 다니게 해서 \
\"성공했다고 보고했는데 산출물이 깨진\" 상태를 구조적으로 없앤다.",
)
}
fn step_def() -> Value {
json!({
"description": "편집 step 하나. `action` 이 판별자인 태그드 유니온이며, 8종 전부 \
선택 필드 `if`(조건절)를 받는다.",
"oneOf": [
r("FillFieldsStep"),
r("ReplaceTextStep"),
r("SetCellStep"),
r("SetCheckboxStep"),
r("FillTemplateStep"),
r("RepeatAndFillParagraphBlockStep"),
r("RepeatAndFillTableRowsStep"),
r("ImportParagraphBlockStep"),
],
})
}
fn step_variant(
action: &str,
action_doc: &str,
extra: Value,
required: &[&str],
doc: &str,
) -> Value {
let mut properties = serde_json::Map::new();
properties.insert("action".to_string(), constant(action, action_doc));
if let Some(map) = extra.as_object() {
for (key, value) in map {
properties.insert(key.clone(), value.clone());
}
}
properties.insert(
"if".to_string(),
r_doc(
"StepCondition",
"선택 조건. 거짓이면 이 step 을 건너뛰고 저널에 skipped:true 로 남긴다. \
거짓인 step 은 선검증에서도 면제된다(없는 필드를 채우는 step 이라도 위반이 아니다).",
),
);
let mut required_all = vec!["action".to_string()];
required_all.extend(required.iter().map(|s| s.to_string()));
object(
Value::Object(properties),
&required_all.iter().map(String::as_str).collect::<Vec<_>>(),
doc,
)
}
fn fill_fields_step_def() -> Value {
step_variant(
"fill_fields",
"누름틀(필드)에 값을 채우는 step 임을 지목한다.",
json!({
"data": json!({
"type": "object",
"description": "필드 이름 → 채울 값. 같은 이름이 여러 번 나오는 서식은 \
`이름[순번]`(0 기준)으로 지목한다(예: \"피규제집단명[13]\"). \
순번 없이 이름만 주면 첫 칸을 채우고 저널의 ambiguous 로 알린다.",
"additionalProperties": {
"type": ["string", "number", "boolean"],
"description": "채울 값. 문자열이 아니면 JSON 표기 그대로 문자열화해 넣는다.",
},
}),
}),
&["data"],
"누름틀 채우기 (메일머지). 화면상 구별되지 않는 이름의 쌍둥이 필드가 있으면 채우되 \
저널의 `confusable` 로 반드시 보고한다.",
)
}
fn replace_text_step_def() -> Value {
step_variant(
"replace_text",
"본문 문자열을 치환하는 step 임을 지목한다.",
json!({
"find": json!({
"type": "string",
"minLength": 1,
"description": "찾을 문자열. 빈 문자열은 거부한다(문서 전체를 뜻하게 되므로).",
}),
"replace": prim("string", "바꿔 넣을 문자열. 빈 문자열이면 삭제다."),
"caseSensitive": json!({
"type": "boolean",
"default": true,
"description": "대소문자를 구별할지. 기본은 구별한다.",
}),
"occurrence": uint(
"0 기준 일치 순번. 주면 그 한 건만, 생략하면 전건을 치환한다. \
범위를 벗어나면 선검증에서 거부한다.",
),
}),
&["find", "replace"],
"문자열 치환 (기관명 변경·연도 갱신·용어 정비). 일치 0건이면 선검증에서 거부한다 \
— 조용히 0건 치환을 성공으로 보고하지 않는다.",
)
}
fn set_cell_step_def() -> Value {
step_variant(
"set_cell",
"표 한 칸의 내용을 바꾸는 step 임을 지목한다.",
json!({
"table": uint("0 기준 표 번호 (문서 순서)."),
"row": json!({
"type": "integer",
"minimum": 0,
"maximum": 65535,
"description": "0 기준 행 번호. HWP 격자 주소는 u16 이라 65535 를 넘으면 거부한다.",
}),
"col": json!({
"type": "integer",
"minimum": 0,
"maximum": 65535,
"description": "0 기준 열 번호. HWP 격자 주소는 u16 이라 65535 를 넘으면 거부한다.",
}),
"text": json!({
"type": "string",
"pattern": "^[^\r\n\t]*$",
"description": "칸에 기록할 한 줄 값. 줄바꿈·탭은 거부한다(칸 구조가 깨지므로).",
}),
"keepStyle": json!({
"type": "boolean",
"default": false,
"description": "참이면 기존 글자색을 유지한다. 기본은 검정으로 바꾼다 \
— 서식 안내문의 회색 예시 글자를 그대로 두면 제출본에 남는다.",
}),
}),
&["table", "row", "col", "text"],
"표 칸 기록. 좌표는 실행 시점에 다시 해석하므로 앞 step 의 편집으로 밀린 표도 안전하다. \
병합으로 덮인 칸은 앵커 좌표 안내와 함께 거부한다.",
)
}
fn set_checkbox_step_def() -> Value {
step_variant(
"set_checkbox",
"빈 체크박스를 표시하는 step 임을 지목한다.",
json!({
"occurrence": uint(
"0 기준 빈 체크박스(□) 순번. 범위를 벗어나면 선검증에서 거부한다.",
),
}),
&["occurrence"],
"체크박스 표시 — 문서의 n 번째 빈 체크박스 □ 를 ☑ 로 바꾼다.",
)
}
fn step_condition_def() -> Value {
let mut def = closed_object(
json!({
"fieldExists": nonempty_string(
"그 이름의 누름틀이 문서에 있으면 참. `이름[순번]`(0 기준)으로 특정 순번의 \
존재를 물을 수도 있다 — 동명 필드가 몇 개인지에 따라 참·거짓이 갈린다.",
),
"fieldEquals": r_doc(
"FieldEqualsCondition",
"지목한 누름틀의 **현재 값**이 주어진 값과 정확히 같으면 참.",
),
"textFound": nonempty_string(
"그 문자열이 본문에 한 건이라도 있으면 참 (대소문자 구별).",
),
}),
&[],
"step 조건절. 정확히 한 종류만 쓴다 — 두 조건을 함께 주면 and 인지 or 인지가 \
계획서에 적혀 있지 않으므로 거부한다. 판정은 **입력 문서 기준으로 실행 전에 한 번** \
이루어지며, 앞 step 의 편집 결과가 뒤 step 의 조건을 바꾸지 않는다 \
(선검증과 실행이 같은 판정을 보게 하기 위한 것이다).",
);
if let Some(map) = def.as_object_mut() {
map.insert("minProperties".to_string(), json!(1));
map.insert("maxProperties".to_string(), json!(1));
}
def
}
fn preview_step_def() -> Value {
object(
json!({
"step": uint("0 기준 step 순번 — 계획서 steps[] 의 인덱스와 같다. 건너뛴 step 도 \
자리를 지키므로 저널 항목과 계획서 항목을 순번으로 짝지을 수 있다."),
"action": prim(
"string",
"그 step 의 action. 기존 4종 및 템플릿/가져오기 4종이며 Step 정의를 따른다.",
),
"operationResult": prim("object", "템플릿 action의 예정 적용 대상·경로 대응표. 실행 시 같은 입력에서 동일 구조를 반환한다."),
"source": prim("object", "가져오기 전용 {path,sha256}. 한 번 읽어 검증한 원본 파일 지문. workload 대신 result.resources에 자원 집계를 낸다."),
"workload": prim("object", "records·targets·replacementTextBytes 입력 작업량. 메모리나 조판 비용 실측값이 아니다."),
"skipped": json!({
"type": "boolean",
"description": "참이면 `if` 조건이 거짓이라 이 step 은 실행되지 않는다 — 선검증도 \
면제된다. 거짓(또는 생략)이면 정상적으로 실행 가능하다고 판정된 것이다.",
}),
"reason": prim(
"string",
"`skipped` 가 참일 때만 실리는 사유 — 어느 조건이 왜 거짓이었는지. 실행 가능한 \
step 에는 없다.",
),
}),
&["step", "action"],
"`dryRun:true` 저널의 `preview[]` 원소 하나. `skipped` 가 없거나 거짓이면 그 step 은 실제 \
실행에서도 적용될 것이라는 뜻이고, 참이면 `reason` 과 함께 건너뛸 것이라는 뜻이다 — \
dry-run 이 예고하는 실행 개수와 `run`(실제 실행)이 보고할 적용 개수가 같은 말을 하도록 한다.",
)
}
fn field_equals_condition_def() -> Value {
closed_object(
json!({
"name": nonempty_string(
"누름틀 이름. `이름[순번]`(0 기준)으로 동명 필드 중 하나를 지목할 수 있다.",
),
"value": prim("string", "비교할 값. 문자열 완전 일치로만 판정한다."),
}),
&["name", "value"],
"`fieldEquals` 의 피연산자 — 어떤 필드의 값이 무엇과 같은지.",
)
}
fn definition_count(schema: &Value) -> usize {
schema
.get("$defs")
.and_then(|d| d.as_object())
.map(|o| o.len())
.unwrap_or(0)
}
pub fn plan_schema() -> Value {
let mut defs: serde_json::Map<String, Value> = [
("Plan", plan_def()),
("Preconditions", preconditions_def()),
("Assertions", assertions_def()),
("Step", step_def()),
("FillFieldsStep", fill_fields_step_def()),
("ReplaceTextStep", replace_text_step_def()),
("SetCellStep", set_cell_step_def()),
("SetCheckboxStep", set_checkbox_step_def()),
("StepCondition", step_condition_def()),
("FieldEqualsCondition", field_equals_condition_def()),
("PreviewStep", preview_step_def()),
]
.into_iter()
.map(|(name, def)| (name.to_string(), def))
.collect();
template::extend(&mut defs);
template::restrict_single_step(defs.get_mut("Plan").expect("Plan exists"));
json!({
"$schema": SCHEMA_DIALECT,
"$id": format!("https://github.com/edwardkim/rhwp/schema/plan/{PLAN_SCHEMA_VERSION}"),
"title": "rhwp 편집 계획서",
"planSchemaVersion": PLAN_SCHEMA_VERSION,
"description":
"`rhwp run` 이 실행하는 선언적 편집 계획서의 공개 계약. 계획을 **만드는** 쪽이 \
읽는 문서다 — 필수·선택 필드와 허용 값이 실행기의 선검증 분기와 1:1로 대응한다. \
진화 규약: 필드 추가 = minor, 의미 변경·삭제 = major.",
"$ref": "#/$defs/Plan",
"x-dryRunPreview": r_doc(
"PreviewStep",
"`dryRun:true` 로 실행했을 때 저널의 `preview[]` 배열 원소 하나의 모양. 입력 \
계획서가 받는 필드가 아니라 실행기가 돌려주는 저널의 계약이다.",
),
"$defs": defs,
})
}
pub fn envelope() -> Value {
let schema = plan_schema();
let def_count = definition_count(&schema);
json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"planSchemaVersion": PLAN_SCHEMA_VERSION,
"dialect": SCHEMA_DIALECT,
"definitionCount": def_count,
"schema": schema,
})
}
#[cfg(test)]
mod tests {
use super::*;
const CLOSED_DEFS: &[(&str, &str)] = &[
("ImportParagraphBlockStep", "파일 입력 계약의 미지 옵션을 런타임과 동일하게 거부한다"),
(
"StepCondition",
"실행기가 모르는 조건 키를 invalid 로 거부한다 — 스키마가 더 관대하면 통과한 계획이 실행에서 막힌다",
),
(
"FieldEqualsCondition",
"피연산자가 name·value 둘뿐이다 — 셋째 키는 뜻이 정의돼 있지 않다",
),
(
"TemplateLimits",
"native 요청이 상한 키 오타를 거부한다 — 안전 예산의 잘못된 지정을 묵살하지 않는다",
),
(
"TemplateScope",
"native 요청의 deny_unknown_fields와 같은 명시 대상 주소 계약을 유지한다",
),
(
"TemplateBlock",
"복제 원형·삽입 경계·복사 수의 오타를 native 요청처럼 거부한다",
),
];
#[test]
fn schema_has_root_and_defs() {
let schema = plan_schema();
assert_eq!(schema["$ref"], "#/$defs/Plan");
assert!(schema["$defs"]["Plan"].is_object());
assert!(schema["$defs"]["StepCondition"].is_object());
}
#[test]
fn every_ref_resolves_to_a_definition() {
let schema = plan_schema();
let defs = schema["$defs"].as_object().expect("$defs");
let mut missing = Vec::new();
collect_refs(&schema, &mut |name| {
if !defs.contains_key(name) {
missing.push(name.to_string());
}
});
assert!(missing.is_empty(), "정의되지 않은 참조: {missing:?}");
}
#[test]
fn definitions_are_reachable_from_root() {
let schema = plan_schema();
let defs = schema["$defs"].as_object().expect("$defs");
let mut referenced = std::collections::HashSet::new();
referenced.insert("Plan".to_string());
collect_refs(&schema, &mut |name| {
referenced.insert(name.to_string());
});
let orphans: Vec<&String> = defs.keys().filter(|k| !referenced.contains(*k)).collect();
assert!(orphans.is_empty(), "아무도 참조하지 않는 정의: {orphans:?}");
}
#[test]
fn objects_are_open_unless_listed_with_a_reason() {
let schema = plan_schema();
let defs = schema["$defs"].as_object().expect("$defs");
for (name, def) in defs {
if def["type"] != "object" {
continue;
}
if name == "TemplateRecord" {
assert_eq!(def["additionalProperties"]["type"], "string");
continue;
}
let closed = CLOSED_DEFS.iter().find(|(n, _)| n == name);
match closed {
Some((_, why)) => {
assert_eq!(
def["additionalProperties"], false,
"{name} 은 닫힌 객체로 등재됐는데 실제로는 열려 있다 ({why})"
);
}
None => assert_eq!(
def["additionalProperties"], true,
"{name} 이 추가 필드를 막고 있다 — 계획서는 추가-전용 진화다. \
정말 닫아야 하면 CLOSED_DEFS 에 사유와 함께 등재하라"
),
}
}
for (name, why) in CLOSED_DEFS {
assert!(defs.contains_key(*name), "낡은 CLOSED_DEFS 항목: {name}");
assert!(!why.trim().is_empty(), "{name} 의 닫은 사유가 비었습니다");
}
}
#[test]
fn step_union_is_discriminated_by_action() {
let schema = plan_schema();
let variants = schema["$defs"]["Step"]["oneOf"]
.as_array()
.expect("Step.oneOf");
assert_eq!(variants.len(), 8, "기존 4종과 템플릿/가져오기 4종");
let mut actions = Vec::new();
for variant in variants {
let name = variant["$ref"]
.as_str()
.and_then(|p| p.strip_prefix("#/$defs/"))
.expect("oneOf 분기는 $defs 참조");
let def = &schema["$defs"][name];
let action = def["properties"]["action"]["const"]
.as_str()
.unwrap_or_else(|| panic!("{name} 에 action const 가 없다"));
assert!(
def["required"]
.as_array()
.expect("required")
.iter()
.any(|r| r == "action"),
"{name} 이 action 을 필수로 선언하지 않았다"
);
assert!(
def["properties"]["if"]["$ref"] == "#/$defs/StepCondition",
"{name} 이 조건절 `if` 를 받지 않는다"
);
actions.push(action.to_string());
}
actions.sort();
assert_eq!(
actions,
[
"fill_fields",
"fill_template",
"import_paragraph_block",
"repeat_and_fill_paragraph_block",
"repeat_and_fill_table_rows",
"replace_text",
"set_cell",
"set_checkbox"
]
);
}
#[test]
fn every_definition_and_property_carries_a_description() {
let schema = plan_schema();
let mut missing = Vec::new();
for (name, def) in schema["$defs"].as_object().expect("$defs") {
check_described(def, name, &mut missing);
}
assert!(missing.is_empty(), "설명 없는 스키마 노드: {missing:?}");
}
#[test]
fn envelope_reports_definition_count() {
let env = envelope();
assert_eq!(env["schemaVersion"], "1.0");
assert_eq!(env["planSchemaVersion"], PLAN_SCHEMA_VERSION);
assert_eq!(env["dialect"], SCHEMA_DIALECT);
let count = env["definitionCount"].as_u64().expect("definitionCount");
assert!(count >= 9, "정의가 너무 적다: {count}");
assert_eq!(env["schema"]["$ref"], "#/$defs/Plan");
}
fn check_described(node: &Value, path: &str, missing: &mut Vec<String>) {
let Some(map) = node.as_object() else {
return;
};
let pure_ref = map.len() == 1 && map.contains_key("$ref");
if !pure_ref
&& !map
.get("description")
.and_then(Value::as_str)
.is_some_and(|d| !d.trim().is_empty())
{
missing.push(path.to_string());
}
if let Some(props) = map.get("properties").and_then(Value::as_object) {
for (key, value) in props {
check_described(value, &format!("{path}.{key}"), missing);
}
}
if let Some(extra) = map.get("additionalProperties") {
if extra.is_object() {
check_described(extra, &format!("{path}.additionalProperties"), missing);
}
}
}
fn collect_refs(value: &Value, sink: &mut impl FnMut(&str)) {
match value {
Value::Object(map) => {
for (key, item) in map {
if key == "$ref" {
if let Some(path) = item.as_str() {
if let Some(name) = path.strip_prefix("#/$defs/") {
sink(name);
}
}
} else {
collect_refs(item, sink);
}
}
}
Value::Array(items) => {
for item in items {
collect_refs(item, sink);
}
}
_ => {}
}
}
}