kc-beta 0.7.3 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +57 -4
  2. package/bin/kc-beta.js +20 -6
  3. package/package.json +3 -2
  4. package/src/agent/engine.js +493 -132
  5. package/src/agent/pipelines/_advance-hints.js +92 -0
  6. package/src/agent/pipelines/_milestone-derive.js +387 -17
  7. package/src/agent/pipelines/initializer.js +4 -1
  8. package/src/agent/pipelines/skill-authoring.js +30 -1
  9. package/src/agent/skill-loader.js +433 -111
  10. package/src/agent/tools/agent-tool.js +2 -2
  11. package/src/agent/tools/consult-skill.js +127 -0
  12. package/src/agent/tools/copy-to-workspace.js +4 -3
  13. package/src/agent/tools/dashboard-render.js +48 -1
  14. package/src/agent/tools/document-parse.js +31 -2
  15. package/src/agent/tools/phase-advance.js +17 -13
  16. package/src/agent/tools/release.js +378 -8
  17. package/src/agent/tools/sandbox-exec.js +65 -8
  18. package/src/agent/tools/worker-llm-call.js +95 -15
  19. package/src/agent/tools/workspace-file.js +7 -7
  20. package/src/agent/workspace.js +25 -4
  21. package/src/cli/components.js +4 -1
  22. package/src/cli/index.js +97 -1
  23. package/src/config.js +20 -3
  24. package/src/marathon/driver.js +217 -0
  25. package/src/marathon/prompts.js +93 -0
  26. package/template/.env.template +16 -0
  27. package/template/AGENT.md +182 -7
  28. package/template/skills/en/{meta-meta/auto-model-selection → auto-model-selection}/SKILL.md +1 -0
  29. package/template/skills/en/{meta-meta/bootstrap-workspace → bootstrap-workspace}/SKILL.md +15 -0
  30. package/template/skills/{zh/meta → en}/compliance-judgment/SKILL.md +1 -0
  31. package/template/skills/en/{meta/confidence-system → confidence-system}/SKILL.md +1 -0
  32. package/template/skills/en/{meta/corner-case-management → corner-case-management}/SKILL.md +1 -0
  33. package/template/skills/en/{meta/cross-document-verification → cross-document-verification}/SKILL.md +1 -0
  34. package/template/skills/en/{meta-meta/dashboard-reporting → dashboard-reporting}/SKILL.md +1 -0
  35. package/template/skills/en/{meta/data-sensibility → data-sensibility}/SKILL.md +1 -0
  36. package/template/skills/{zh/meta → en}/document-chunking/SKILL.md +1 -0
  37. package/template/skills/en/{meta/document-parsing → document-parsing}/SKILL.md +1 -0
  38. package/template/skills/{zh/meta → en}/entity-extraction/SKILL.md +1 -0
  39. package/template/skills/en/{meta-meta/evolution-loop → evolution-loop}/SKILL.md +1 -0
  40. package/template/skills/en/{meta-meta/pdf-review-dashboard → pdf-review-dashboard}/SKILL.md +1 -0
  41. package/template/skills/en/{meta-meta/quality-control → quality-control}/SKILL.md +10 -0
  42. package/template/skills/en/{meta-meta/rule-extraction → rule-extraction}/SKILL.md +1 -0
  43. package/template/skills/en/{meta-meta/rule-graph → rule-graph}/SKILL.md +1 -0
  44. package/template/skills/en/{meta-meta/skill-authoring → skill-authoring}/SKILL.md +40 -0
  45. package/template/skills/en/skill-creator/SKILL.md +2 -1
  46. package/template/skills/en/{meta-meta/skill-to-workflow → skill-to-workflow}/SKILL.md +58 -4
  47. package/template/skills/en/{meta-meta/task-decomposition → task-decomposition}/SKILL.md +1 -0
  48. package/template/skills/en/{meta/tree-processing → tree-processing}/SKILL.md +1 -0
  49. package/template/skills/en/{meta-meta/version-control → version-control}/SKILL.md +1 -0
  50. package/template/skills/en/{meta-meta/work-decomposition → work-decomposition}/SKILL.md +51 -6
  51. package/template/skills/phase_skills.yaml +112 -0
  52. package/template/skills/zh/{meta-meta/auto-model-selection → auto-model-selection}/SKILL.md +1 -0
  53. package/template/skills/zh/{meta-meta/bootstrap-workspace → bootstrap-workspace}/SKILL.md +15 -0
  54. package/template/skills/zh/compliance-judgment/SKILL.md +83 -0
  55. package/template/skills/zh/{meta/confidence-system → confidence-system}/SKILL.md +1 -0
  56. package/template/skills/zh/{meta/corner-case-management → corner-case-management}/SKILL.md +1 -0
  57. package/template/skills/zh/{meta/cross-document-verification → cross-document-verification}/SKILL.md +1 -0
  58. package/template/skills/zh/{meta-meta/dashboard-reporting → dashboard-reporting}/SKILL.md +1 -0
  59. package/template/skills/zh/{meta/data-sensibility → data-sensibility}/SKILL.md +1 -0
  60. package/template/skills/zh/document-chunking/SKILL.md +40 -0
  61. package/template/skills/zh/document-parsing/SKILL.md +102 -0
  62. package/template/skills/zh/entity-extraction/SKILL.md +121 -0
  63. package/template/skills/zh/{meta-meta/evolution-loop → evolution-loop}/SKILL.md +1 -0
  64. package/template/skills/zh/{meta-meta/pdf-review-dashboard → pdf-review-dashboard}/SKILL.md +1 -0
  65. package/template/skills/zh/{meta-meta/quality-control → quality-control}/SKILL.md +10 -0
  66. package/template/skills/zh/{meta-meta/rule-extraction → rule-extraction}/SKILL.md +1 -0
  67. package/template/skills/zh/{meta-meta/rule-graph → rule-graph}/SKILL.md +1 -0
  68. package/template/skills/zh/{meta-meta/skill-authoring → skill-authoring}/SKILL.md +40 -0
  69. package/template/skills/zh/skill-creator/SKILL.md +205 -200
  70. package/template/skills/zh/skill-to-workflow/SKILL.md +243 -0
  71. package/template/skills/zh/{meta-meta/task-decomposition → task-decomposition}/SKILL.md +1 -0
  72. package/template/skills/zh/tree-processing/SKILL.md +126 -0
  73. package/template/skills/zh/{meta-meta/version-control → version-control}/SKILL.md +1 -0
  74. package/template/skills/zh/{meta-meta/work-decomposition → work-decomposition}/SKILL.md +49 -4
  75. package/template/workflows/common/llm_client.py +168 -0
  76. package/template/workflows/common/utils.py +132 -0
  77. package/template/CLAUDE.md +0 -150
  78. package/template/skills/en/meta/compliance-judgment/SKILL.md +0 -82
  79. package/template/skills/en/meta/document-chunking/SKILL.md +0 -32
  80. package/template/skills/en/meta/entity-extraction/SKILL.md +0 -120
  81. package/template/skills/zh/meta/document-parsing/SKILL.md +0 -101
  82. package/template/skills/zh/meta/tree-processing/SKILL.md +0 -121
  83. package/template/skills/zh/meta-meta/skill-to-workflow/SKILL.md +0 -188
  84. /package/template/skills/en/{meta/compliance-judgment → compliance-judgment}/references/output-format.md +0 -0
  85. /package/template/skills/en/{meta/cross-document-verification → cross-document-verification}/references/contradiction-taxonomy.md +0 -0
  86. /package/template/skills/en/{meta-meta/dashboard-reporting → dashboard-reporting}/scripts/generate_dashboard.py +0 -0
  87. /package/template/skills/en/{meta/document-parsing → document-parsing}/references/parser-catalog.md +0 -0
  88. /package/template/skills/en/{meta-meta/evolution-loop → evolution-loop}/references/convergence-guide.md +0 -0
  89. /package/template/skills/en/{meta-meta/pdf-review-dashboard → pdf-review-dashboard}/scripts/generate_review.js +0 -0
  90. /package/template/skills/en/{meta-meta/quality-control → quality-control}/references/qa-layers.md +0 -0
  91. /package/template/skills/en/{meta-meta/quality-control → quality-control}/references/sampling-strategies.md +0 -0
  92. /package/template/skills/en/{meta-meta/rule-extraction → rule-extraction}/references/chunking-strategies.md +0 -0
  93. /package/template/skills/en/{meta-meta/skill-authoring → skill-authoring}/references/skill-format-spec.md +0 -0
  94. /package/template/skills/en/{meta-meta/skill-to-workflow → skill-to-workflow}/references/worker-llm-catalog.md +0 -0
  95. /package/template/skills/en/{meta-meta/task-decomposition → task-decomposition}/references/decision-matrix.md +0 -0
  96. /package/template/skills/en/{meta-meta/version-control → version-control}/references/trace-id-spec.md +0 -0
  97. /package/template/skills/zh/{meta/compliance-judgment → compliance-judgment}/references/output-format.md +0 -0
  98. /package/template/skills/zh/{meta/cross-document-verification → cross-document-verification}/references/contradiction-taxonomy.md +0 -0
  99. /package/template/skills/zh/{meta-meta/dashboard-reporting → dashboard-reporting}/scripts/generate_dashboard.py +0 -0
  100. /package/template/skills/zh/{meta/document-parsing → document-parsing}/references/parser-catalog.md +0 -0
  101. /package/template/skills/zh/{meta-meta/evolution-loop → evolution-loop}/references/convergence-guide.md +0 -0
  102. /package/template/skills/zh/{meta-meta/pdf-review-dashboard → pdf-review-dashboard}/scripts/generate_review.js +0 -0
  103. /package/template/skills/zh/{meta-meta/quality-control → quality-control}/references/qa-layers.md +0 -0
  104. /package/template/skills/zh/{meta-meta/quality-control → quality-control}/references/sampling-strategies.md +0 -0
  105. /package/template/skills/zh/{meta-meta/rule-extraction → rule-extraction}/references/chunking-strategies.md +0 -0
  106. /package/template/skills/zh/{meta-meta/skill-authoring → skill-authoring}/references/skill-format-spec.md +0 -0
  107. /package/template/skills/zh/{meta-meta/skill-to-workflow → skill-to-workflow}/references/worker-llm-catalog.md +0 -0
  108. /package/template/skills/zh/{meta-meta/task-decomposition → task-decomposition}/references/decision-matrix.md +0 -0
  109. /package/template/skills/zh/{meta-meta/version-control → version-control}/references/trace-id-spec.md +0 -0
