diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e64d83a9..7b7c0840 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -320,6 +320,12 @@ jobs:
- name: Verify bounded watcher states and rejected source mutations
run: python3 -B scripts/verify_alden_realtime_state.py
+ - name: Test declared and body notation normalization
+ run: python3 -B -m unittest tests.test_alden_time_normalization tests.test_alden_quantity_normalization tests.test_alden_normalization_evidence tests.test_alden_body_normalization tests.test_alden_body_details -v
+
+ - name: Verify body notation source mutation sensitivity
+ run: python3 -B scripts/verify_alden_body_normalization.py
+
# The reader enforces a process peak RSS budget. Earlier test modules
# must not consume the memory allowance of this independent CLI process.
- name: Test bounded affinity in a fresh process
diff --git a/desktop/src-tauri/src/resource_layout.rs b/desktop/src-tauri/src/resource_layout.rs
index e5ac6157..c2a113b7 100644
--- a/desktop/src-tauri/src/resource_layout.rs
+++ b/desktop/src-tauri/src/resource_layout.rs
@@ -50,6 +50,7 @@ pub const DATA_FILES: &[&str] = &[
"scripts/alden_link_fetch.py",
"scripts/alden_graph_quality.py",
"scripts/alden_normalization_evidence.py",
+ "scripts/alden_body_normalization.py",
"scripts/alden_time_normalization.py",
"scripts/alden_quantity_normalization.py",
"scripts/alden_content_evidence.py",
diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json
index e63f5052..3c857c06 100644
--- a/desktop/src-tauri/tauri.conf.json
+++ b/desktop/src-tauri/tauri.conf.json
@@ -134,6 +134,7 @@
"bundle-resources/scripts/alden_link_fetch.py": "scripts/alden_link_fetch.py",
"bundle-resources/scripts/alden_graph_quality.py": "scripts/alden_graph_quality.py",
"bundle-resources/scripts/alden_normalization_evidence.py": "scripts/alden_normalization_evidence.py",
+ "bundle-resources/scripts/alden_body_normalization.py": "scripts/alden_body_normalization.py",
"bundle-resources/scripts/alden_time_normalization.py": "scripts/alden_time_normalization.py",
"bundle-resources/scripts/alden_quantity_normalization.py": "scripts/alden_quantity_normalization.py",
"bundle-resources/scripts/alden_content_evidence.py": "scripts/alden_content_evidence.py",
diff --git a/desktop/src/__tests__/body-notation.test.ts b/desktop/src/__tests__/body-notation.test.ts
new file mode 100644
index 00000000..16c9b2e2
--- /dev/null
+++ b/desktop/src/__tests__/body-notation.test.ts
@@ -0,0 +1,87 @@
+// @vitest-environment happy-dom
+import { webcrypto } from 'node:crypto';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fixture from './fixtures/body-notation.json';
+import { verifiedBodyNotation, renderBodyNotation } from '../knowledge/body-notation';
+import { parseKnowledgeGraph } from '../knowledge/graph-model';
+import { renderNodeDetails, setNodeDetailsVisible } from '../knowledge/node-details';
+
+const data = () => structuredClone(fixture);
+const graph = () => parseKnowledgeGraph({ nodes: [{ id: 'record-a', label: '자료', category: 'document', source_version: 'v1', source_target: 'target-a' }], edges: [] });
+beforeEach(() => {
+ vi.stubGlobal('crypto', webcrypto);
+ document.body.innerHTML = '';
+ const pane = document.querySelector('dialog')!;
+ pane.close = () => { pane.removeAttribute('open'); };
+});
+afterEach(() => vi.unstubAllGlobals());
+
+describe('exact source body notation boundary', () => {
+ it('accepts the actual Python parser fixture, including emoji, exact integers and percent points', async () => {
+ const result = await verifiedBodyNotation(graph().nodes[0], data());
+ expect(result?.items).toHaveLength(8);
+ expect(result?.items.map(item => item.value)).toEqual(expect.arrayContaining(['2026-02-23', '50000000 원', '-5 명', '5 %p', '8000 g ~ 3000 g · 원문 순서', '의미 미확정', '9007199254740993 명']));
+ });
+ it.each([
+ ['body bytes', (v: any) => { v.body = v.body.replace('기한', '수정'); }],
+ ['document', (v: any) => { v.body_notation.binding.document_id = 'other'; }],
+ ['version', (v: any) => { v.body_notation.binding.version = 'v2'; }],
+ ['target', (v: any) => { v.body_notation.binding.target_id = 'other'; }],
+ ['archive', (v: any) => { v.body_notation.binding.raw_sha256 = 'b'.repeat(64); }],
+ ['body digest', (v: any) => { v.body_notation.binding.body_sha256 = v.body_notation.analysis.body_sha256 = 'b'.repeat(64); }],
+ ['excerpt scope', (v: any) => { v.body_notation.binding.body_scope = 'detail_body_excerpt'; }],
+ ['raw quote', (v: any) => { v.body_notation.analysis.candidates[0].raw = '
'; }],
+ ['UTF16 offset', (v: any) => { v.body_notation.analysis.candidates[0].utf16_start -= 1; }],
+ ['codepoint offset', (v: any) => { v.body_notation.analysis.candidates[0].start -= 1; }],
+ ['invalid offset', (v: any) => { v.body_notation.analysis.candidates[0].start = -1; }],
+ ['overlapping spans', (v: any) => { v.body_notation.analysis.candidates.push(v.body_notation.analysis.candidates[0]); }],
+ ['unknown unit', (v: any) => { v.body_notation.analysis.candidates[1].canonical_unit = 'KRW'; }],
+ ['invented dimension', (v: any) => { v.body_notation.analysis.candidates[1].dimension = '__proto__'; }],
+ ['fact claim', (v: any) => { v.body_notation.analysis.semantic_validity = 'verified'; }],
+ ['incomplete state', (v: any) => { v.body_notation.analysis.state = 'supported_notation_scan_complete'; v.body_notation.analysis.truncated = true; }],
+ ['excess candidates', (v: any) => { v.body_notation.analysis.candidates = Array(65).fill(v.body_notation.analysis.candidates[0]); }],
+ ])('rejects a mismatched %s without altering the body', async (_name, mutate) => {
+ const value = data(); mutate(value);
+ expect(await verifiedBodyNotation(graph().nodes[0], value)).toBeNull();
+ });
+ it('supports canonical IDs after unified graph ID rewriting', async () => {
+ const node = { ...graph().nodes[0], id: 'scoped:record-a', canonicalId: 'record-a' };
+ expect(await verifiedBodyNotation(node, { ...data(), node_id: node.id })).not.toBeNull();
+ });
+ it('leaves the source readable if WebCrypto is absent or rejects', async () => {
+ vi.stubGlobal('crypto', {});
+ renderNodeDetails(graph(), graph().nodes[0], { ok: true, details: data() });
+ await vi.waitFor(() => expect(document.querySelector('.knowledge-body-notation')).toBeNull());
+ expect(document.getElementById('knowledge-node-body')?.textContent).toBe(fixture.body);
+ vi.stubGlobal('crypto', { subtle: { digest: () => Promise.reject(new Error('unavailable')) } });
+ renderBodyNotation(document.getElementById('knowledge-node-body')!, graph().nodes[0], data());
+ await vi.waitFor(() => expect(document.querySelector('.knowledge-body-notation')).toBeNull());
+ });
+ it('uses a collapsed disclosure and literal source quotes without HTML execution', async () => {
+ renderNodeDetails(graph(), graph().nodes[0], { ok: true, details: data() });
+ await vi.waitFor(() => expect(document.querySelector('.knowledge-body-notation')?.hidden).toBe(false));
+ const section = document.querySelector('.knowledge-body-notation')!;
+ expect(section.open).toBe(false);
+ expect(section.querySelectorAll('mark')).toHaveLength(8);
+ expect(document.querySelector('img')).toBeNull();
+ expect(section.textContent).toContain('현재 유효성');
+ expect(document.querySelector('#knowledge-node-facts')).toBeNull();
+ });
+ it('discloses excerpt and candidate budgets', async () => {
+ const value = data(); value.truncated = true; value.body_notation.binding.body_scope = 'detail_body_excerpt';
+ value.body_notation.analysis.truncated = true; value.body_notation.analysis.state = 'bounded_candidates';
+ renderBodyNotation(document.getElementById('knowledge-node-body')!, graph().nodes[0], value);
+ await vi.waitFor(() => expect(document.querySelector('.knowledge-body-notation')?.textContent).toContain('처리 한도'));
+ expect(document.querySelector('.knowledge-body-notation')?.textContent).toContain('발췌 범위');
+ });
+ it.each(['new render', 'close'])('discards a delayed digest after %s', async action => {
+ let finish!: (buffer: ArrayBuffer) => void;
+ vi.stubGlobal('crypto', { subtle: { digest: () => new Promise(resolve => { finish = resolve; }) } });
+ renderNodeDetails(graph(), graph().nodes[0], { ok: true, details: data() });
+ if (action === 'new render') renderNodeDetails(graph(), graph().nodes[0], { ok: false });
+ else setNodeDetailsVisible(false);
+ finish(await webcrypto.subtle.digest('SHA-256', new TextEncoder().encode(fixture.body)));
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(document.querySelector('.knowledge-body-notation')).toBeNull();
+ });
+});
diff --git a/desktop/src/__tests__/fixtures/body-notation.json b/desktop/src/__tests__/fixtures/body-notation.json
new file mode 100644
index 00000000..a7933f63
--- /dev/null
+++ b/desktop/src/__tests__/fixtures/body-notation.json
@@ -0,0 +1,161 @@
+{
+ "node_id": "record-a",
+ "basis": "source_record",
+ "target_id": "target-a",
+ "version": "v1",
+ "raw_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "body": "😀 기한 2026년 2월 23일, 연봉 5천만원, 수량 −5명. 비율 5%p, 범위 8~3kg. 연도 26년 2월 23일. 단위 없는 5천. 큰 수 9007199254740993명.
",
+ "truncated": false,
+ "body_notation": {
+ "binding": {
+ "basis": "verified_source_record_detail",
+ "document_id": "record-a",
+ "target_id": "target-a",
+ "version": "v1",
+ "raw_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "body_sha256": "3bd423a018cc59c3bc022869685c893d5a120b898774622ee622a7e5e33a3f83",
+ "body_scope": "detail_body"
+ },
+ "analysis": {
+ "policy": "body-notation-candidates-v1",
+ "state": "supported_notation_scan_complete",
+ "body_sha256": "3bd423a018cc59c3bc022869685c893d5a120b898774622ee622a7e5e33a3f83",
+ "body_characters": 130,
+ "offset_basis": "exact_supplied_unicode_codepoints",
+ "semantic_validity": "not_assessed",
+ "client_offset_basis": "exact_supplied_utf16_code_units",
+ "source_authorization": "caller_must_bind_permitted_current_source_version",
+ "candidates": [
+ {
+ "kind": "time",
+ "start": 5,
+ "end": 17,
+ "raw": "2026년 2월 23일",
+ "status": "normalized",
+ "precision": "day",
+ "canonical": "2026-02-23",
+ "basis": "date_only",
+ "reason": null,
+ "utf16_start": 6,
+ "utf16_end": 18
+ },
+ {
+ "start": 22,
+ "end": 26,
+ "raw": "5천만원",
+ "source_unit": "원",
+ "source_sign": "unsigned",
+ "kind": "quantity",
+ "status": "normalized",
+ "canonical_value": "50000000",
+ "canonical_unit": "원",
+ "dimension": "money_won_unspecified",
+ "reason": null,
+ "utf16_start": 23,
+ "utf16_end": 27
+ },
+ {
+ "start": 31,
+ "end": 34,
+ "raw": "−5명",
+ "source_unit": "명",
+ "source_sign": "negative",
+ "kind": "quantity",
+ "status": "normalized",
+ "canonical_value": "-5",
+ "canonical_unit": "명",
+ "dimension": "person_count",
+ "reason": null,
+ "utf16_start": 32,
+ "utf16_end": 35
+ },
+ {
+ "start": 39,
+ "end": 42,
+ "raw": "5%p",
+ "source_unit": "%p",
+ "source_sign": "unsigned",
+ "kind": "quantity",
+ "status": "normalized",
+ "canonical_value": "5",
+ "canonical_unit": "%p",
+ "dimension": "percentage_point",
+ "reason": null,
+ "utf16_start": 40,
+ "utf16_end": 43
+ },
+ {
+ "start": 47,
+ "end": 52,
+ "raw": "8~3kg",
+ "source_unit": "kg",
+ "source_sign": "unsigned",
+ "kind": "quantity_range",
+ "status": "normalized",
+ "reason": null,
+ "first": {
+ "status": "normalized",
+ "dimension": "mass",
+ "canonical_value": "8000",
+ "canonical_unit": "g",
+ "reason": null
+ },
+ "last": {
+ "status": "normalized",
+ "dimension": "mass",
+ "canonical_value": "3000",
+ "canonical_unit": "g",
+ "reason": null
+ },
+ "range_marker": "~",
+ "written_order": "descending",
+ "utf16_start": 48,
+ "utf16_end": 53
+ },
+ {
+ "kind": "time",
+ "start": 57,
+ "end": 67,
+ "raw": "26년 2월 23일",
+ "status": "ambiguous",
+ "canonical": null,
+ "reason": "century_not_declared",
+ "precision": "day",
+ "basis": "body_notation",
+ "utf16_start": 58,
+ "utf16_end": 68
+ },
+ {
+ "kind": "untyped_number",
+ "start": 75,
+ "end": 78,
+ "raw": "5천.",
+ "status": "ambiguous",
+ "reason": "unit_not_declared",
+ "source_unit": null,
+ "canonical_unit": null,
+ "dimension": null,
+ "canonical_value": null,
+ "utf16_start": 76,
+ "utf16_end": 79
+ },
+ {
+ "start": 83,
+ "end": 100,
+ "raw": "9007199254740993명",
+ "source_unit": "명",
+ "source_sign": "unsigned",
+ "kind": "quantity",
+ "status": "normalized",
+ "canonical_value": "9007199254740993",
+ "canonical_unit": "명",
+ "dimension": "person_count",
+ "reason": null,
+ "utf16_start": 84,
+ "utf16_end": 101
+ }
+ ],
+ "truncated": false
+ }
+ }
+}
diff --git a/desktop/src/knowledge/body-notation.ts b/desktop/src/knowledge/body-notation.ts
new file mode 100644
index 00000000..6200571e
--- /dev/null
+++ b/desktop/src/knowledge/body-notation.ts
@@ -0,0 +1,107 @@
+import type { KnowledgeNode } from './graph-model';
+
+type ObjectValue = Record;
+type Notation = { raw: string; start: number; end: number; status: string; value: string };
+const object = (value: unknown): ObjectValue | null => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as ObjectValue : null;
+const sha = (value: unknown): value is string => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
+const decimal = (value: unknown): value is string => typeof value === 'string' && value.length <= 256 && /^-?[0-9]+(?:\.[0-9]+)?$/.test(value);
+const units: Record = { mass: 'g', length: 'm', duration: 's', data: 'bit',
+ money_won_unspecified: '원', money_KRW: 'KRW', money_USD: 'USD', money_EUR: 'EUR', money_JPY: 'JPY',
+ person_count: '명', item_count: '개', case_count: '건', occurrence_count: '회', percent: '%', percentage_point: '%p' };
+const statuses: Record = { normalized: '구문 변환', ambiguous: '의미 미확정', unsupported: '지원 범위 밖', invalid: '형식 확인 필요' };
+
+function quantity(value: ObjectValue | null): string | null {
+ if (!value || value.status !== 'normalized' || !decimal(value.canonical_value)
+ || typeof value.dimension !== 'string' || !Object.hasOwn(units, value.dimension)
+ || value.canonical_unit !== units[value.dimension]) return null;
+ // Keep exact decimal strings, including integers beyond Number's precision.
+ return `${value.canonical_value} ${units[value.dimension]}`;
+}
+
+function display(value: ObjectValue): string | null {
+ if (typeof value.status !== 'string' || !Object.hasOwn(statuses, value.status)
+ || !['time', 'quantity', 'quantity_range', 'quantity_relation', 'untyped_number'].includes(String(value.kind))) return null;
+ if (value.status !== 'normalized') return statuses[value.status];
+ if (value.kind === 'time') return typeof value.canonical === 'string' && value.canonical.length <= 64
+ && /^[0-9]{4}-[0-9]{2}-[0-9]{2}(?:T[0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:\.[0-9]{1,9})?)?Z)?$/.test(value.canonical) ? value.canonical : null;
+ if (value.kind === 'quantity') return quantity(value);
+ if (value.kind === 'quantity_range') {
+ const first = object(value.first), last = object(value.last);
+ const left = quantity(first), right = quantity(last);
+ return left && right && first?.dimension === last?.dimension && first?.canonical_unit === last?.canonical_unit
+ && ['~', '~', '–', '—'].includes(String(value.range_marker)) ? `${left} ~ ${right} · 원문 순서` : null;
+ }
+ return null;
+}
+
+/** Verify only an annotation packet for this exact source excerpt; never infer facts. */
+export async function verifiedBodyNotation(node: KnowledgeNode, selected: ObjectValue): Promise<{ items: Notation[]; excerpt: boolean; limited: boolean } | null> {
+ const note = object(selected.body_notation), binding = object(note?.binding), analysis = object(note?.analysis);
+ const body = selected.body;
+ if (selected.basis !== 'source_record' || selected.node_id !== node.id || typeof body !== 'string' || body.length > 24000 || !binding || !analysis
+ || binding.basis !== 'verified_source_record_detail' || binding.document_id !== (node.canonicalId || node.id)
+ || binding.target_id !== node.sourceTarget || binding.target_id !== selected.target_id
+ || binding.version !== node.sourceVersion || binding.version !== selected.version
+ || !sha(selected.raw_sha256) || binding.raw_sha256 !== selected.raw_sha256
+ || !sha(binding.body_sha256) || binding.body_sha256 !== analysis.body_sha256
+ || binding.body_scope !== (selected.truncated === true ? 'detail_body_excerpt' : 'detail_body')
+ || analysis.policy !== 'body-notation-candidates-v1' || analysis.semantic_validity !== 'not_assessed'
+ || analysis.offset_basis !== 'exact_supplied_unicode_codepoints' || analysis.client_offset_basis !== 'exact_supplied_utf16_code_units'
+ || analysis.source_authorization !== 'caller_must_bind_permitted_current_source_version'
+ || typeof analysis.truncated !== 'boolean'
+ || analysis.state !== (analysis.truncated ? 'bounded_candidates' : 'supported_notation_scan_complete')
+ || !Array.isArray(analysis.candidates) || analysis.candidates.length > 64) return null;
+ const boundaries = [0]; let utf16 = 0;
+ for (const scalar of body) {
+ if (scalar.length === 1 && /[\ud800-\udfff]/.test(scalar)) return null;
+ utf16 += scalar.length; boundaries.push(utf16);
+ }
+ if (boundaries.length - 1 > 12000 || analysis.body_characters !== boundaries.length - 1) return null;
+ const items: Notation[] = []; let previousEnd = 0;
+ for (const candidate of analysis.candidates) {
+ const value = object(candidate);
+ if (!value || !Number.isInteger(value.start) || !Number.isInteger(value.end)) return null;
+ const start = value.start as number, end = value.end as number;
+ if (start < previousEnd || end <= start || end >= boundaries.length
+ || value.utf16_start !== boundaries[start] || value.utf16_end !== boundaries[end]
+ || typeof value.raw !== 'string' || value.raw.length > 512 || value.raw !== body.slice(boundaries[start], boundaries[end])) return null;
+ const copy = display(value); if (!copy) return null;
+ items.push({ raw: value.raw, start: boundaries[start], end: boundaries[end], status: statuses[String(value.status)], value: copy });
+ previousEnd = end;
+ }
+ // Backend checked the archive/current version; this independently binds client
+ // offsets to the delivered body. Missing WebCrypto leaves the source readable.
+ if (!globalThis.crypto?.subtle) return null;
+ const expectedHash = binding.body_sha256;
+ const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(body));
+ const actual = Array.from(new Uint8Array(hash), byte => byte.toString(16).padStart(2, '0')).join('');
+ return actual === expectedHash ? { items, excerpt: selected.truncated === true, limited: analysis.truncated } : null;
+}
+
+export function renderBodyNotation(bodyElement: HTMLElement, node: KnowledgeNode, selected: ObjectValue | null): void {
+ const root = bodyElement.ownerDocument;
+ root.querySelectorAll('.knowledge-body-notation').forEach(item => item.remove());
+ if (!selected?.body_notation) return;
+ const body = selected.body as string;
+ const section = root.createElement('details'); section.className = 'knowledge-body-notation'; section.hidden = true;
+ bodyElement.after(section);
+ void verifiedBodyNotation(node, selected).then(result => {
+ const pane = root.getElementById('knowledge-note-pane');
+ if (!section.isConnected) return; // Another render/close invalidated this request.
+ if (!result?.items.length || pane && pane.hidden) { section.remove(); return; }
+ const summary = root.createElement('summary'); summary.textContent = `날짜·수량 표기 · ${result.items.length}개`;
+ const explanation = root.createElement('p');
+ explanation.textContent = '원문에 적힌 표기만 해석합니다. 실제 사실·현재 유효성·채용 조건은 확인하지 않았습니다.'
+ + (result.excerpt ? ' 본문 앞부분의 발췌 범위입니다.' : '') + (result.limited ? ' 처리 한도에 도달해 일부만 표시합니다.' : '');
+ const list = root.createElement('ul');
+ for (const item of result.items) {
+ const row = root.createElement('li'), quote = root.createElement('q'), mark = root.createElement('mark'), resultText = root.createElement('span');
+ mark.textContent = item.raw;
+ quote.append(root.createTextNode(body.slice(Math.max(0, item.start - 36), item.start)), mark,
+ root.createTextNode(body.slice(item.end, item.end + 36)));
+ resultText.textContent = item.status === item.value ? item.status : `${item.status} · ${item.value}`;
+ row.append(quote, resultText); list.append(row);
+ }
+ section.append(summary, explanation, list); section.hidden = false;
+ }).catch(() => section.remove());
+}
diff --git a/desktop/src/knowledge/node-details.ts b/desktop/src/knowledge/node-details.ts
index aa93c90c..57c4987f 100644
--- a/desktop/src/knowledge/node-details.ts
+++ b/desktop/src/knowledge/node-details.ts
@@ -1,5 +1,6 @@
import type { KnowledgeGraph, KnowledgeNode } from './graph-model';
import { matchesSourceReference } from './graph-model';
+import { renderBodyNotation } from './body-notation';
const STRIPPED_TEXT_CONTROLS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g;
function text(value: unknown, limit = 1200): string {
@@ -101,6 +102,7 @@ export function setNodeDetailsVisible(visible: boolean, root: Document = documen
pane.hidden = false;
if (!pane.open) pane.showModal();
} else {
+ root.querySelectorAll('.knowledge-body-notation').forEach(item => item.remove());
if (pane.open) pane.close();
pane.hidden = true;
delete pane.dataset.nodeId;
@@ -183,6 +185,7 @@ export function renderNodeDetails(graph: KnowledgeGraph, node: KnowledgeNode, pa
const candidate = readingCandidate(selected, retainedCopy);
const reading = candidate?.reading ?? copy;
if (body) { renderBody(body, reading, graph, selected?.basis !== 'source_record'); body.hidden = !reading; }
+ if (body) renderBodyNotation(body, node, selected);
root.querySelectorAll('.knowledge-body-limit').forEach(note => note.remove());
if (body && reading && (clipped || selected?.truncated === true)) {
const note = root.createElement('p'); note.className = 'knowledge-body-limit';
diff --git a/desktop/src/settings.css b/desktop/src/settings.css
index 712dc66f..dcbf43ca 100644
--- a/desktop/src/settings.css
+++ b/desktop/src/settings.css
@@ -602,6 +602,13 @@ body.settings-view {
.knowledge-separated-tail summary { cursor:pointer; }
.knowledge-separated-tail p { margin:8px 0; }
.knowledge-separated-tail-text { white-space:pre-wrap; overflow-wrap:anywhere; font:inherit; }
+.knowledge-body-notation { margin:12px 0 18px; font-size:12px; line-height:1.65; color:var(--muted); }
+.knowledge-body-notation summary { cursor:pointer; }
+.knowledge-body-notation ul { list-style:none; padding:0; max-height:280px; overflow:auto; }
+.knowledge-body-notation li { padding:8px 0; border-top:1px solid var(--border); overflow-wrap:anywhere; }
+.knowledge-body-notation q { display:block; white-space:pre-wrap; quotes:none; }
+.knowledge-body-notation mark { background:#6ad2d526; color:inherit; border-radius:3px; padding:0 2px; }
+.knowledge-body-notation li span { display:block; margin-top:4px; }
.knowledge-node-facts { padding-left:20px; margin:0 0 22px; font-size:14px; line-height:1.8; white-space:pre-wrap; overflow-wrap:anywhere; }
.knowledge-node-facts li + li { margin-top:8px; }
.knowledge-note-subheading { font-size:12px; font-weight:600; color:var(--muted); margin:24px 0 8px; }
diff --git a/docs/evaluation/body-normalization-20261024.md b/docs/evaluation/body-normalization-20261024.md
new file mode 100644
index 00000000..99037f57
--- /dev/null
+++ b/docs/evaluation/body-normalization-20261024.md
@@ -0,0 +1,116 @@
+# Body notation candidate parser
+
+The installed quality scan of 12,561 permitted career versions found no explicit
+quantity/time metadata fields. That is a coverage gap; it does not establish that
+body numbers or dates were normalized. The pure parser now connects to the
+source-detail read API and a collapsed source-popup disclosure. Its module is
+included in the desktop and immutable-worker resource lists. It does not write
+ingestion, search indexes, graph facts or a persistent annotation database.
+
+`scripts/alden_body_normalization.py::analyze_body_fields` accepts the exact body
+string and returns lexical candidates bound to its UTF-8 SHA-256. Source text is
+not rewritten, normalized to NFC, merged or discarded. Every candidate includes
+its exact substring, Unicode-codepoint offsets and JavaScript UTF-16 offsets.
+The caller must validate permission, current document/version and body digest
+before exposing results. The API checks current membership, permissions, native
+source authority, projection/version identity and the retained archive again
+after analysis, and after the entity projection before returning the packet.
+These are bounded read validation points, not perpetual freshness after delivery.
+
+The popup independently checks the node/target/version/archive/excerpt binding,
+UTF-16 and codepoint spans and a WebCrypto digest of the exact delivered body.
+Failed/absent WebCrypto omits annotations and keeps the original source readable.
+Close, replacement and failed-response paths remove the pending disclosure, so
+an old asynchronous digest cannot attach to a newly selected source. Quotes use
+literal DOM text. Canonical decimal strings never pass through JavaScript Number.
+The disclosure separates notation from facts and shows excerpt/candidate limits;
+short years, missing units and other ambiguity remain visible.
+
+Supported notation includes year-first Gregorian dates and ISO-like times,
+explicit physical/data units through the existing exact converter, count units,
+explicit currency codes/literal won, Korean numeric magnitudes and percent versus
+percentage points. `1억 2천만원` yields the number 120000000 in literal `원`; it
+does not infer a national currency or exchange rate. `초봉 5천` can expose 5000
+with no unit and an ambiguous status. Two-digit years, missing timezones,
+hyphen-as-range-versus-subtraction, factual claim roles and temporal validity
+are not guessed. Written endpoint order and explicit signs remain visible.
+
+The safety promise is exact, bounded syntax annotation without invented units,
+centuries, timezones or source authorization. It is not semantic fact extraction.
+Inputs above 131,072 code points return a budget result with no claimed body
+hash; candidate count is capped at 64 and numeric tokens at 128 characters.
+Budget state/truncation must remain visible. URL tokens are excluded. Plain IDs,
+relative dates, prefix-only currency expressions, repeated-unit interval
+assembly, arbitrary locale formats and all possible Unicode operators are not
+comprehensively supported. No-candidate output does not mean a body lacks
+numbers, dates or meaningful knowledge.
+
+```mermaid
+stateDiagram-v2
+ [*] --> Input
+ Input --> BudgetResult: body exceeds character budget
+ Input --> InvalidInput: type or UTF-8 invalid
+ Input --> BoundText: digest exact supplied text
+ BoundText --> Candidates: scan supported date / quantity notation
+ Candidates --> SyntaxNormalized: exact supported notation
+ Candidates --> Ambiguous: unit / century / timezone / operator unresolved
+ Candidates --> InvalidNotation: grouping / calendar / arithmetic invalid
+ SyntaxNormalized --> Report
+ Ambiguous --> Report
+ InvalidNotation --> Report
+ Report --> TruncatedReport: candidate budget exhausted
+ Report --> SourceReadValidation
+ TruncatedReport --> SourceReadValidation
+ SourceReadValidation --> Rejected: changed authority / version / archive
+ SourceReadValidation --> ClientBinding: current source at read boundary
+ ClientBinding --> Omitted: invalid packet / missing crypto / closed popup
+ ClientBinding --> Disclosure: exact body digest and spans
+```
+
+This is a conceptual projection of the parser and implemented read/display
+boundaries, not a formal liveness proof or fact-store promotion. Concurrent-state
+regressions use private synthetic databases and fake native authority adapters.
+
+For body length N and returned count C <= 64, hashing, URL scanning and the UTF-16
+boundary map traverse at most O(N). Three lexical streams use a fixed 128-character
+numeric window; decimal precision and unit tables are fixed. Storage is O(N+C)
+because URL intervals may grow with input. These are code-derived bounds with
+fixed grammar constants, not a wall-clock SLA or a generic linear-time claim for
+unbounded regexes. Numeric candidate normalization uses a private exact Decimal
+context; the existing SI converter retains ownership of its final exponent
+budget, including valid down-conversions such as `100e100 mg`.
+
+Run checks with the pinned project Python and `-B`:
+
+```sh
+python3 -B -m unittest tests.test_alden_time_normalization tests.test_alden_quantity_normalization tests.test_alden_normalization_evidence tests.test_alden_body_normalization tests.test_alden_body_details -v
+python3 -B scripts/verify_alden_body_normalization.py --output /absolute/private/fresh/body-verification.json
+```
+
+The verifier checks current and restored source and rejects six deliberately
+broken source copies: lost signs, wrong magnitude, wrong UTF-16 offsets, malformed
+grouping admitted, guessed century and URL numbers admitted. Mutations occur only
+in temporary copies and the working parser remains unchanged. Tests include 112
+generated standalone magnitude cases and ten compound cases using independent
+integer sum/product oracles. These are bounded checks, not a theorem, a full
+Unicode grammar audit, independent semantic gold or an installed product result.
+
+Offline evaluation of two saved canonical source pairs (four records, two unique
+bodies) verifies exact body binding and spans. It is not fresh acquisition or
+current permission revalidation. A synthetic URL-only scan forces complete
+traversal without hitting the candidate cap; its CPU timings are separate from
+whole-app latency, resources and any before/after improvement claim.
+
+Application regressions include committed version changes, project/native grant
+revocation, native revision changes, stored-body corruption, archive substitution,
+late entity projection and legacy schema reads. Frontend regressions cover exact
+parser output, malformed packets, emoji offsets, delayed digest cancellation,
+literal HTML, bounded disclosures and canonical IDs in the unified graph.
+The pure-parser complexity discussion excludes the caller's database queries and
+bounded archive revalidation; it is not a whole-popup performance claim.
+
+Representative independent date/quantity/temporal gold, installed UI readback and
+external-review/release evidence remain separate promotion gates. Installation
+and runtime evidence are recorded in the task's current delivery report, not
+inferred from local tests. No source merges, semantic relations or expired-job
+decisions follow from this parser alone.
diff --git a/scripts/alden_body_normalization.py b/scripts/alden_body_normalization.py
new file mode 100644
index 00000000..73215910
--- /dev/null
+++ b/scripts/alden_body_normalization.py
@@ -0,0 +1,260 @@
+"""Bounded lexical annotations of supplied text, never facts or merge decisions.
+
+Offsets index the exact supplied Python string (Unicode code points), not NFC,
+UTF-8 bytes or UTF-16 units. Callers must bind the digest to a permitted current
+source/version before exposing annotations. This parser performs no I/O.
+"""
+from decimal import Context, Decimal, DecimalException, Inexact, InvalidOperation, localcontext
+import hashlib
+import heapq
+import re
+import unicodedata
+
+from alden_quantity_normalization import normalize_declared_quantity
+from alden_time_normalization import normalize_declared_time
+
+POLICY = 'body-notation-candidates-v1'
+MAX_BODY_CHARS = 131072
+MAX_CANDIDATES = 64
+MAX_TOKEN_CHARS = 128
+_SIGN_TRANSLATION = str.maketrans('−-﹣+﹢', '---++')
+_H = r'[ \t\u00a0]*'
+_NUMBER = re.compile(r'(?:[0-9]{1,3}(?:,[0-9]{3})+|[0-9]+)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\Z')
+_URL = re.compile(r'https?://[^\s<>]+', re.IGNORECASE)
+_CLOCK = r'(?:[Tt ][0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:[.,][0-9]{1,9})?)?(?:[Zz]|[+-][0-9]{2}:[0-9]{2}|[ \t]+[A-Za-z]{1,8})?)'
+_DATE = re.compile(
+ r'(?[0-9]{4}|[0-9]{2})년' + _H + r'(?P[0-9]{1,2})월' + _H + r'(?P[0-9]{1,2})일'
+ r'|(?P[0-9]{4})(?P[-/.])(?P[0-9]{1,2})(?P=sep)(?P[0-9]{1,2}))'
+ r'(?P' + _CLOCK + r')?(?![A-Za-z0-9_/:]|\.[0-9])')
+_SPECIAL_UNITS = {
+ '원': ('money_won_unspecified', '원'), 'KRW': ('money_KRW', 'KRW'),
+ 'USD': ('money_USD', 'USD'), 'EUR': ('money_EUR', 'EUR'), 'JPY': ('money_JPY', 'JPY'),
+ '명': ('person_count', '명'), '개': ('item_count', '개'), '건': ('case_count', '건'), '회': ('occurrence_count', '회'),
+ '%': ('percent', '%'), '%p': ('percentage_point', '%p'), '%포인트': ('percentage_point', '%p'),
+}
+_ALIASES = {'초': 's', '분': 'min', '시간': 'h'}
+_SI = ('GiB', 'MiB', 'KiB', 'Gbit', 'Mbit', 'kbit', 'bit', 'GB', 'MB', 'kB', 'B',
+ 'kg', 'mg', 'Mg', 'µg', 'μg', 'g', 'km', 'cm', 'mm', 'm', 'min', 'ms', 'µs', 'μs', 's', 'h')
+_UNITS = '|'.join(re.escape(unit) for unit in sorted(set(_SI) | _SPECIAL_UNITS.keys() | _ALIASES.keys(), key=lambda value: (-len(value), value)))
+_RUN = r'(?:[+\-−-﹣+﹢]' + _H + r')?[0-9][0-9.,eE+\-−-﹣+﹢~~–—조억만천백십 \t\u00a0]{0,127}'
+_QUANTITY = re.compile(r'(?' + _RUN + r')' + _H + r'(?P' + _UNITS + r')(?![A-Za-z%])')
+_BARE_SCALED = re.compile(r'(?' + _RUN + r')')
+_BIG = {'조': 10**12, '억': 10**8, '만': 10**4}
+_SMALL = {'천': 1000, '백': 100, '십': 10}
+
+
+def _coefficient(value):
+ if not _NUMBER.fullmatch(value):
+ raise ValueError('malformed_number')
+ exponent = re.search(r'[eE]([+-]?[0-9]+)\Z', value)
+ if exponent and (len(exponent[1].lstrip('+-')) > 3 or abs(int(exponent[1])) > 100):
+ raise ValueError('exponent_out_of_budget')
+ return Decimal(value.replace(',', ''))
+
+
+def _group(value):
+ total, start, previous = Decimal(0), 0, 10000
+ for index, character in enumerate(value):
+ if character not in _SMALL:
+ continue
+ scale = _SMALL[character]
+ if scale >= previous or index == start:
+ raise ValueError('ambiguous_scale_sequence')
+ total += _coefficient(value[start:index]) * scale
+ start, previous = index + 1, scale
+ if start < len(value):
+ total += _coefficient(value[start:])
+ elif start == 0:
+ raise ValueError('missing_number')
+ return total
+
+
+def _scalar(raw):
+ if len(raw) > MAX_TOKEN_CHARS or re.search(r'[0-9][ \t\u00a0]+[0-9]', raw):
+ raise ValueError('number_budget_or_spacing')
+ value = re.sub(r'[ \t\u00a0]', '', raw).translate(_SIGN_TRANSLATION)
+ sign = -1 if value.startswith('-') else 1
+ if value.startswith(('+', '-')):
+ value = value[1:]
+ if not value:
+ raise ValueError('missing_number')
+ total, start, previous = Decimal(0), 0, 10**16
+ for index, character in enumerate(value):
+ if character not in _BIG:
+ continue
+ scale = _BIG[character]
+ if scale >= previous or index == start:
+ raise ValueError('ambiguous_scale_sequence')
+ total += _group(value[start:index]) * scale
+ start, previous = index + 1, scale
+ if start < len(value):
+ total += _group(value[start:])
+ elif start == 0:
+ raise ValueError('missing_number')
+ total *= sign
+ total = total.normalize()
+ if abs(total.as_tuple().exponent) > 100:
+ raise ValueError('exponent_out_of_budget')
+ rendered = format(total, 'f') if total else '0'
+ if len(rendered) > 128:
+ raise ValueError('canonical_value_out_of_budget')
+ return rendered
+
+
+def _exact_scalar(raw):
+ # Private exact context: caller precision, exponent limits and traps cannot
+ # silently round a money/count expression or change its interpretation.
+ exact = Context(prec=160, Emin=-1000, Emax=1000, traps=[Inexact, InvalidOperation])
+ with localcontext(exact):
+ return _scalar(raw)
+
+
+def _normalize(raw, unit):
+ try:
+ if unit not in _SPECIAL_UNITS and not any(character in raw for character in (*_BIG, *_SMALL)):
+ if len(raw) > MAX_TOKEN_CHARS or re.search(r'[0-9][ \t\u00a0]+[0-9]', raw):
+ raise ValueError('number_budget_or_spacing')
+ literal = re.sub(r'[ \t\u00a0]', '', raw).translate(_SIGN_TRANSLATION)
+ unsigned = literal[1:] if literal.startswith(('+', '-')) else literal
+ _coefficient(unsigned)
+ # Preserve the original declared exponent for the existing unit
+ # converter: e.g. 100e100 mg may validly down-convert to 1e99 g.
+ return normalize_declared_quantity(literal.replace(',', ''), _ALIASES.get(unit, unit))
+ value = _exact_scalar(raw)
+ if unit in _SPECIAL_UNITS:
+ dimension, canonical_unit = _SPECIAL_UNITS[unit]
+ return {'status': 'normalized', 'canonical_value': value, 'canonical_unit': canonical_unit,
+ 'dimension': dimension, 'reason': None}
+ return normalize_declared_quantity(value, _ALIASES.get(unit, unit))
+ except (ValueError, DecimalException) as error:
+ return {'status': 'invalid', 'canonical_value': None, 'canonical_unit': None,
+ 'dimension': None, 'reason': str(error) if isinstance(error, ValueError) else 'exact_arithmetic_budget'}
+
+
+def _quantity_value(raw, unit):
+ separators = [index for index, char in enumerate(raw)
+ if char in '~~–—' or char == '-' and index and raw[index - 1] not in 'eE']
+ ranges = []
+ for index in separators:
+ first, last = raw[:index].strip(), raw[index + 1:].strip()
+ left, right = _normalize(first, unit), _normalize(last, unit)
+ if left['status'] == right['status'] == 'normalized':
+ ranges.append((left, right, raw[index]))
+ if len(ranges) == 1:
+ left, right, marker = ranges[0]
+ order = 'descending' if Decimal(left['canonical_value']) > Decimal(right['canonical_value']) else 'nondecreasing'
+ return {'kind': 'quantity_relation' if marker == '-' else 'quantity_range',
+ 'status': 'ambiguous' if marker == '-' else 'normalized',
+ 'reason': 'hyphen_may_be_range_or_subtraction' if marker == '-' else None,
+ 'first': left, 'last': right, 'range_marker': marker, 'written_order': order}
+ if separators:
+ return {'kind': 'quantity', 'status': 'ambiguous', 'canonical_value': None,
+ 'canonical_unit': None, 'dimension': None, 'reason': 'range_not_fully_resolved'}
+ return {'kind': 'quantity', **_normalize(raw, unit)}
+
+
+def _dates(body):
+ for match in _DATE.finditer(body):
+ year = match['ky'] or match['iy']
+ if len(year) == 2:
+ result = {'status': 'ambiguous', 'canonical': None, 'reason': 'century_not_declared', 'precision': 'day', 'basis': 'body_notation'}
+ else:
+ month, day = match['km'] or match['im'], match['kd'] or match['id']
+ iso = f'{year}-{int(month):02d}-{int(day):02d}'
+ if match['clock']:
+ iso += 'T' + match['clock'][1:]
+ result = normalize_declared_time(iso)
+ if not match['clock'] and re.match(r'[Tt ][0-9]{2}:', body[match.end():match.end() + 7]):
+ result = {'status': 'unsupported', 'canonical': None, 'reason': 'time_suffix_not_fully_parsed', 'precision': None, 'basis': 'body_notation'}
+ yield {'kind': 'time', 'start': match.start(), 'end': match.end(), 'raw': match[0], **result}
+
+
+def _numeric_prefix(body, start):
+ previous = start - 1
+ while previous >= 0 and body[previous] in ' \t\u00a0':
+ previous -= 1
+ return previous >= 0 and (body[previous] in '0123456789+−-﹣+﹢-~~–—조억만천백십'
+ or unicodedata.category(body[previous]) == 'Pd'
+ or body[previous] in '.,' and previous > 0 and body[previous - 1].isdigit())
+
+
+def _quantities(body):
+ for match in _QUANTITY.finditer(body):
+ # A longer expression or separated sign must not yield a positive tail.
+ if _numeric_prefix(body, match.start()):
+ continue
+ raw, unit = match['number'].strip(), match['unit']
+ result = _quantity_value(raw, unit)
+ yield {'start': match.start(), 'end': match.end(), 'raw': match[0], 'source_unit': unit,
+ 'source_sign': 'negative' if raw.startswith(('-', '−', '-', '﹣')) else 'explicit_positive' if raw.startswith(('+', '+', '﹢')) else 'unsigned',
+ **result}
+
+
+def _untyped_numbers(body):
+ for match in _BARE_SCALED.finditer(body):
+ raw = match[0].rstrip(' \t\u00a0')
+ if not any(character in raw for character in (*_BIG, *_SMALL)) or _numeric_prefix(body, match.start()):
+ continue
+ end = match.start() + len(raw)
+ if end < len(body) and body[end] in '0123456789.,eE+−-﹣+﹢-~~–—조억만천백십':
+ continue # Never normalize a budget-cut prefix as a whole number.
+ try:
+ value = _exact_scalar(raw)
+ except (ValueError, DecimalException):
+ value = None
+ yield {'kind': 'untyped_number', 'start': match.start(), 'end': end, 'raw': raw,
+ 'status': 'ambiguous', 'reason': 'unit_not_declared', 'source_unit': None,
+ 'canonical_unit': None, 'dimension': None,
+ 'canonical_value': value}
+
+
+def analyze_body_fields(body):
+ """Extract bounded syntax candidates. Neither absence nor conversion is truth."""
+ if not isinstance(body, str):
+ raise ValueError('body_text_required')
+ if len(body) > MAX_BODY_CHARS:
+ return {'policy': POLICY, 'state': 'body_budget_exceeded', 'body_sha256': None,
+ 'body_characters': len(body), 'candidates': [], 'truncated': True,
+ 'offset_basis': 'exact_supplied_unicode_codepoints', 'semantic_validity': 'not_assessed',
+ 'client_offset_basis': 'exact_supplied_utf16_code_units',
+ 'source_authorization': 'caller_must_bind_permitted_current_source_version'}
+ try:
+ body_hash = hashlib.sha256(body.encode('utf-8')).hexdigest()
+ except UnicodeEncodeError:
+ raise ValueError('body_unicode_invalid') from None
+ urls = [(match.start(), match.end()) for match in _URL.finditer(body)]
+ candidates, url_index = [], 0
+ merged = heapq.merge(_dates(body), _quantities(body), _untyped_numbers(body),
+ key=lambda item: (item['start'], -item['end']))
+ truncated = False
+ for candidate in merged:
+ if candidates and candidate['start'] < candidates[-1]['end']:
+ continue # Prefer the full typed span over its untyped subexpression.
+ while url_index < len(urls) and urls[url_index][1] <= candidate['start']:
+ url_index += 1
+ if url_index < len(urls) and urls[url_index][0] < candidate['end'] and candidate['start'] < urls[url_index][1]:
+ continue
+ if len(candidates) == MAX_CANDIDATES:
+ truncated = True
+ break
+ assert body[candidate['start']:candidate['end']] == candidate['raw']
+ candidates.append(candidate)
+ # JS strings use UTF-16. Compute requested boundary offsets in one pass,
+ # rather than encoding every candidate's potentially long body prefix.
+ points = sorted({item[key] for item in candidates for key in ('start', 'end')})
+ converted, cursor, code_units = {}, 0, 0
+ for point in points:
+ while cursor < point:
+ code_units += 2 if ord(body[cursor]) > 0xffff else 1
+ cursor += 1
+ converted[point] = code_units
+ for candidate in candidates:
+ candidate['utf16_start'] = converted[candidate['start']]
+ candidate['utf16_end'] = converted[candidate['end']]
+ return {'policy': POLICY, 'state': 'bounded_candidates' if truncated else 'supported_notation_scan_complete',
+ 'body_sha256': body_hash, 'body_characters': len(body),
+ 'offset_basis': 'exact_supplied_unicode_codepoints', 'semantic_validity': 'not_assessed',
+ 'client_offset_basis': 'exact_supplied_utf16_code_units',
+ 'source_authorization': 'caller_must_bind_permitted_current_source_version',
+ 'candidates': candidates, 'truncated': truncated}
diff --git a/scripts/alden_collection.py b/scripts/alden_collection.py
index 1413e84c..6a5eb2a0 100644
--- a/scripts/alden_collection.py
+++ b/scripts/alden_collection.py
@@ -1362,7 +1362,7 @@ def incident_scope(current_ids):
row = db.execute(exact + "SELECT " + fields + " FROM shown s JOIN versions v ON v.id=s.visible_version WHERE s.id=?", (focus, *args, focus)).fetchone()
if row is None:
raise ValueError("collection_graph_focus_not_in_scope")
- return self._record_details(db, row, expected_version)
+ return self._record_details(db, row, expected_version, projects)
json_node = """json_object('id',s.id,'platform',s.platform,'original_id',s.original_id,
'visible_version',s.visible_version,'target_id',s.target_id,'collected_at',s.collected_at,
'label',alden_display_label(v.label,v.body),'body',substr(v.body,1,2400),'metadata',json_object('kind',substr(CAST(json_extract(v.metadata,'$.kind') AS TEXT),1,256)),
@@ -1577,13 +1577,13 @@ def incident_scope(current_ids):
'projection': 'current_graph_references'}
if details and focus:
row = next(r for r in rows if r["id"] == focus)
- detail = self._record_details(db, row, expected_version)
+ detail = self._record_details(db, row, expected_version, projects)
if detail["ok"] is not True:
return detail
result["details"] = detail["details"]
return result
- def _record_details(self, db, row, expected_version) -> dict:
+ def _record_details(self, db, row, expected_version, projects) -> dict:
if not db.execute('SELECT alden_source_allowed(?,?,?)',
(row['target_id'], row['id'], row['visible_version'])).fetchone()[0]:
return {'ok': False, 'error': 'collection_source_authorization_required'}
@@ -1609,15 +1609,75 @@ def _record_details(self, db, row, expected_version) -> dict:
display_label = " · ".join(str(record[key]) for key in ("handle", "author", "date") if record.get(key))
if not display_label:
display_label = row["original_id"]
- return {"ok": True, "details": {"node_id": row["id"], "basis": "source_record", "summary": row["label"], "display_label": display_label,
- "body": body[:12000], "truncated": len(body) > 12000,
+ visible_body = body[:12000]
+ from alden_body_normalization import analyze_body_fields, POLICY as BODY_NOTATION_POLICY
+ from alden_content_evidence import content_evidence_class
+ metadata = json.loads(row['metadata'])
+ evidence_class = content_evidence_class(metadata,body,source=record,
+ body_source='retained_record.localOriginalText' if body_format=='retained_original_text' else 'stored_body')
+ analysis = analyze_body_fields(visible_body) if self.schema >= 3 and evidence_class=='content_candidate' else None
+ if analysis is not None and (analysis.get('policy') != BODY_NOTATION_POLICY
+ or analysis.get('body_sha256') != digest(visible_body.encode())
+ or analysis.get('body_characters') != len(visible_body)
+ or analysis.get('semantic_validity') != 'not_assessed'):
+ raise RuntimeError('collection_body_notation_binding_invalid')
+ result = {"ok": True, "details": {"node_id": row["id"], "basis": "source_record", "summary": row["label"], "display_label": display_label,
+ "body": visible_body, "truncated": len(body) > 12000,
"body_format": body_format,
"text_projection": projected['projection'],
"reading_projection": reading_tail_presentation(body, record),
"version": row["visible_version"], "collected_at": row["collected_at"],
"raw_sha256": row["raw_sha256"], "source_url": row["source_url"],
"target_id": row["target_id"], "platform": row["platform"],
- "capture": self._source_capture_reference(db, row)}}
+ "capture": self._source_capture_reference(db, row),
+ "body_notation": {"binding": {"basis": "verified_source_record_detail",
+ "document_id": row['id'], "target_id": row['target_id'],
+ "version": row['visible_version'], "raw_sha256": row['raw_sha256'],
+ "body_sha256": analysis['body_sha256'],
+ "body_scope": "detail_body_excerpt" if len(body) > 12000 else "detail_body"},
+ "analysis": analysis} if analysis is not None else None}}
+ self._verify_current_detail(result['details'], projects)
+ return result
+
+ def _verify_current_detail(self, details, projects):
+ """A fresh read after parsing/projection, never the earlier graph snapshot."""
+ binding = {'document_id':details['node_id'],'target_id':details['target_id'],
+ 'version':details['version'],'raw_sha256':details['raw_sha256']}
+ marks = ','.join('?' for _ in projects)
+ availability = 'm.availability' if self.schema >= 3 else "'available'"
+ with self.database() as current:
+ current.execute('PRAGMA query_only=ON')
+ if not current.in_transaction:
+ current.execute('BEGIN')
+ row = current.execute('''SELECT m.current_version,v.*,d.availability AS document_availability,
+ ''' + availability + ''' AS membership_availability,
+ EXISTS(SELECT 1 FROM target_projects p WHERE p.target_id=m.target_id
+ AND p.permission!='denied' AND p.project IN (''' + marks + ''')) AS permitted,
+ alden_source_allowed(m.target_id,m.document_id,m.current_version) AS source_allowed
+ FROM memberships m JOIN documents d ON d.id=m.document_id
+ JOIN versions v ON v.id=m.current_version
+ WHERE m.target_id=? AND m.document_id=?''', (*projects,binding['target_id'],binding['document_id'])).fetchone()
+ if row is None or row['document_availability'] != 'available' or row['membership_availability'] != 'available':
+ raise RuntimeError('collection_graph_source_unavailable')
+ if not row['permitted'] or not row['source_allowed']:
+ raise RuntimeError('collection_source_authorization_changed')
+ if row['current_version'] != binding['version']:
+ raise RuntimeError('collection_graph_version_changed')
+ if row['raw_sha256'] != binding['raw_sha256']:
+ raise RuntimeError('collection_source_integrity')
+ if self.schema < 3 or row['processing_version']=='legacy':
+ details['body_notation'] = None
+ else:
+ metadata = json.loads(row['metadata'])
+ if not isinstance(metadata,dict):
+ raise RuntimeError('collection_source_integrity')
+ projection = digest(encoded([row['label'],row['body'],{key:value for key,value in metadata.items() if key!='source'}]))
+ version = identity('version',encoded([binding['document_id'],row['raw_sha256'],row['processing_version'],projection]).decode())
+ if row['projection_sha256'] != projection or version != row['current_version']:
+ raise RuntimeError('collection_source_integrity')
+ raw = self._verified_source_blob(self.blobs,row['raw_path'],MAX_RECORD_BYTES)
+ if digest(raw) != row['raw_sha256']:
+ raise RuntimeError('collection_source_integrity')
@staticmethod
def _verified_source_blob(folder: Path, name: str, budget: int) -> bytes:
@@ -1885,5 +1945,7 @@ def read_action(state_root: Path, action: str, query: str | None = None, *,
with store.database() as db:
if store._source_authority_snapshot(db, projects) != authority:
raise RuntimeError('collection_source_authorization_changed')
+ if result.get('details',{}).get('basis') == 'source_record':
+ store._verify_current_detail(result['details'],projects)
return result
raise ValueError("collection_action_invalid")
diff --git a/scripts/prepare-auto-reply-session-runtime.py b/scripts/prepare-auto-reply-session-runtime.py
index 24524605..e8f36ec7 100755
--- a/scripts/prepare-auto-reply-session-runtime.py
+++ b/scripts/prepare-auto-reply-session-runtime.py
@@ -86,6 +86,7 @@ def _default_state_root() -> Path:
"alden_graph_quality.py",
"alden_annotation_candidates.py",
"alden_normalization_evidence.py",
+ "alden_body_normalization.py",
"alden_time_normalization.py",
"alden_quantity_normalization.py",
"alden_entity_projection.py",
diff --git a/scripts/verify_alden_body_normalization.py b/scripts/verify_alden_body_normalization.py
new file mode 100644
index 00000000..d57b3744
--- /dev/null
+++ b/scripts/verify_alden_body_normalization.py
@@ -0,0 +1,78 @@
+"""Bounded checks of the real parser and isolated, deliberately broken variants."""
+from pathlib import Path
+import argparse
+import hashlib
+import json
+import os
+import subprocess
+import sys
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[1]
+SOURCE = ROOT / 'scripts/alden_body_normalization.py'
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--output', type=Path)
+ args = parser.parse_args()
+ original = SOURCE.read_bytes()
+ source = original.decode()
+ replacements = {
+ 'lost_negative_sign': ("sign = -1 if value.startswith('-') else 1", 'sign = 1'),
+ 'wrong_magnitude': ("'만': 10**4", "'만': 10**3"),
+ 'wrong_js_offsets': ('code_units += 2 if ord(body[cursor]) > 0xffff else 1', 'code_units += 1'),
+ 'malformed_grouping_accepted': ('(?:,[0-9]{3})+', '(?:,[0-9]{1,3})+'),
+ 'guessed_century': ("year = match['ky'] or match['iy']", "year = match['ky'] or match['iy']\n if len(year) == 2: year = '20' + year"),
+ 'url_numbers_admitted': ("if url_index < len(urls) and urls[url_index][0] < candidate['end'] and candidate['start'] < urls[url_index][1]:", 'if False:'),
+ }
+ variants = {'current': source}
+ for name, (before, after) in replacements.items():
+ assert source.count(before) == 1, name + ': recheck code-to-property correspondence'
+ variants[name] = source.replace(before, after)
+ variants['restored'] = source
+ results = {}
+ if args.output:
+ assert args.output.is_absolute()
+ args.output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ assert not args.output.exists()
+ with tempfile.TemporaryDirectory(prefix='alden-body-verification-') as folder:
+ work = Path(folder)
+ (work / 'scripts').mkdir()
+ (work / 'tests').mkdir()
+ for relative in ['scripts/alden_quantity_normalization.py', 'scripts/alden_time_normalization.py', 'tests/test_alden_body_normalization.py']:
+ (work / relative).write_bytes((ROOT / relative).read_bytes())
+ for name, text in variants.items():
+ (work / 'scripts/alden_body_normalization.py').write_text(text)
+ run = subprocess.run([sys.executable, '-B', '-m', 'unittest', 'discover', '-s', 'tests', '-p', 'test_alden_body_normalization.py', '-v'],
+ cwd=work, capture_output=True, text=True, timeout=30,
+ env={**os.environ, 'PYTHONDONTWRITEBYTECODE': '1', 'PYTHONPATH': str(work / 'scripts')})
+ expected = name in ('current', 'restored')
+ results[name] = {'exit_code': run.returncode, 'passed': run.returncode == 0,
+ 'source_sha256': hashlib.sha256(text.encode()).hexdigest()}
+ if args.output:
+ path = args.output.with_name('mutation-' + name + '.log')
+ with path.open('x') as handle:
+ path.chmod(0o600)
+ handle.write(run.stdout + run.stderr)
+ assert (run.returncode == 0) == expected, name + ': mutation sensitivity or current parser check failed'
+ assert SOURCE.read_bytes() == original
+ report = {'scope': 'Real parser source and six isolated mutations; bounded unit/generated-input checks, not a theorem or semantic gold.',
+ 'source_sha256': hashlib.sha256(original).hexdigest(),
+ 'covered': ['exact source/codepoint/UTF16 span equality', 'signs', 'Korean magnitudes',
+ 'grouping syntax', 'no century guess', 'URL exclusion'],
+ 'bounds': {'body_characters': 131072, 'candidates_per_body': 64, 'token_characters': 128,
+ 'integer_oracle_generated_cases': 112, 'compound_integer_oracle_cases': 10},
+ 'results': results, 'python_version': sys.version, 'production_source_modified': False,
+ 'limits': ['No fact extraction/authorization/current-version integration, physical UI, liveness, full Unicode grammar or independent precision/recall proof.',
+ 'Range/subtraction, relative dates, implicit timezone/currency and unsupported notation stay unresolved.']}
+ if args.output:
+ with args.output.open('x') as handle:
+ args.output.chmod(0o600)
+ json.dump(report, handle, ensure_ascii=False, indent=2)
+ handle.write('\n')
+ print(json.dumps({'current_and_restored_passed': True, 'rejected_mutants': len(replacements), 'source_unchanged': True}))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tests/test_alden_body_details.py b/tests/test_alden_body_details.py
new file mode 100644
index 00000000..07527f03
--- /dev/null
+++ b/tests/test_alden_body_details.py
@@ -0,0 +1,157 @@
+from pathlib import Path
+from tempfile import TemporaryDirectory
+import hashlib
+import json
+import sys
+import unittest
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
+from alden_collection import CollectionStore, read_action, encoded, digest
+from alden_body_normalization import analyze_body_fields
+
+
+class BodyDetailTests(unittest.TestCase):
+ def setUp(self):
+ temporary = TemporaryDirectory(dir='/private/tmp')
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.store = CollectionStore(self.root)
+ self.target = self.store.register(platform='graph',original_id='source',kind='source',label='자료',projects=['project'])
+ self.body = '😀 기한 2026년 2월 23일, 연봉 5천만원, 수량 −5명'
+ self.ingest(self.body)
+ self.node = self.store.graph_page(projects=['project'])['nodes'][0]
+
+ def ingest(self, body, **extra):
+ self.store.ingest(self.target,[{'platform':'graph','original_id':'source-record','label':'자료',
+ 'text':body,'raw':{'localOriginalText':body},**extra}])
+
+ def details(self, **kwargs):
+ return read_action(self.root,'collection-graph',json.dumps({'projects':['project'],
+ 'focus':self.node['id'],'hops':0,'details':True,'expected_version':self.node['source_version']}),**kwargs)
+
+ def test_actual_read_boundary_binds_the_exact_displayed_body_and_source_receipt(self):
+ detail = self.details()['details']
+ note = detail['body_notation']
+ self.assertEqual(note['binding'],{'basis':'verified_source_record_detail','document_id':detail['node_id'],
+ 'target_id':detail['target_id'],'version':detail['version'],'raw_sha256':detail['raw_sha256'],
+ 'body_sha256':hashlib.sha256(detail['body'].encode()).hexdigest(),'body_scope':'detail_body'})
+ self.assertEqual(note['analysis']['body_sha256'],note['binding']['body_sha256'])
+ self.assertEqual(len(note['analysis']['candidates']),3)
+ for item in note['analysis']['candidates']:
+ self.assertEqual(detail['body'][item['start']:item['end']],item['raw'])
+
+ def test_annotations_cover_the_returned_excerpt_not_hidden_source_tail(self):
+ self.ingest('가' * 12000 + '\n수량 8명')
+ self.node = self.store.graph_page(projects=['project'])['nodes'][0]
+ detail = self.details()['details']
+ self.assertTrue(detail['truncated'])
+ self.assertEqual(detail['body_notation']['binding']['body_scope'],'detail_body_excerpt')
+ self.assertEqual(detail['body_notation']['analysis']['candidates'],[])
+
+ def test_metadata_only_records_are_not_annotated_as_body_content(self):
+ self.ingest('본문을 획득하지 않은 파일 목록 50GB',content_indexed=False)
+ self.node = self.store.graph_page(projects=['project'])['nodes'][0]
+ self.assertIsNone(self.details()['details']['body_notation'])
+
+ def test_committed_version_change_during_analysis_rejects_old_packet(self):
+ def changed(body):
+ result = analyze_body_fields(body)
+ self.ingest('개정된 수량은 7명입니다.')
+ return result
+ with patch('alden_body_normalization.analyze_body_fields',side_effect=changed):
+ with self.assertRaisesRegex(RuntimeError,'collection_graph_version_changed'):
+ self.details()
+
+ def test_permission_revocation_during_analysis_rejects_old_packet(self):
+ def revoked(body):
+ result = analyze_body_fields(body)
+ with self.store.database() as db:
+ db.execute("UPDATE target_projects SET permission='denied' WHERE target_id=?",(self.target,))
+ return result
+ with patch('alden_body_normalization.analyze_body_fields',side_effect=revoked):
+ with self.assertRaisesRegex(RuntimeError,'collection_source_authorization_changed'):
+ self.details()
+
+ def protected_source(self):
+ with self.store.database() as db:
+ db.execute("UPDATE target_projects SET permission='denied' WHERE target_id=?",(self.target,))
+ self.target = self.store.register(platform='telegram',original_id='protected',kind='local-db',
+ label='보호된 자료',projects=['project'])
+ self.store.source_access = lambda *args: True
+ self.ingest(self.body)
+ self.node = self.store.graph_page(projects=['project'])['nodes'][0]
+
+ def test_native_source_grant_revocation_during_analysis_rejects_the_packet(self):
+ self.protected_source()
+ allowed = True
+ def revoked(body):
+ nonlocal allowed
+ result = analyze_body_fields(body)
+ allowed = False
+ return result
+ with patch('alden_body_normalization.analyze_body_fields',side_effect=revoked):
+ with self.assertRaisesRegex(RuntimeError,'collection_source_authorization_changed'):
+ self.details(source_access=lambda *args: allowed,source_revision=lambda *args:'a'*64)
+
+ def test_native_source_revision_change_during_analysis_rejects_the_packet(self):
+ self.protected_source()
+ revision = 'a'*64
+ def changed(body):
+ nonlocal revision
+ result = analyze_body_fields(body)
+ revision = 'b'*64
+ return result
+ with patch('alden_body_normalization.analyze_body_fields',side_effect=changed):
+ with self.assertRaisesRegex(RuntimeError,'collection_source_authorization_changed'):
+ self.details(source_access=lambda *args:True,source_revision=lambda *args:revision)
+
+ def test_changed_stored_body_without_new_version_is_an_integrity_error(self):
+ def corrupted(body):
+ result = analyze_body_fields(body)
+ with self.store.database() as db:
+ db.execute('UPDATE versions SET body=? WHERE id=?',('forged 99명',self.node['source_version']))
+ return result
+ with patch('alden_body_normalization.analyze_body_fields',side_effect=corrupted):
+ with self.assertRaisesRegex(RuntimeError,'collection_source_integrity'):
+ self.details()
+
+ def test_raw_path_swap_cannot_borrow_another_valid_archive(self):
+ def swapped(body):
+ result = analyze_body_fields(body)
+ raw = encoded({'localOriginalText':'unrelated 99명'})
+ name = digest(raw) + '.json'
+ (self.store.blobs / name).write_bytes(raw)
+ with self.store.database() as db:
+ db.execute('UPDATE versions SET raw_path=? WHERE id=?',(name,self.node['source_version']))
+ return result
+ with patch('alden_body_normalization.analyze_body_fields',side_effect=swapped):
+ with self.assertRaisesRegex(RuntimeError,'collection_source_integrity'):
+ self.details()
+
+ def test_final_read_rechecks_after_entity_projection(self):
+ def project(payload,*args):
+ self.ingest('다른 버전 9명')
+ return payload
+ with patch('alden_entity_projection.project_groups',side_effect=project):
+ with self.assertRaisesRegex(RuntimeError,'collection_graph_version_changed'):
+ self.details()
+
+ def test_mismatched_parser_body_digest_is_not_exposed(self):
+ result = analyze_body_fields(self.body)
+ result['body_sha256'] = '0' * 64
+ with patch('alden_body_normalization.analyze_body_fields',return_value=result):
+ with self.assertRaisesRegex(RuntimeError,'collection_body_notation_binding_invalid'):
+ self.details()
+
+ def test_schema_two_can_still_read_without_new_annotations(self):
+ with self.store.database() as db:
+ db.execute('ALTER TABLE memberships DROP COLUMN availability')
+ db.execute("UPDATE meta SET value='2' WHERE key='schema'")
+ detail = self.details()['details']
+ self.assertEqual(detail['body'],self.body)
+ self.assertIsNone(detail['body_notation'])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_alden_body_normalization.py b/tests/test_alden_body_normalization.py
new file mode 100644
index 00000000..46004d9b
--- /dev/null
+++ b/tests/test_alden_body_normalization.py
@@ -0,0 +1,187 @@
+import hashlib
+from decimal import localcontext
+from pathlib import Path
+import sys
+import unittest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
+from alden_body_normalization import analyze_body_fields, MAX_BODY_CHARS, MAX_CANDIDATES
+
+
+class BodyNormalizationTests(unittest.TestCase):
+ def candidates(self, body):
+ report = analyze_body_fields(body)
+ self.assertEqual(report['body_sha256'], hashlib.sha256(body.encode()).hexdigest())
+ self.assertEqual(report['semantic_validity'], 'not_assessed')
+ for item in report['candidates']:
+ self.assertEqual(body[item['start']:item['end']], item['raw'])
+ self.assertEqual(body.encode('utf-16-le')[item['utf16_start'] * 2:item['utf16_end'] * 2].decode('utf-16-le'), item['raw'])
+ self.assertGreater(item['end'], item['start'])
+ return report['candidates']
+
+ def test_source_offsets_are_exact_codepoints_without_unicode_or_line_rewriting(self):
+ body = '😀 가\r\n기한 2026년 2월 23일, 수량 −5 명'
+ result = self.candidates(body)
+ self.assertEqual([item['raw'] for item in result], ['2026년 2월 23일', '−5 명'])
+ self.assertEqual(result[0]['canonical'], '2026-02-23')
+ self.assertEqual(result[1]['canonical_value'], '-5')
+ self.assertEqual(result[1]['source_sign'], 'negative')
+ self.assertGreater(result[0]['utf16_start'], result[0]['start'])
+
+ def test_short_year_and_local_clock_remain_ambiguous(self):
+ short = self.candidates('기한 26년 2월 23일까지')[0]
+ self.assertEqual((short['status'], short['canonical']), ('ambiguous', None))
+ self.assertEqual(short['reason'], 'century_not_declared')
+ clock = self.candidates('시간 2026-02-23 12:30')[0]
+ self.assertEqual(clock['status'], 'ambiguous')
+ self.assertIsNone(clock['canonical'])
+
+ def test_sentence_period_is_not_a_date_component(self):
+ for body in ('기한 2026년 2월 23일.', '기한 2026.2.23.'):
+ with self.subTest(body=body):
+ items = self.candidates(body)
+ self.assertEqual(items[0]['canonical'],'2026-02-23')
+ self.assertFalse(items[0]['raw'].endswith('.'))
+ self.assertEqual(self.candidates('기한 2026.2.23.24'),[])
+ self.assertEqual(self.candidates('기한 26년 2월 23일.')[0]['status'],'ambiguous')
+
+ def test_explicit_offset_and_gregorian_validity(self):
+ value = self.candidates('시각 2026-02-23T12:30:00+09:00')[0]
+ self.assertEqual(value['canonical'], '2026-02-23T03:30:00Z')
+ for text, expected in [('2024/2/29', 'normalized'), ('2026.2.29', 'invalid'), ('2026-13-01', 'invalid')]:
+ with self.subTest(text=text):
+ self.assertEqual(self.candidates('일자 ' + text)[0]['status'], expected)
+
+ def test_invalid_datetime_tail_cannot_become_a_normalized_date_only(self):
+ value = self.candidates('시각 2026-02-23 12:30+09:00junk')[0]
+ self.assertNotEqual(value['status'], 'normalized')
+ self.assertIsNone(value['canonical'])
+
+ def test_urls_and_identifiers_are_not_number_sources(self):
+ self.assertEqual(self.candidates('https://example.test/2026-02-23/5kg HTTPS://example.test/?mass=5kg abc2026-02-23def id_10kg 0x10B'), [])
+
+ def test_exact_korean_magnitudes_and_no_currency_jurisdiction_guess(self):
+ values = {
+ '5천만원': '50000000', '1억5000만원': '150000000',
+ '1억 2천만원': '120000000', '3천5백만원': '35000000',
+ '-1억5000만원': '-150000000', '1.5만 명': '15000',
+ '1,234.50 USD': '1234.5', '2.5e1 KRW': '25',
+ }
+ for raw, expected in values.items():
+ with self.subTest(raw=raw):
+ item = self.candidates('값 ' + raw)[0]
+ self.assertEqual(item['status'], 'normalized')
+ self.assertEqual(item['canonical_value'], expected)
+ if raw.endswith('원'):
+ self.assertEqual(item['canonical_unit'], '원')
+ self.assertEqual(item['dimension'], 'money_won_unspecified')
+
+ def test_si_units_use_existing_exact_converter_and_case(self):
+ for raw, expected, unit in [('1.25kg', '1250', 'g'), ('1.25mg', '0.00125', 'g'),
+ ('1Mg', '1000000', 'g'), ('1KiB', '8192', 'bit'), ('2분', '120', 's')]:
+ with self.subTest(raw=raw):
+ item = self.candidates('값 ' + raw)[0]
+ self.assertEqual((item['canonical_value'], item['canonical_unit']), (expected, unit))
+ self.assertEqual(self.candidates('값 10msec 또는 2mb'), [])
+
+ def test_malformed_grouping_scales_and_spacing_never_normalize_a_tail(self):
+ for raw in ['12,34원', '1.2.3kg', '5 10kg', '1백2천원', '2천백만원', '1억만원', '1e999g', '5--+2kg']:
+ with self.subTest(raw=raw):
+ items = self.candidates('값 ' + raw)
+ self.assertTrue(items)
+ self.assertTrue(all(item['status'] != 'normalized' for item in items))
+ self.assertTrue(all(item.get('canonical_value') is None for item in items))
+
+ def test_range_direction_is_preserved_without_sorting_or_truth_claims(self):
+ for raw, first, last, direction in [('10~20kg', '10000', '20000', 'nondecreasing'),
+ ('10~2kg', '10000', '2000', 'descending'),
+ ('−5~-2kg', '-5000', '-2000', 'nondecreasing')]:
+ with self.subTest(raw=raw):
+ item = self.candidates('구간 ' + raw)[0]
+ self.assertEqual(item['kind'], 'quantity_range')
+ self.assertEqual((item['first']['canonical_value'], item['last']['canonical_value']), (first, last))
+ self.assertEqual(item['written_order'], direction)
+
+ def test_hyphen_does_not_resolve_range_versus_subtraction(self):
+ item = self.candidates('수식 10-2kg')[0]
+ self.assertEqual(item['kind'], 'quantity_relation')
+ self.assertEqual(item['status'], 'ambiguous')
+ self.assertEqual(item['reason'], 'hyphen_may_be_range_or_subtraction')
+ self.assertEqual(item['first']['canonical_value'], '10000')
+ self.assertEqual(item['last']['canonical_value'], '2000')
+
+ def test_compound_magnitudes_have_independent_integer_sum_oracle(self):
+ for a in [1, 2, 9]:
+ for b in [1, 35, 9999]:
+ value = self.candidates(f'금액 {a}억{b}만원')[0]
+ self.assertEqual(value['canonical_value'], str(a * 100000000 + b * 10000))
+ value = self.candidates('금액 1조2억3만4천5백6십7원')[0]
+ self.assertEqual(value['canonical_value'], str(10**12 + 2 * 10**8 + 3 * 10**4 + 4567))
+
+ def test_scientific_exponent_minus_is_not_a_range(self):
+ item = self.candidates('측정 1e-2kg')[0]
+ self.assertEqual(item['kind'], 'quantity')
+ self.assertEqual(item['canonical_value'], '10')
+
+ def test_missing_monetary_unit_is_explicit_rather_than_a_currency_guess(self):
+ item = self.candidates('초봉 5천 이상으로 형성됩니다.')[0]
+ self.assertEqual(item['kind'], 'untyped_number')
+ self.assertEqual((item['canonical_value'], item['canonical_unit']), ('5000', None))
+ self.assertEqual(item['status'], 'ambiguous')
+ self.assertEqual(item['reason'], 'unit_not_declared')
+ self.assertEqual(len(self.candidates('연봉 5천만원')), 1)
+
+ def test_existing_unit_downconversion_owns_final_exponent_budget(self):
+ item = self.candidates('측정 100e100 mg')[0]
+ self.assertEqual(item['status'], 'normalized')
+ self.assertEqual(item['canonical_value'], '1' + '0' * 99)
+
+ def test_percent_and_percentage_points_are_distinct(self):
+ values = self.candidates('변화 +5% 및 5%p, −0원')
+ self.assertEqual([item['canonical_unit'] for item in values], ['%', '%p', '원'])
+ self.assertEqual(values[-1]['canonical_value'], '0')
+ self.assertEqual(values[-1]['source_sign'], 'negative')
+
+ def test_fullwidth_and_small_signs_do_not_lose_direction(self):
+ for sign in ['-', '−', '-', '﹣']:
+ item = self.candidates('측정 ' + sign + '5kg')[0]
+ self.assertEqual(item['canonical_value'], '-5000')
+ self.assertEqual(item['source_sign'], 'negative')
+ for sign in ['+', '+', '﹢']:
+ item = self.candidates('수량 ' + sign + '5명')[0]
+ self.assertEqual(item['canonical_value'], '5')
+ self.assertEqual(item['source_sign'], 'explicit_positive')
+ self.assertEqual(self.candidates('미확인 부호 ‐5kg 또는 –5kg'), [])
+
+ def test_callers_decimal_context_cannot_round_results(self):
+ with localcontext() as context:
+ context.prec = 2
+ context.Emin, context.Emax = -2, 2
+ value = self.candidates('금액 123456789.12345만원')[0]
+ self.assertEqual(value['canonical_value'], '1234567891234.5')
+
+ def test_budgets_are_explicit_and_do_not_claim_full_normalization(self):
+ report = analyze_body_fields('가' * (MAX_BODY_CHARS + 1))
+ self.assertEqual(report['state'], 'body_budget_exceeded')
+ self.assertTrue(report['truncated'])
+ self.assertIsNone(report['body_sha256'])
+ report = analyze_body_fields(' '.join('수량 5명' for _ in range(MAX_CANDIDATES + 1)))
+ self.assertEqual(len(report['candidates']), MAX_CANDIDATES)
+ self.assertTrue(report['truncated'])
+
+ def test_invalid_inputs_do_not_produce_annotations(self):
+ for value in [None, 12, True, {}, '\ud800']:
+ with self.subTest(value=repr(value)), self.assertRaises(ValueError):
+ analyze_body_fields(value)
+
+ def test_generated_grouping_and_magnitude_equivalence_with_independent_integer_oracle(self):
+ for coefficient in [0, 1, 9, 99, 999, 1234, 999999]:
+ for magnitude, scale in [('', 1), ('천', 1000), ('만', 10000), ('억', 100000000)]:
+ for sign in ['', '+', '-', '−']:
+ item = self.candidates(f'금액 {sign}{coefficient:,}{magnitude}원')[0]
+ expected = coefficient * scale * (-1 if sign in ('-', '−') else 1)
+ self.assertEqual(item['canonical_value'], str(expected))
+
+
+if __name__ == '__main__':
+ unittest.main()