@@ -0,0 +1,132 @@
1
+ """KC workflow helpers (v0.8.1 P10-B).
2
+
3
+ Common utilities for distilled workflows. Provider-agnostic, no
4
+ external dependencies. Reusable across rule check.py / workflow.py
5
+ files so that per-rule scripts stay focused on rule-specific logic.
6
+
7
+ Currently:
8
+ strip_annotations(text) — drop reviewer-annotation footers
9
+ from sample documents so per-rule
10
+ check.py regex doesn't false-positive
11
+ on the annotation itself
12
+
13
+ detect_report_type(text) — light-touch report-type classifier
14
+ (年报 / 季报 / 月报 / 周报 / 其他)
15
+ used by rules that gate on report type
16
+
17
+ make_result(rule_id, verdict, evidence, confidence, **kwargs)
18
+ — standardized result dict factory
19
+ """
20
+ import re
21
+
22
+
23
+ # Annotation prefixes that mark reviewer-added footers in sample docs.
24
+ # These should be stripped before keyword/regex matching so per-rule
25
+ # check.py doesn't match the annotation as if it were document content.
26
+ #
27
+ # Added based on E2E #11 贷款 v0.8 audit § 9: 4/14 spot-checks
28
+ # false-positive PASS because samples contain `预期命中点: ...年化利率`
29
+ # footers that the rule's keyword regex matches.
30
+ _ANNOTATION_PREFIXES = (
31
+ "预期命中点",
32
+ "预期结果",
33
+ "预期判定",
34
+ "预期验证",
35
+ "标注",
36
+ "审核标注",
37
+ "Expected",
38
+ "expected",
39
+ "EXPECTED",
40
+ "Annotation",
41
+ "annotation",
42
+ )
43
+
44
+
45
+ def strip_annotations(text, extra_prefixes=None):
46
+ """Remove reviewer-annotation footers from document text.
47
+
48
+ A line is dropped if it starts with one of the recognized
49
+ annotation prefixes followed by `:` or `:` (Chinese full-width
50
+ colon). All subsequent lines until a blank line or end of text
51
+ are also dropped (annotations are typically multi-line trailing
52
+ blocks).
53
+
54
+ Pass `extra_prefixes` (iterable of strings) to add project-specific
55
+ annotation labels.
56
+
57
+ Returns the cleaned text. Input is never mutated.
58
+ """
59
+ if not text:
60
+ return text
61
+ prefixes = tuple(_ANNOTATION_PREFIXES)
62
+ if extra_prefixes:
63
+ prefixes = prefixes + tuple(extra_prefixes)
64
+ # Build a pattern matching `<prefix>` + colon (half or full-width)
65
+ pattern = "|".join(re.escape(p) for p in prefixes)
66
+ anno_start = re.compile(rf"^\s*(?:{pattern})\s*[::]")
67
+
68
+ out_lines = []
69
+ in_anno_block = False
70
+ for line in text.split("\n"):
71
+ if anno_start.match(line):
72
+ in_anno_block = True
73
+ continue
74
+ if in_anno_block:
75
+ # End block on a blank line OR a line that doesn't look
76
+ # like annotation continuation (no leading whitespace).
77
+ if not line.strip() or not line.startswith((" ", "\t", "-", "*", "·")):
78
+ in_anno_block = False
79
+ if line.strip():
80
+ out_lines.append(line)
81
+ # Otherwise still inside the annotation block — drop.
82
+ continue
83
+ out_lines.append(line)
84
+ return "\n".join(out_lines)
85
+
86
+
87
+ _REPORT_TYPE_PATTERNS = [
88
+ ("年报", re.compile(r"年报|年度报告|annual report", re.IGNORECASE)),
89
+ ("半年报", re.compile(r"半年报|半年度报告|interim report", re.IGNORECASE)),
90
+ ("季报", re.compile(r"季报|季度报告|quarterly report", re.IGNORECASE)),
91
+ ("月报", re.compile(r"月报|月度报告|monthly report", re.IGNORECASE)),
92
+ ("周报", re.compile(r"周报|周度报告|weekly report", re.IGNORECASE)),
93
+ ]
94
+
95
+
96
+ def detect_report_type(text):
97
+ """Light-touch report-type classifier.
98
+
99
+ Returns one of: "年报", "半年报", "季报", "月报", "周报", "其他".
100
+ Scans only the first 2000 chars (report-type identifiers usually
101
+ appear in the title or cover page). Used by rules that gate on
102
+ report type (e.g. R02-06/R02-08 are NOT_APPLICABLE for 季报).
103
+ """
104
+ if not text:
105
+ return "其他"
106
+ head = text[:2000]
107
+ for kind, pattern in _REPORT_TYPE_PATTERNS:
108
+ if pattern.search(head):
109
+ return kind
110
+ return "其他"
111
+
112
+
113
+ def make_result(rule_id, verdict, evidence, confidence=0.7, **kwargs):
114
+ """Build a standardized check result dict.
115
+
116
+ Required: rule_id, verdict ("PASS" / "FAIL" / "WARNING" / "NOT_APPLICABLE"),
117
+ evidence (string explaining the verdict).
118
+
119
+ Optional: confidence (0.0-1.0), plus any extra fields the rule
120
+ needs (model_used, llm_calls, llm_tokens, comment, etc.).
121
+ """
122
+ result = {
123
+ "rule_id": rule_id,
124
+ "verdict": verdict,
125
+ "evidence": evidence,
126
+ "confidence": confidence,
127
+ }
128
+ result.update(kwargs)
129
+ return result
130
+
131
+
132
+ __all__ = ["strip_annotations", "detect_report_type", "make_result"]
@@ -1,150 +0,0 @@
1
- # KC Reborn — Document Verification Workspace
2
-
3
- ## What This Workspace Is
4
-
5
- You are a coding agent tasked with building a document verification app for the developer user's specific business scenario. The meta skills in `skills/` encode the methodology of experienced verification system architects and business analysts. You bring the intelligence and judgment to apply this methodology to the specific case at hand.
6
-
7
- Your goal: build a verification system that starts with you doing the work, then gradually distills your capability into cheap, fast workflows powered by worker LLMs. You are the ground truth. The workflows you create are the deliverables.
8
-
9
- ## Roles
10
-
11
- - **Developer user**: The human you serve. They are a domain expert (e.g., tech lead at a bank's loan department). They provide the rules, the documents, and the business context. Discuss decisions with them.
12
- - **You (the coding agent)**: You are both the Builder (creating skills and workflows) and the Observer (judging quality). You do the verification first, prove it works, then teach smaller models to replicate your results.
13
- - **Worker LLMs**: The performers. Models configured in `.env` (TIER1 through TIER4) that will execute the workflows you build. Your job is to find the smallest model that works for each task.
14
-
15
- ## Workspace Layout
16
-
17
- ```
18
- Rules/ — Regulation documents, compliance notes from the developer user
19
- Samples/ — Sample documents for testing (your training set)
20
- Input/ — Production document batches awaiting verification
21
- Output/ — Verification results
22
- skills/ — Meta skills encoding verification methodology
23
- .env — Configuration: API keys, model tiers, thresholds, language
24
- ```
25
-
26
- Note: KC's session workspace under `~/.kc_agent/workspaces/<sessionId>/`
27
- uses lowercase counterparts (`rules/`, `samples/`, `input/`, `output/`,
28
- `logs/`, `workflows/`, `rule_skills/`) — these are runtime-internal and
29
- separate from this project's user-facing folders above. The asymmetry
30
- is intentional: title-case for human-facing project dirs, lowercase for
31
- KC's working state.
32
-
33
- ## Your Mission
34
-
35
- Follow this lifecycle. Each step references the skill(s) to consult:
36
-
37
- 1. **Bootstrap** → Read `bootstrap-workspace`. Understand the business scenario, read Rules/, scan Samples/, configure .env with the developer user.
38
- 2. **Extract Rules** → Read `rule-extraction`. Decompose regulation documents into atomic, testable verification rules.
39
- 3. **Decompose Tasks** → Read `task-decomposition`. For each rule, break the verification into sub-tasks and assign the optimal method (rule, code, LLM, or manual) to each.
40
- 4. **Map Rule Relationships** → Read `rule-graph`. Identify shared entities, dependencies, and conflicts between rules. Each rule stays independently executable.
41
- 5. **Write Rule Skills** → Read `skill-authoring`. Write each rule into a skill folder. Before writing extraction logic for a new document type, consult `data-sensibility` to observe the data first.
42
- 6. **Test Skills** → Apply each skill to Samples/. Use `evolution-loop` to diagnose failures and iterate. Continue until accuracy meets SKILL_ACCURACY threshold in .env.
43
- 7. **Distill to Workflows** → Read `skill-to-workflow`. Convert proven skills into Python code + worker LLM prompts. Test workflows against your own results as ground truth. Iterate until WORKFLOW_ACCURACY is met.
44
- 8. **Production QC** → Read `quality-control` and `confidence-system`. Run workflows on Input/. Sample and review results based on confidence scores. For multi-document cases, read `cross-document-verification`. Use `evolution-loop` when quality drops.
45
- 9. **Stabilize** → Gradually reduce monitoring as workflows prove reliable. Only intervene when rules change or quality drops.
46
- 10. **Report** → Read `dashboard-reporting`. Generate HTML dashboards so the developer user can see results, progress, and issues. Ensure dashboards include feedback collection mechanisms for users.
47
-
48
- Throughout: use `version-control` to track all changes. Use `corner-case-management` to handle edge cases without polluting workflows. Use `task-decomposition` and `rule-graph` to inform optimization decisions.
49
-
50
- ## Core Principles
51
-
52
- - **Minimum viable model**: Always use the smallest, cheapest, fastest model that meets the accuracy threshold. Start simple, escalate only when necessary.
53
- - **JIT structure**: Do not design schemas or formats prematurely. Define them when needed, keep them consistent once defined.
54
- - **OTF evolution**: The system you build today may look completely different tomorrow. Embrace change.
55
- - **Skills before workflows**: Prove each rule works as a skill (you executing it) before distilling into code + worker LLM prompts.
56
- - **Log everything**: Every test iteration, every evolution decision, every version change. Both JSON (machine-readable) and plain text (human-readable).
57
-
58
- ## How to Read Skills
59
-
60
- Skills use progressive disclosure:
61
- 1. **Frontmatter** (name + description) — always visible, ~100 words. Tells you WHEN to use the skill.
62
- 2. **SKILL.md body** — read when the skill is relevant. Under 500 lines. Conveys methodology, not recipes.
63
- 3. **references/** — read on demand for detailed technical reference.
64
- 4. **scripts/** — executable code you can run or adapt.
65
- 5. **assets/** — data files, templates, examples.
66
-
67
- Skills convey philosophy and decision frameworks. Adapt them to the specific business case. Do not follow them rigidly.
68
-
69
- ## Communication with Developer User
70
-
71
- - **Proactively discuss**: rule granularity, accuracy thresholds, model selection, edge cases.
72
- - **Report progress**: after each testing round, share results and next steps.
73
- - **Escalate**: when you cannot resolve an issue after iterating, surface it with evidence.
74
- - **Ask**: the developer user is a domain expert. When in doubt about a rule's intent, ask.
75
-
76
- ---
77
-
78
- # KC Reborn — 文档核查工作区
79
-
80
- ## 这是什么
81
-
82
- 你是一个编程智能体,负责为开发者用户的具体业务场景构建文档核查应用。`skills/` 中的元技能编码了资深核查系统架构师和业务分析师的方法论。你负责运用智慧和判断力,将这些方法论应用到具体场景中。
83
-
84
- 你的目标:构建一个核查系统,先由你亲自执行核查工作,然后逐步将你的能力蒸馏为由 Worker LLM(执行模型)驱动的低成本、高速度的工作流。你是基准真值。你创建的工作流是最终交付物。
85
-
86
- ## 角色定义
87
-
88
- - **开发者用户**:你服务的人。他们是领域专家(如银行信贷部门的技术负责人)。他们提供规则、文档和业务背景。与他们讨论决策。
89
- - **你(编程智能体)**:你既是构建者(创建技能和工作流),也是观察者(评判质量)。你先执行核查,证明方法可行,再教小模型复现你的结果。
90
- - **Worker LLM**:执行者。在 `.env` 中配置的模型(TIER1到TIER4),将执行你构建的工作流。你的任务是为每项工作找到能胜任的最小模型。
91
-
92
- ## 工作区结构
93
-
94
- ```
95
- Rules/ — 法规文件、开发者用户的合规注释
96
- Samples/ — 用于测试的样本文件(你的训练集)
97
- Input/ — 等待核查的生产批次文件
98
- Output/ — 核查结果
99
- skills/ — 编码核查方法论的元技能
100
- .env — 配置:API密钥、模型层级、阈值、语言
101
- ```
102
-
103
- 注:KC 在 `~/.kc_agent/workspaces/<sessionId>/` 下的会话工作区使用
104
- 小写对应目录(`rules/`、`samples/`、`input/`、`output/`、`logs/`、
105
- `workflows/`、`rule_skills/`)—— 这些是运行时内部目录,与本项目上面
106
- 那些用户可见的目录是分开的。这种大小写不对称是有意的:项目里给人看
107
- 的目录用首字母大写;KC 自己的工作状态用小写。
108
-
109
- ## 你的使命
110
-
111
- 遵循以下生命周期。每一步标注了需要参考的技能:
112
-
113
- 1. **初始化** → 阅读 `bootstrap-workspace`。理解业务场景,阅读 Rules/,浏览 Samples/,与开发者用户配置 .env。
114
- 2. **提取规则** → 阅读 `rule-extraction`。将法规文件分解为原子级、可测试的核查规则。
115
- 3. **任务分解** → 阅读 `task-decomposition`。对每条规则,将核查过程拆解为子任务,为每个子任务分配最优方法(规则、代码、LLM 或人工)。
116
- 4. **构建规则图谱** → 阅读 `rule-graph`。识别规则间的共享实体、依赖关系和潜在冲突。每条规则保持独立可执行。
117
- 5. **编写规则技能** → 阅读 `skill-authoring`。将每条规则写入技能文件夹。编写新文档类型的提取逻辑前,先阅读 `data-sensibility` 观察数据。
118
- 6. **测试技能** → 在 Samples/ 上应用每个技能。使用 `evolution-loop` 诊断失败并迭代。直到准确率达到 .env 中的 SKILL_ACCURACY 阈值。
119
- 7. **蒸馏为工作流** → 阅读 `skill-to-workflow`。将验证过的技能转化为 Python 代码 + Worker LLM 提示词。用你自己的结果作为基准测试工作流。迭代直到达到 WORKFLOW_ACCURACY。
120
- 8. **生产质控** → 阅读 `quality-control` 和 `confidence-system`。在 Input/ 上运行工作流。根据置信度分数抽样审查结果。涉及多文档案件时,阅读 `cross-document-verification`。质量下降时使用 `evolution-loop`。
121
- 9. **稳定运行** → 随着工作流稳定,逐步降低监控频率。仅在规则变更或质量下降时介入。
122
- 10. **报告** → 阅读 `dashboard-reporting`。生成 HTML 仪表板,让开发者用户直观地看到结果、进度和问题。确保仪表盘内置用户反馈收集机制。
123
-
124
- 全程使用 `version-control` 跟踪所有变更。使用 `corner-case-management` 处理边缘案例,不要污染主工作流。使用 `task-decomposition` 和 `rule-graph` 指导优化决策。
125
-
126
- ## 核心原则
127
-
128
- - **最小可用模型**:始终使用能达到准确率阈值的最小、最便宜、最快的模型。从简单开始,必要时才升级。
129
- - **即时结构(JIT)**:不要过早设计数据结构或格式。需要时定义,定义后保持一致。
130
- - **即时演进(OTF)**:你今天构建的系统明天可能面目全非。拥抱变化。
131
- - **先技能后工作流**:先证明每条规则作为技能(你执行)可行,再蒸馏为代码 + Worker LLM 提示词。
132
- - **记录一切**:每次测试迭代、每个演进决策、每次版本变更。同时保存 JSON(机器可读)和纯文本(人类可读)。
133
-
134
- ## 如何阅读技能
135
-
136
- 技能采用渐进式披露:
137
- 1. **前置元数据**(名称 + 描述)— 始终可见,约100字。告诉你何时使用该技能。
138
- 2. **SKILL.md 正文** — 技能相关时阅读。500行以内。传达方法论,而非配方。
139
- 3. **references/** — 按需阅读,获取详细技术参考。
140
- 4. **scripts/** — 可执行代码,可直接运行或修改。
141
- 5. **assets/** — 数据文件、模板、示例。
142
-
143
- 技能传达的是理念和决策框架。请根据具体业务场景灵活运用,不要机械照搬。
144
-
145
- ## 与开发者用户的沟通
146
-
147
- - **主动讨论**:规则粒度、准确率阈值、模型选择、边缘案例。
148
- - **汇报进度**:每轮测试后,分享结果和下一步计划。
149
- - **升级问题**:迭代后仍无法解决的问题,附带证据提交给开发者用户。
150
- - **多问**:开发者用户是领域专家。对规则意图有疑问时,问他们。
@@ -1,82 +0,0 @@
1
- ---
2
- name: compliance-judgment
3
- description: Determine whether extracted entities comply with verification rules. Use after entity extraction to make the pass/fail judgment for each rule on each document. Covers translating natural language rules into executable logic, choosing between Python calculation and LLM semantic judgment, and producing actionable comments on failures. Also use when designing the judgment step of a workflow or when a rule's judgment logic needs debugging.
4
- ---
5
-
6
- # Compliance Judgment
7
-
8
- Judgment is the moment of truth. You have the extracted entity. You have the rule. Do they comply? The answer must be clear, correct, and — when the answer is no — accompanied by a concise, actionable comment.
9
-
10
- ## The Judgment Spectrum
11
-
12
- Rules range from trivially deterministic to deeply semantic. Pick the right tool for each rule.
13
-
14
- **Deterministic** — threshold checks, format validation, date arithmetic, cross-field consistency. Pure Python: free, instant, deterministic.
15
-
16
- **Semantic** — adequacy, completeness, consistency, compliance with templates, detecting misleading or suggestive language, assessing whether a description is fair and balanced. These require language understanding — use worker LLM.
17
-
18
- Many real compliance rules require semantic judgment. "The risk disclosure must adequately describe the key risks" cannot be checked with regex or Python. "The contract description must not be misleading or suggestive" requires deep language understanding. Use worker LLM for these without hesitation.
19
-
20
- Some rules combine both: extract a number (deterministic), compare to threshold (deterministic), then assess the explanation if borderline (semantic). The mix depends on the rule.
21
-
22
- The right method is whatever achieves accuracy at lowest cost. Simple threshold checks don't need LLM. Semantic assessments don't benefit from Python. Most projects will have a mix — let the nature of each rule determine the method.
23
-
24
- ## Output Format
25
-
26
- For each rule × document combination:
27
-
28
- ```json
29
- {
30
- "rule_id": "R001",
31
- "document": "report_2024_q1.pdf",
32
- "result": "pass | fail | missing | error | uncertain",
33
- "extracted_value": "12.5%",
34
- "expected": ">= 8.0%",
35
- "comment": "",
36
- "confidence": 0.95
37
- }
38
- ```
39
-
40
- **Result values:**
41
- - **pass**: Entity complies with the rule.
42
- - **fail**: Entity does not comply. Comment is required.
43
- - **missing**: The entity could not be found in the document. This is different from fail — the information is absent, not non-compliant.
44
- - **error**: Something went wrong during extraction or judgment (parsing failure, API error). Needs investigation.
45
- - **uncertain**: The judgment is ambiguous. May need human review.
46
-
47
- **Design exit criteria first:** Before writing judgment logic for a rule, define the exit conditions: what constitutes pass, what constitutes fail, what triggers escalation to human, how to handle empty/missing values, what value ranges are valid. Explicit exit criteria prevent ambiguous or inconsistent judgment.
48
-
49
- **Prompt design:** Design prompts for what you want, not against what you don't want. "Don't include reasoning" is less reliable than extracting the verdict from structured output in postprocessing. Use output filtering instead of prompt negation.
50
-
51
- **Comments:**
52
- - Required only when result is `fail`. Skip for `pass` unless the developer user specifically requests pass comments.
53
- - Be concise and factual: "Capital adequacy ratio is 7.2%, below the regulatory minimum of 8.0%."
54
- - Do not editorialize: not "This is a serious violation that could result in penalties." Just state the facts.
55
- - Include the extracted value and the expected value/condition for context.
56
-
57
- ### Lightweight Annotation Markup
58
-
59
- For human review, token-efficient logging, and clean diff comparisons, results can also be expressed in compact text markup:
60
-
61
- ```
62
- [PASS] capital_adequacy <- 12.5% (>= 8.0%) | conf:0.95 | src:p3-s2
63
- [FAIL] sign_date_gap <- 75d (<= 30d) | conf:0.90 | src:p1-s4 | note:Signing overdue by 45 days
64
- [MISSING] collateral_value | conf:0.60 | note:Collateral valuation not found in document
65
- ```
66
-
67
- This format is losslessly convertible to and from the JSON format above. Use it when presenting results to the developer user for quick review, logging to evolution iteration summaries where token economy matters, or computing diffs between verification runs. See `references/output-format.md` for the full specification and conversion rules.
68
-
69
- ## Judgment Ordering
70
-
71
- Some rules depend on the results of other rules:
72
- - Rule B might only apply if Rule A passes. "If the borrower is a new customer (Rule A), then additional documentation is required (Rule B)."
73
- - Rule C might use a value computed by Rule A. "The risk-weighted capital ratio (Rule A) determines the required reserve level (Rule C)."
74
-
75
- Map these dependencies in the rule catalog. Execute rules in dependency order. Pass upstream results as context to downstream rules.
76
-
77
- ## Handling Edge Cases
78
-
79
- - **Null extraction**: The entity was not found. Default to `missing`, not `fail`. A missing value is an extraction problem, not a compliance problem.
80
- - **Multiple values**: The document contains the entity in multiple places with different values. Flag as `uncertain`. Report all found values.
81
- - **Conditional rules**: "If the loan exceeds 1M, then collateral is required." Check the condition before applying the rule. If the condition is not met, the rule does not apply — result is `pass` (or `not_applicable` if you add that category).
82
- - **Negative results**: Some rules check for absence. "The document must NOT contain guarantees to related parties." Searching for absence is harder than searching for presence. Be thorough in the search, then be confident in the negative.
@@ -1,32 +0,0 @@
1
- ---
2
- name: document-chunking
3
- description: >
4
- Fast, cheap chunking for processing batches of sample and input documents.
5
- Use when you need to split documents into manageable pieces for initial observation,
6
- data sensibility checks, or feeding to extraction workflows. Not for production
7
- verification chunking — for that, use tree-processing to design a tailored chunking script.
8
- ---
9
-
10
- # Document Chunking
11
-
12
- Split documents into pieces for downstream processing. This is the fast, cheap version — for batch processing of samples and inputs, not for precision verification workflows.
13
-
14
- ## Methods
15
-
16
- **Page-level splits** — simplest. Each page is a chunk. Works for most document processing where you need to iterate over content.
17
-
18
- **Fixed-size chunks** — split by character/token count with overlap. Good for search and initial observation. Typical: 2000-4000 chars with 200 char overlap.
19
-
20
- **Header-based splits** — detect section headers and split at boundaries. Preserves semantic units. Use regex patterns for the document's header convention.
21
-
22
- ## When to Use What
23
-
24
- Pick the simplest method that serves the task:
25
- - Batch document observation → page-level
26
- - Full-text search index → fixed-size with overlap
27
- - Section-level extraction → header-based
28
- - Table of contents available → parse TOC for structure
29
-
30
- ## Relationship to tree-processing
31
-
32
- This skill is for quick, cheap chunking during exploration and batch processing. When you need production-grade chunking for verification workflows — where the chunking mechanism must be precise, consistent, and coded as a script — use `tree-processing` instead.
@@ -1,120 +0,0 @@
1
- ---
2
- name: entity-extraction
3
- description: Extract specific entities, values, and text segments from documents as required by verification rules. Use after tree processing has located the relevant section, when a rule needs a specific number, date, name, amount, clause, or any domain-specific entity extracted. Covers extraction method selection (regex vs LLM), schema design, postprocessing, and confidence annotation. Also use when designing the extraction step of a workflow for worker LLMs.
4
- ---
5
-
6
- # Entity Extraction
7
-
8
- An entity is the thing you need to check. A number, a date, a name, a clause, a percentage, a statement. The rule says what to check; extraction is how you get the value to check it against.
9
-
10
- ## Extraction Type Taxonomy
11
-
12
- Different extraction scenarios call for different approaches:
13
-
14
- ### Single Entity from Single Section
15
- The simplest case. One rule needs one value from one place.
16
- - Example: "Extract the capital adequacy ratio from the Key Metrics table."
17
- - Approach: Locate the section, apply regex or LLM extraction.
18
-
19
- ### Multiple Entities from Single Section
20
- One rule needs several related values from the same place.
21
- - Example: "Extract the borrower's name, loan amount, interest rate, and maturity date from the loan agreement summary."
22
- - Approach: Design a single extraction call that returns all values. More efficient than multiple calls.
23
-
24
- ### Single Entity from Multiple Sections
25
- One value is scattered across multiple places, or needs cross-referencing.
26
- - Example: "Extract the total collateral value, which may be listed in the collateral section or in Appendix A."
27
- - Approach: Collect content from all relevant sections, then extract. Note which source the value came from.
28
-
29
- ### Entity from Full Document
30
- The value could be anywhere, or the rule applies to the document as a whole.
31
- - Example: "Check whether the document contains a valid signature page."
32
- - Approach: For the coding agent, scan the full document. For worker LLM workflows, design a two-pass approach: first pass identifies the location, second pass extracts the value.
33
-
34
- ## Method Selection
35
-
36
- Extraction method selection is a cost-accuracy search. The goal is finding the cheapest method that meets the accuracy threshold. Regex is the smallest, cheapest "model" — zero cost, instant, deterministic. Worker LLM is more capable but costs tokens and time. Any search strategy is valid: try the cheapest first and escalate, try the most capable first and downgrade, bisect, or jump directly to a known-good method based on past experience in AGENT.md.
37
-
38
- ### Available Methods
39
-
40
- **Regex / Python** — Cost: zero. Speed: instant. Deterministic.
41
- Works well for: dates, monetary amounts, percentages, identifiers, fixed phrases, any value with a predictable format.
42
-
43
- **Worker LLM** — Cost: API tokens. Speed: seconds. Semantic understanding.
44
- Works well for: contextual interpretation, conditional values, semantic matching, ambiguous structures, suggestive or misleading language detection, table interpretation, anything requiring understanding rather than pattern matching.
45
-
46
- Many real verification tasks require semantic understanding — "is this description misleading?", "does this clause adequately disclose risk?", "is this guarantor's business description consistent with their stated industry?" — regex cannot handle these. Use worker LLM without hesitation for such tasks.
47
-
48
- ### The Search
49
-
50
- If a method's results fall below the accuracy threshold, try a different method or a more capable model. If regex works and meets accuracy — keep it, it's free. If regex produces results below threshold, escalate to worker LLM. If a cheap worker LLM isn't accurate enough, try a more capable tier. Record what works for each extraction type in AGENT.md for future reference.
51
-
52
- ## Project Glossary
53
-
54
- The project glossary (built and maintained by `rule-extraction`, stored at `rules/glossary.json`) is a useful resource when designing extraction. It records canonical names and known aliases for entities that appear across rules. Reading it before extracting helps keep entity names schema-aligned and avoids parallel labels for the same thing.
55
-
56
- Whether the glossary becomes more than a naming convention — for instance, driving cheap pattern matching for entities with stable surface forms — is a per-project judgment. Apply the same cost-accuracy logic as elsewhere: whatever method meets the accuracy threshold for the task at hand.
57
-
58
- ## Schema Design
59
-
60
- Define the expected output for each extraction. Keep it simple and JIT:
61
-
62
- ```json
63
- {
64
- "entity_name": "capital_adequacy_ratio",
65
- "value": 12.5,
66
- "unit": "%",
67
- "raw_text": "资本充足率为12.5%",
68
- "source_location": "Chapter 2, Table 1, Row 3",
69
- "confidence": 0.95,
70
- "extraction_method": "regex"
71
- }
72
- ```
73
-
74
- The schema should capture:
75
- - **value**: The extracted value, normalized.
76
- - **unit**: If applicable (%, 元, days, etc.).
77
- - **raw_text**: The original text fragment where the value was found. This is evidence for the judgment step.
78
- - **source_location**: Where in the document the value was found.
79
- - **confidence**: How sure you are (see `confidence-system`).
80
- - **extraction_method**: What extracted it (regex, LLM-TIER2, etc.).
81
-
82
- Do not over-engineer the schema. Add fields as needed during testing.
83
-
84
- ## Postprocessing
85
-
86
- Raw extracted values often need normalization:
87
-
88
- - **Chinese numerals → digits**: 一百二十万 → 1200000
89
- - **Date standardization**: 2024年3月15日 → 2024-03-15
90
- - **Unit conversion**: 万元 → multiply by 10000 if comparing to a threshold in 元.
91
- - **Whitespace and noise removal**: Strip extra spaces, line breaks, formatting artifacts.
92
- - **Percentage normalization**: 0.125 → 12.5% or vice versa, depending on what the rule expects.
93
-
94
- Build postprocessing as Python functions in the rule skill's `scripts/` directory. They are deterministic and reusable.
95
-
96
- ## Confidence Annotation
97
-
98
- Every extraction should carry a confidence estimate:
99
-
100
- - **Regex match, validated format**: 0.90-0.95
101
- - **LLM extraction, high certainty**: 0.80-0.85
102
- - **LLM extraction, some ambiguity**: 0.60-0.75
103
- - **Fallback or inferred value**: 0.40-0.60
104
- - **No value found**: 0.0 (flag as MISSING)
105
-
106
- These are starting points. Calibrate based on actual accuracy (see `confidence-system`).
107
-
108
- ## Prompt Design: Ask For What You Want
109
-
110
- Design prompts for what you want, not against what you don't want. "Don't include explanations" in a prompt is less reliable than stripping non-JSON text from the output in postprocessing. If you need to tell the LLM not to do something, use output filtering instead of prompt negation.
111
-
112
- ## Fitting Worker LLM Context
113
-
114
- When designing extraction for worker LLM workflows:
115
-
116
- 1. Calculate the prompt size: system prompt + instructions + examples + output format = N tokens.
117
- 2. Available context for document content = model's context window - N.
118
- 3. If the section exceeds available context, narrow further via tree processing.
119
- 4. Always leave room for the model's response.
120
- 5. Test with the actual model to verify the context fits — token counts from the coding agent may differ from the worker LLM's tokenizer.
@@ -1,101 +0,0 @@
1
- ---
2
- name: document-parsing
3
- description: Parse source documents into machine-readable text with maximum fidelity. Use when processing any document in Samples/ or Input/ for the first time, when parsed text quality is poor, or when tables and charts need special handling. Covers multi-level parser selection from simple text extraction to OCR and vision models. Also use when a verification rule fails due to parsing issues (garbled text, missing tables, mangled layouts) and the parser needs to be upgraded for that document type.
4
- ---
5
-
6
- # Document Parsing
7
-
8
- Parsing is the foundation. If the text is wrong, everything downstream is wrong. But parsing is also a cost center — do not use expensive vision models when simple text extraction works.
9
-
10
- ## The Minimum Viable Parser Principle
11
-
12
- Start with the simplest parser. Escalate only when necessary. This is not about saving money — it is about producing the most reliable output. Simple parsers have fewer failure modes.
13
-
14
- ### Level 1: Direct Text Extraction
15
- - Tool: pdfjs-dist or similar PDF text extraction.
16
- - When: Well-formed digital PDFs with embedded text. This covers most modern business documents.
17
- - Output: Raw text with basic structure preserved (paragraphs, basic formatting).
18
- - Limitations: Tables may come out as messy text. Charts and images are invisible. Scanned PDFs produce nothing.
19
-
20
- ### Level 2: Provider VLM (Vision Language Model)
21
- - Tool: VLM models from configured provider (VLM_TIER3 for cheap OCR, VLM_TIER1 for complex interpretation).
22
- - When: Level 1 produces garbled/incomplete text, scanned PDFs, image-based PDFs.
23
- - Output: Recognized text from page images, or structured interpretation (table as markdown, chart data as JSON).
24
- - Calling a provider VLM is more convenient and reliable than deploying local OCR. Use the cheapest VLM tier first; escalate to a more capable tier for complex tables/charts.
25
-
26
- ### Level 3: MineRU API or Local Tools (Optional)
27
- - Tool: MineRU API, pdfplumber, or locally deployed OCR — if configured.
28
- - When: Provider VLM is unavailable or too expensive for batch processing.
29
- - These are optional fallbacks. Most users will use Level 1 + Level 2.
30
-
31
- ## Quality Detection
32
-
33
- How to know when to escalate:
34
-
35
- - **Low character count**: The document has pages but extracted text is very short. Likely a scanned PDF.
36
- - **Garbled text**: Unusual character sequences, encoding errors, or meaningless text patterns.
37
- - **Missing expected sections**: The table of contents mentions Chapter 5 but no Chapter 5 text was extracted.
38
- - **Table artifacts**: Columns of numbers without alignment, cell content mixed with headers, or table borders appearing as characters.
39
- - **Missing numbers in financial tables**: If a financial document's key metrics are not in the extracted text, the tables were probably not parsed.
40
-
41
- Write a quick quality check after parsing and before proceeding. If quality is insufficient, escalate to the next parser level.
42
-
43
- ### Parse Quality Score
44
-
45
- Compute a quality score (0.0 to 1.0) from weighted heuristics to make escalation decisions systematic rather than ad-hoc. A recommended starting framework:
46
-
47
- - **Character density** (weight ~0.3): actual character count / expected characters for the document's page count. A 10-page PDF that yields only 200 characters likely failed.
48
- - **Garble ratio** (weight ~0.2): fraction of characters that are common CJK/Latin vs control characters, unusual sequences, or encoding artifacts.
49
- - **Section completeness** (weight ~0.3): if the document has a table of contents, what fraction of TOC entries have matching content in the extracted text?
50
- - **Table integrity** (weight ~0.2): for financial documents, are key numeric values that should appear in tables actually present in the extracted text?
51
-
52
- **Escalation thresholds** (recommended defaults — adjust freely):
53
- - Score >= 0.7: accept this parser level, proceed to downstream processing.
54
- - Score 0.4-0.7: escalate to the next parser level, re-parse, re-score.
55
- - Score < 0.4: skip directly to Level 3 (OCR) or Level 4 (vision) depending on document characteristics.
56
-
57
- **Lock-in**: once a parser level produces an acceptable score for a document type, record that level. Do not re-evaluate unless a downstream verification failure is traced back to a parsing issue.
58
-
59
- These weights, thresholds, and the scoring approach itself are starting points. The coding agent should design whatever quality assessment works for the specific document types at hand — a simple pass/fail heuristic may be sufficient for some scenarios; a more nuanced scoring function may be needed for others. The important pattern is: **measure quality → compare to threshold → decide whether to escalate**.
60
-
61
- This follows the same tier-transition pattern as model tier selection in `skill-to-workflow`: a quality/accuracy score drives the decision to stay, escalate, or skip tiers.
62
-
63
- ## Table Handling
64
-
65
- Tables are critical in financial documents (balance sheets, ratio tables, compliance metrics). They deserve special attention:
66
-
67
- 1. **Detection**: Identify table regions. Look for grid patterns, consistent column spacing, or explicit table markers.
68
- 2. **Extraction**: Extract cell-by-cell content. Preserve the row-column relationship.
69
- 3. **Reconstruction**: Convert to a structured format (markdown table, JSON array of rows, or CSV).
70
- 4. **Validation**: Spot-check that key values in the reconstructed table match what is visible in the document.
71
-
72
- When the standard parser fails on tables, try the vision model approach: send the table image (cropped from the PDF page) to a vision model and ask it to produce a markdown table.
73
-
74
- ## Chart Handling
75
-
76
- Charts (bar charts, line charts, pie charts) occasionally contain data needed for verification:
77
-
78
- - Extract the chart image from the document.
79
- - Send to a vision model with a prompt: "Extract the data points, labels, and values from this chart. Return as a JSON array."
80
- - Validate the extracted data against any nearby text or table that might contain the same numbers.
81
-
82
- This is expensive. Only do it when a verification rule specifically requires data from a chart and that data is not available in text elsewhere in the document.
83
-
84
- ## Output Format
85
-
86
- Parsed documents should be saved as clean markdown:
87
-
88
- - Preserve the document's heading hierarchy (# Chapter, ## Section, ### Subsection).
89
- - Preserve lists, numbered or bulleted.
90
- - Convert tables to markdown table format.
91
- - Note page boundaries if relevant (some rules reference specific pages).
92
- - Strip noise: headers, footers, page numbers, watermarks (unless a rule specifically checks for them).
93
-
94
- Save parsed output alongside the original document for reuse across rules.
95
-
96
- ## Caching
97
-
98
- Parsing is expensive (especially Level 3-4). Cache parsed output:
99
- - Store the parsed markdown alongside the original file.
100
- - Track which parser level produced it.
101
- - Re-parse only when: the original file changes, a rule requires higher-quality parsing than what is cached, or a verification failure is traced back to a parsing issue.