cognitive-modules 0.1.1__tar.gz → 0.2.0__tar.gz

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 (27) hide show
  1. {cognitive_modules-0.1.1/src/cognitive_modules.egg-info → cognitive_modules-0.2.0}/PKG-INFO +131 -2
  2. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/README.md +130 -1
  3. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/pyproject.toml +1 -1
  4. cognitive_modules-0.2.0/src/cognitive/loader.py +247 -0
  5. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive/templates.py +1 -1
  6. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0/src/cognitive_modules.egg-info}/PKG-INFO +131 -2
  7. cognitive_modules-0.1.1/src/cognitive/loader.py +0 -133
  8. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/LICENSE +0 -0
  9. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/setup.cfg +0 -0
  10. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive/__init__.py +0 -0
  11. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive/cli.py +0 -0
  12. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive/providers/__init__.py +0 -0
  13. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive/registry.py +0 -0
  14. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive/runner.py +0 -0
  15. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive/subagent.py +0 -0
  16. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive/validator.py +0 -0
  17. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive_modules.egg-info/SOURCES.txt +0 -0
  18. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive_modules.egg-info/dependency_links.txt +0 -0
  19. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive_modules.egg-info/entry_points.txt +0 -0
  20. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive_modules.egg-info/requires.txt +0 -0
  21. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/src/cognitive_modules.egg-info/top_level.txt +0 -0
  22. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/tests/test_cli.py +0 -0
  23. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/tests/test_loader.py +0 -0
  24. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/tests/test_registry.py +0 -0
  25. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/tests/test_runner.py +0 -0
  26. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/tests/test_subagent.py +0 -0
  27. {cognitive_modules-0.1.1 → cognitive_modules-0.2.0}/tests/test_validator.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cognitive-modules
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: Structured LLM task runner with schema validation, confidence scoring, and subagent orchestration
5
5
  Author: ziel-io
6
6
  License: MIT
@@ -151,6 +151,7 @@ cog doctor
151
151
  | 模块 | 功能 | 示例 |
152
152
  |------|------|------|
153
153
  | `code-reviewer` | 代码审查 | `cog run code-reviewer --args "你的代码"` |
154
+ | `code-simplifier` | 代码简化 | `cog run code-simplifier --args "复杂代码"` |
154
155
  | `task-prioritizer` | 任务优先级排序 | `cog run task-prioritizer --args "任务1,任务2"` |
155
156
  | `api-designer` | REST API 设计 | `cog run api-designer --args "订单系统"` |
156
157
  | `ui-spec-generator` | UI 规范生成 | `cog run ui-spec-generator --args "电商首页"` |
@@ -241,6 +242,134 @@ export LLM_PROVIDER=ollama
241
242
  cog doctor
242
243
  ```
243
244
 
245
+ ## 创建新模块(完整流程)
246
+
247
+ 以 `code-simplifier` 为例:
248
+
249
+ ### Step 1: 创建目录结构
250
+
251
+ ```bash
252
+ mkdir -p cognitive/modules/code-simplifier
253
+ ```
254
+
255
+ ### Step 2: 编写 MODULE.md
256
+
257
+ ```bash
258
+ cat > cognitive/modules/code-simplifier/MODULE.md << 'EOF'
259
+ ---
260
+ name: code-simplifier
261
+ version: 1.0.0
262
+ responsibility: Simplify complex code while preserving functionality
263
+
264
+ excludes:
265
+ - Changing the code's behavior
266
+ - Adding new features
267
+ - Removing functionality
268
+
269
+ constraints:
270
+ no_network: true
271
+ no_side_effects: true
272
+ require_confidence: true
273
+ require_rationale: true
274
+ ---
275
+
276
+ # Code Simplifier Module
277
+
278
+ You are an expert at refactoring and simplifying code.
279
+
280
+ ## Input
281
+
282
+ Code to simplify: $ARGUMENTS
283
+
284
+ ## Simplification Strategies
285
+
286
+ 1. **Remove redundancy** - Eliminate duplicate code
287
+ 2. **Improve naming** - Use clear, descriptive names
288
+ 3. **Reduce nesting** - Flatten deep conditionals
289
+ 4. **Simplify logic** - Use built-in functions
290
+
291
+ ## Output Requirements
292
+
293
+ Return JSON containing:
294
+ - `simplified_code`: The simplified version
295
+ - `changes`: List of changes made
296
+ - `summary`: Brief description
297
+ - `rationale`: Explanation of decisions
298
+ - `confidence`: Confidence score [0-1]
299
+ EOF
300
+ ```
301
+
302
+ ### Step 3: 编写 schema.json
303
+
304
+ ```bash
305
+ cat > cognitive/modules/code-simplifier/schema.json << 'EOF'
306
+ {
307
+ "$schema": "https://ziel-io.github.io/cognitive-modules/schema/v1.json",
308
+ "input": {
309
+ "type": "object",
310
+ "properties": {
311
+ "code": { "type": "string" },
312
+ "language": { "type": "string" },
313
+ "$ARGUMENTS": { "type": "string" }
314
+ }
315
+ },
316
+ "output": {
317
+ "type": "object",
318
+ "required": ["simplified_code", "changes", "summary", "rationale", "confidence"],
319
+ "properties": {
320
+ "simplified_code": { "type": "string" },
321
+ "changes": {
322
+ "type": "array",
323
+ "items": {
324
+ "type": "object",
325
+ "properties": {
326
+ "type": { "type": "string" },
327
+ "description": { "type": "string" }
328
+ }
329
+ }
330
+ },
331
+ "summary": { "type": "string" },
332
+ "rationale": { "type": "string" },
333
+ "confidence": { "type": "number", "minimum": 0, "maximum": 1 }
334
+ }
335
+ }
336
+ }
337
+ EOF
338
+ ```
339
+
340
+ ### Step 4: 验证模块
341
+
342
+ ```bash
343
+ cog validate code-simplifier
344
+ cog list # 确认模块出现在列表中
345
+ ```
346
+
347
+ ### Step 5: 测试运行
348
+
349
+ ```bash
350
+ cog run code-simplifier --args "def calc(x): if x > 0: if x < 10: return x * 2 else: return x else: return 0" --pretty
351
+ ```
352
+
353
+ ### Step 6: 添加示例(可选)
354
+
355
+ ```bash
356
+ mkdir -p cognitive/modules/code-simplifier/examples
357
+ # 添加 input.json 和 output.json 作为测试用例
358
+ ```
359
+
360
+ ### 模块设计要点
361
+
362
+ | 要素 | 必须 | 说明 |
363
+ |------|------|------|
364
+ | `name` | ✅ | 唯一标识符,kebab-case |
365
+ | `version` | ✅ | 语义化版本 |
366
+ | `responsibility` | ✅ | 一句话描述职责 |
367
+ | `excludes` | ✅ | 明确列出不做的事 |
368
+ | `$ARGUMENTS` | ✅ | 支持命令行参数 |
369
+ | `confidence` | ✅ | 输出必须包含 0-1 置信度 |
370
+ | `rationale` | ✅ | 输出必须包含推理过程 |
371
+ | `schema.json` | ✅ | 定义输入输出契约 |
372
+
244
373
  ## 开发
245
374
 
246
375
  ```bash
@@ -254,7 +383,7 @@ pip install -e ".[dev]"
254
383
  # 运行测试
255
384
  pytest tests/ -v
256
385
 
257
- # 创建新模块
386
+ # 创建新模块(使用模板)
258
387
  cog init my-module -d "模块描述"
259
388
  cog validate my-module
260
389
  ```
@@ -99,6 +99,7 @@ cog doctor
99
99
  | 模块 | 功能 | 示例 |
100
100
  |------|------|------|
101
101
  | `code-reviewer` | 代码审查 | `cog run code-reviewer --args "你的代码"` |
102
+ | `code-simplifier` | 代码简化 | `cog run code-simplifier --args "复杂代码"` |
102
103
  | `task-prioritizer` | 任务优先级排序 | `cog run task-prioritizer --args "任务1,任务2"` |
103
104
  | `api-designer` | REST API 设计 | `cog run api-designer --args "订单系统"` |
104
105
  | `ui-spec-generator` | UI 规范生成 | `cog run ui-spec-generator --args "电商首页"` |
@@ -189,6 +190,134 @@ export LLM_PROVIDER=ollama
189
190
  cog doctor
190
191
  ```
191
192
 
193
+ ## 创建新模块(完整流程)
194
+
195
+ 以 `code-simplifier` 为例:
196
+
197
+ ### Step 1: 创建目录结构
198
+
199
+ ```bash
200
+ mkdir -p cognitive/modules/code-simplifier
201
+ ```
202
+
203
+ ### Step 2: 编写 MODULE.md
204
+
205
+ ```bash
206
+ cat > cognitive/modules/code-simplifier/MODULE.md << 'EOF'
207
+ ---
208
+ name: code-simplifier
209
+ version: 1.0.0
210
+ responsibility: Simplify complex code while preserving functionality
211
+
212
+ excludes:
213
+ - Changing the code's behavior
214
+ - Adding new features
215
+ - Removing functionality
216
+
217
+ constraints:
218
+ no_network: true
219
+ no_side_effects: true
220
+ require_confidence: true
221
+ require_rationale: true
222
+ ---
223
+
224
+ # Code Simplifier Module
225
+
226
+ You are an expert at refactoring and simplifying code.
227
+
228
+ ## Input
229
+
230
+ Code to simplify: $ARGUMENTS
231
+
232
+ ## Simplification Strategies
233
+
234
+ 1. **Remove redundancy** - Eliminate duplicate code
235
+ 2. **Improve naming** - Use clear, descriptive names
236
+ 3. **Reduce nesting** - Flatten deep conditionals
237
+ 4. **Simplify logic** - Use built-in functions
238
+
239
+ ## Output Requirements
240
+
241
+ Return JSON containing:
242
+ - `simplified_code`: The simplified version
243
+ - `changes`: List of changes made
244
+ - `summary`: Brief description
245
+ - `rationale`: Explanation of decisions
246
+ - `confidence`: Confidence score [0-1]
247
+ EOF
248
+ ```
249
+
250
+ ### Step 3: 编写 schema.json
251
+
252
+ ```bash
253
+ cat > cognitive/modules/code-simplifier/schema.json << 'EOF'
254
+ {
255
+ "$schema": "https://ziel-io.github.io/cognitive-modules/schema/v1.json",
256
+ "input": {
257
+ "type": "object",
258
+ "properties": {
259
+ "code": { "type": "string" },
260
+ "language": { "type": "string" },
261
+ "$ARGUMENTS": { "type": "string" }
262
+ }
263
+ },
264
+ "output": {
265
+ "type": "object",
266
+ "required": ["simplified_code", "changes", "summary", "rationale", "confidence"],
267
+ "properties": {
268
+ "simplified_code": { "type": "string" },
269
+ "changes": {
270
+ "type": "array",
271
+ "items": {
272
+ "type": "object",
273
+ "properties": {
274
+ "type": { "type": "string" },
275
+ "description": { "type": "string" }
276
+ }
277
+ }
278
+ },
279
+ "summary": { "type": "string" },
280
+ "rationale": { "type": "string" },
281
+ "confidence": { "type": "number", "minimum": 0, "maximum": 1 }
282
+ }
283
+ }
284
+ }
285
+ EOF
286
+ ```
287
+
288
+ ### Step 4: 验证模块
289
+
290
+ ```bash
291
+ cog validate code-simplifier
292
+ cog list # 确认模块出现在列表中
293
+ ```
294
+
295
+ ### Step 5: 测试运行
296
+
297
+ ```bash
298
+ cog run code-simplifier --args "def calc(x): if x > 0: if x < 10: return x * 2 else: return x else: return 0" --pretty
299
+ ```
300
+
301
+ ### Step 6: 添加示例(可选)
302
+
303
+ ```bash
304
+ mkdir -p cognitive/modules/code-simplifier/examples
305
+ # 添加 input.json 和 output.json 作为测试用例
306
+ ```
307
+
308
+ ### 模块设计要点
309
+
310
+ | 要素 | 必须 | 说明 |
311
+ |------|------|------|
312
+ | `name` | ✅ | 唯一标识符,kebab-case |
313
+ | `version` | ✅ | 语义化版本 |
314
+ | `responsibility` | ✅ | 一句话描述职责 |
315
+ | `excludes` | ✅ | 明确列出不做的事 |
316
+ | `$ARGUMENTS` | ✅ | 支持命令行参数 |
317
+ | `confidence` | ✅ | 输出必须包含 0-1 置信度 |
318
+ | `rationale` | ✅ | 输出必须包含推理过程 |
319
+ | `schema.json` | ✅ | 定义输入输出契约 |
320
+
192
321
  ## 开发
193
322
 
194
323
  ```bash
@@ -202,7 +331,7 @@ pip install -e ".[dev]"
202
331
  # 运行测试
203
332
  pytest tests/ -v
204
333
 
205
- # 创建新模块
334
+ # 创建新模块(使用模板)
206
335
  cog init my-module -d "模块描述"
207
336
  cog validate my-module
208
337
  ```
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cognitive-modules"
7
- version = "0.1.1"
7
+ version = "0.2.0"
8
8
  description = "Structured LLM task runner with schema validation, confidence scoring, and subagent orchestration"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -0,0 +1,247 @@
1
+ """
2
+ Module Loader - Load cognitive modules in all formats.
3
+
4
+ Format v2 (recommended):
5
+ - module.yaml (machine-readable manifest)
6
+ - prompt.md (human-readable prompt)
7
+ - schema.json (input + output + error)
8
+ - tests/ (golden tests)
9
+
10
+ Format v1 (legacy, still supported):
11
+ - MODULE.md (YAML frontmatter + prompt)
12
+ - schema.json (input + output)
13
+
14
+ Format v0 (old, deprecated):
15
+ - module.md (YAML frontmatter)
16
+ - input.schema.json
17
+ - output.schema.json
18
+ - constraints.yaml
19
+ - prompt.txt
20
+ """
21
+
22
+ import json
23
+ from pathlib import Path
24
+ from typing import Optional
25
+
26
+ import yaml
27
+
28
+
29
+ def detect_format(module_path: Path) -> str:
30
+ """Detect module format: 'v2', 'v1', or 'v0'."""
31
+ if (module_path / "module.yaml").exists():
32
+ return "v2"
33
+ elif (module_path / "MODULE.md").exists():
34
+ return "v1"
35
+ elif (module_path / "module.md").exists():
36
+ return "v0"
37
+ else:
38
+ raise FileNotFoundError(f"No module.yaml, MODULE.md, or module.md found in {module_path}")
39
+
40
+
41
+ def parse_frontmatter(content: str) -> tuple[dict, str]:
42
+ """Parse YAML frontmatter from markdown content."""
43
+ if not content.startswith('---'):
44
+ return {}, content
45
+
46
+ parts = content.split('---', 2)
47
+ if len(parts) < 3:
48
+ return {}, content
49
+
50
+ frontmatter = yaml.safe_load(parts[1]) or {}
51
+ body = parts[2].strip()
52
+ return frontmatter, body
53
+
54
+
55
+ def load_v2_format(module_path: Path) -> dict:
56
+ """Load module in v2 format (module.yaml + prompt.md + schema.json)."""
57
+ # Load module.yaml
58
+ with open(module_path / "module.yaml", 'r', encoding='utf-8') as f:
59
+ manifest = yaml.safe_load(f)
60
+
61
+ # Load prompt.md
62
+ prompt_path = module_path / "prompt.md"
63
+ if prompt_path.exists():
64
+ with open(prompt_path, 'r', encoding='utf-8') as f:
65
+ prompt = f.read()
66
+ else:
67
+ prompt = ""
68
+
69
+ # Load schema.json
70
+ schema_path = module_path / "schema.json"
71
+ if schema_path.exists():
72
+ with open(schema_path, 'r', encoding='utf-8') as f:
73
+ schema = json.load(f)
74
+ input_schema = schema.get("input", {})
75
+ output_schema = schema.get("output", {})
76
+ error_schema = schema.get("error", {})
77
+ else:
78
+ input_schema = {}
79
+ output_schema = {}
80
+ error_schema = {}
81
+
82
+ # Extract constraints
83
+ constraints_raw = manifest.get("constraints", {})
84
+ constraints = {
85
+ "operational": {
86
+ "no_external_network": constraints_raw.get("no_network", True),
87
+ "no_side_effects": constraints_raw.get("no_side_effects", True),
88
+ "no_file_write": constraints_raw.get("no_file_write", True),
89
+ "no_inventing_data": constraints_raw.get("no_inventing_data", True),
90
+ },
91
+ "output_quality": {
92
+ "require_confidence": manifest.get("output", {}).get("require_confidence", True),
93
+ "require_rationale": manifest.get("output", {}).get("require_rationale", True),
94
+ "require_behavior_equivalence": manifest.get("output", {}).get("require_behavior_equivalence", False),
95
+ }
96
+ }
97
+
98
+ # Extract tools policy
99
+ tools = manifest.get("tools", {})
100
+
101
+ # Extract output contract
102
+ output_contract = manifest.get("output", {})
103
+
104
+ # Extract failure contract
105
+ failure_contract = manifest.get("failure", {})
106
+
107
+ return {
108
+ "name": manifest.get("name", module_path.name),
109
+ "version": manifest.get("version", "1.0.0"),
110
+ "responsibility": manifest.get("responsibility", ""),
111
+ "excludes": manifest.get("excludes", []),
112
+ "path": module_path,
113
+ "format": "v2",
114
+ "metadata": manifest,
115
+ "input_schema": input_schema,
116
+ "output_schema": output_schema,
117
+ "error_schema": error_schema,
118
+ "constraints": constraints,
119
+ "tools": tools,
120
+ "output_contract": output_contract,
121
+ "failure_contract": failure_contract,
122
+ "prompt": prompt,
123
+ }
124
+
125
+
126
+ def load_v1_format(module_path: Path) -> dict:
127
+ """Load module in v1 format (MODULE.md + schema.json)."""
128
+ # Load MODULE.md
129
+ with open(module_path / "MODULE.md", 'r', encoding='utf-8') as f:
130
+ content = f.read()
131
+
132
+ metadata, prompt = parse_frontmatter(content)
133
+
134
+ # Extract constraints from metadata
135
+ constraints = {
136
+ "operational": {
137
+ "no_external_network": metadata.get("constraints", {}).get("no_network", True),
138
+ "no_side_effects": metadata.get("constraints", {}).get("no_side_effects", True),
139
+ "no_inventing_data": metadata.get("constraints", {}).get("no_inventing_data", True),
140
+ },
141
+ "output_quality": {
142
+ "require_confidence": metadata.get("constraints", {}).get("require_confidence", True),
143
+ "require_rationale": metadata.get("constraints", {}).get("require_rationale", True),
144
+ }
145
+ }
146
+
147
+ # Load schema.json
148
+ schema_path = module_path / "schema.json"
149
+ if schema_path.exists():
150
+ with open(schema_path, 'r', encoding='utf-8') as f:
151
+ schema = json.load(f)
152
+ input_schema = schema.get("input", {})
153
+ output_schema = schema.get("output", {})
154
+ else:
155
+ input_schema = {}
156
+ output_schema = {}
157
+
158
+ return {
159
+ "name": metadata.get("name", module_path.name),
160
+ "version": metadata.get("version", "1.0.0"),
161
+ "responsibility": metadata.get("responsibility", ""),
162
+ "excludes": metadata.get("excludes", []),
163
+ "path": module_path,
164
+ "format": "v1",
165
+ "metadata": metadata,
166
+ "input_schema": input_schema,
167
+ "output_schema": output_schema,
168
+ "constraints": constraints,
169
+ "prompt": prompt,
170
+ }
171
+
172
+
173
+ def load_v0_format(module_path: Path) -> dict:
174
+ """Load module in v0 format (old 6-file format)."""
175
+ # Load module.md
176
+ with open(module_path / "module.md", 'r', encoding='utf-8') as f:
177
+ content = f.read()
178
+
179
+ metadata, _ = parse_frontmatter(content)
180
+
181
+ # Load schemas
182
+ with open(module_path / "input.schema.json", 'r', encoding='utf-8') as f:
183
+ input_schema = json.load(f)
184
+
185
+ with open(module_path / "output.schema.json", 'r', encoding='utf-8') as f:
186
+ output_schema = json.load(f)
187
+
188
+ # Load constraints
189
+ with open(module_path / "constraints.yaml", 'r', encoding='utf-8') as f:
190
+ constraints = yaml.safe_load(f)
191
+
192
+ # Load prompt
193
+ with open(module_path / "prompt.txt", 'r', encoding='utf-8') as f:
194
+ prompt = f.read()
195
+
196
+ return {
197
+ "name": metadata.get("name", module_path.name),
198
+ "version": metadata.get("version", "1.0.0"),
199
+ "responsibility": metadata.get("responsibility", ""),
200
+ "excludes": [],
201
+ "path": module_path,
202
+ "format": "v0",
203
+ "metadata": metadata,
204
+ "input_schema": input_schema,
205
+ "output_schema": output_schema,
206
+ "constraints": constraints,
207
+ "prompt": prompt,
208
+ }
209
+
210
+
211
+ def load_module(module_path: Path) -> dict:
212
+ """Load a module, auto-detecting format."""
213
+ fmt = detect_format(module_path)
214
+ if fmt == "v2":
215
+ return load_v2_format(module_path)
216
+ elif fmt == "v1":
217
+ return load_v1_format(module_path)
218
+ else:
219
+ return load_v0_format(module_path)
220
+
221
+
222
+ def find_module(name: str, search_paths: list[Path]) -> Optional[dict]:
223
+ """Find and load a module by name from search paths."""
224
+ for base_path in search_paths:
225
+ module_path = base_path / name
226
+ if module_path.exists():
227
+ try:
228
+ return load_module(module_path)
229
+ except FileNotFoundError:
230
+ continue
231
+ return None
232
+
233
+
234
+ def list_modules(search_paths: list[Path]) -> list[dict]:
235
+ """List all modules in search paths."""
236
+ modules = []
237
+ for base_path in search_paths:
238
+ if not base_path.exists():
239
+ continue
240
+ for module_dir in base_path.iterdir():
241
+ if module_dir.is_dir():
242
+ try:
243
+ module = load_module(module_dir)
244
+ modules.append(module)
245
+ except FileNotFoundError:
246
+ continue
247
+ return modules
@@ -83,7 +83,7 @@ EXAMPLE_OUTPUT = {
83
83
  def get_schema_template(name: str) -> dict:
84
84
  """Generate schema template as dict."""
85
85
  return {
86
- "$schema": "https://cognitive-modules.io/schema/v1",
86
+ "$schema": "https://ziel-io.github.io/cognitive-modules/schema/v1.json",
87
87
  "$id": name,
88
88
  "title": f"{name.replace('-', ' ').title()} Schema",
89
89
  "input": {
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cognitive-modules
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: Structured LLM task runner with schema validation, confidence scoring, and subagent orchestration
5
5
  Author: ziel-io
6
6
  License: MIT
@@ -151,6 +151,7 @@ cog doctor
151
151
  | 模块 | 功能 | 示例 |
152
152
  |------|------|------|
153
153
  | `code-reviewer` | 代码审查 | `cog run code-reviewer --args "你的代码"` |
154
+ | `code-simplifier` | 代码简化 | `cog run code-simplifier --args "复杂代码"` |
154
155
  | `task-prioritizer` | 任务优先级排序 | `cog run task-prioritizer --args "任务1,任务2"` |
155
156
  | `api-designer` | REST API 设计 | `cog run api-designer --args "订单系统"` |
156
157
  | `ui-spec-generator` | UI 规范生成 | `cog run ui-spec-generator --args "电商首页"` |
@@ -241,6 +242,134 @@ export LLM_PROVIDER=ollama
241
242
  cog doctor
242
243
  ```
243
244
 
245
+ ## 创建新模块(完整流程)
246
+
247
+ 以 `code-simplifier` 为例:
248
+
249
+ ### Step 1: 创建目录结构
250
+
251
+ ```bash
252
+ mkdir -p cognitive/modules/code-simplifier
253
+ ```
254
+
255
+ ### Step 2: 编写 MODULE.md
256
+
257
+ ```bash
258
+ cat > cognitive/modules/code-simplifier/MODULE.md << 'EOF'
259
+ ---
260
+ name: code-simplifier
261
+ version: 1.0.0
262
+ responsibility: Simplify complex code while preserving functionality
263
+
264
+ excludes:
265
+ - Changing the code's behavior
266
+ - Adding new features
267
+ - Removing functionality
268
+
269
+ constraints:
270
+ no_network: true
271
+ no_side_effects: true
272
+ require_confidence: true
273
+ require_rationale: true
274
+ ---
275
+
276
+ # Code Simplifier Module
277
+
278
+ You are an expert at refactoring and simplifying code.
279
+
280
+ ## Input
281
+
282
+ Code to simplify: $ARGUMENTS
283
+
284
+ ## Simplification Strategies
285
+
286
+ 1. **Remove redundancy** - Eliminate duplicate code
287
+ 2. **Improve naming** - Use clear, descriptive names
288
+ 3. **Reduce nesting** - Flatten deep conditionals
289
+ 4. **Simplify logic** - Use built-in functions
290
+
291
+ ## Output Requirements
292
+
293
+ Return JSON containing:
294
+ - `simplified_code`: The simplified version
295
+ - `changes`: List of changes made
296
+ - `summary`: Brief description
297
+ - `rationale`: Explanation of decisions
298
+ - `confidence`: Confidence score [0-1]
299
+ EOF
300
+ ```
301
+
302
+ ### Step 3: 编写 schema.json
303
+
304
+ ```bash
305
+ cat > cognitive/modules/code-simplifier/schema.json << 'EOF'
306
+ {
307
+ "$schema": "https://ziel-io.github.io/cognitive-modules/schema/v1.json",
308
+ "input": {
309
+ "type": "object",
310
+ "properties": {
311
+ "code": { "type": "string" },
312
+ "language": { "type": "string" },
313
+ "$ARGUMENTS": { "type": "string" }
314
+ }
315
+ },
316
+ "output": {
317
+ "type": "object",
318
+ "required": ["simplified_code", "changes", "summary", "rationale", "confidence"],
319
+ "properties": {
320
+ "simplified_code": { "type": "string" },
321
+ "changes": {
322
+ "type": "array",
323
+ "items": {
324
+ "type": "object",
325
+ "properties": {
326
+ "type": { "type": "string" },
327
+ "description": { "type": "string" }
328
+ }
329
+ }
330
+ },
331
+ "summary": { "type": "string" },
332
+ "rationale": { "type": "string" },
333
+ "confidence": { "type": "number", "minimum": 0, "maximum": 1 }
334
+ }
335
+ }
336
+ }
337
+ EOF
338
+ ```
339
+
340
+ ### Step 4: 验证模块
341
+
342
+ ```bash
343
+ cog validate code-simplifier
344
+ cog list # 确认模块出现在列表中
345
+ ```
346
+
347
+ ### Step 5: 测试运行
348
+
349
+ ```bash
350
+ cog run code-simplifier --args "def calc(x): if x > 0: if x < 10: return x * 2 else: return x else: return 0" --pretty
351
+ ```
352
+
353
+ ### Step 6: 添加示例(可选)
354
+
355
+ ```bash
356
+ mkdir -p cognitive/modules/code-simplifier/examples
357
+ # 添加 input.json 和 output.json 作为测试用例
358
+ ```
359
+
360
+ ### 模块设计要点
361
+
362
+ | 要素 | 必须 | 说明 |
363
+ |------|------|------|
364
+ | `name` | ✅ | 唯一标识符,kebab-case |
365
+ | `version` | ✅ | 语义化版本 |
366
+ | `responsibility` | ✅ | 一句话描述职责 |
367
+ | `excludes` | ✅ | 明确列出不做的事 |
368
+ | `$ARGUMENTS` | ✅ | 支持命令行参数 |
369
+ | `confidence` | ✅ | 输出必须包含 0-1 置信度 |
370
+ | `rationale` | ✅ | 输出必须包含推理过程 |
371
+ | `schema.json` | ✅ | 定义输入输出契约 |
372
+
244
373
  ## 开发
245
374
 
246
375
  ```bash
@@ -254,7 +383,7 @@ pip install -e ".[dev]"
254
383
  # 运行测试
255
384
  pytest tests/ -v
256
385
 
257
- # 创建新模块
386
+ # 创建新模块(使用模板)
258
387
  cog init my-module -d "模块描述"
259
388
  cog validate my-module
260
389
  ```
@@ -1,133 +0,0 @@
1
- """
2
- Module Loader - Load cognitive modules in both old and new formats.
3
-
4
- Old format (6 files):
5
- - module.md (YAML frontmatter)
6
- - input.schema.json
7
- - output.schema.json
8
- - constraints.yaml
9
- - prompt.txt
10
- - examples/
11
-
12
- New format (2 files):
13
- - MODULE.md (YAML frontmatter + prompt)
14
- - schema.json (input + output combined)
15
- """
16
-
17
- import json
18
- from pathlib import Path
19
- from typing import Optional
20
-
21
- import yaml
22
-
23
-
24
- def detect_format(module_path: Path) -> str:
25
- """Detect module format: 'new' or 'old'."""
26
- if (module_path / "MODULE.md").exists():
27
- return "new"
28
- elif (module_path / "module.md").exists():
29
- return "old"
30
- else:
31
- raise FileNotFoundError(f"No MODULE.md or module.md found in {module_path}")
32
-
33
-
34
- def parse_frontmatter(content: str) -> tuple[dict, str]:
35
- """Parse YAML frontmatter from markdown content."""
36
- if not content.startswith('---'):
37
- return {}, content
38
-
39
- parts = content.split('---', 2)
40
- if len(parts) < 3:
41
- return {}, content
42
-
43
- frontmatter = yaml.safe_load(parts[1]) or {}
44
- body = parts[2].strip()
45
- return frontmatter, body
46
-
47
-
48
- def load_new_format(module_path: Path) -> dict:
49
- """Load module in new format (MODULE.md + schema.json)."""
50
- # Load MODULE.md
51
- with open(module_path / "MODULE.md", 'r', encoding='utf-8') as f:
52
- content = f.read()
53
-
54
- metadata, prompt = parse_frontmatter(content)
55
-
56
- # Extract constraints from metadata
57
- constraints = {
58
- "operational": {
59
- "no_external_network": metadata.get("constraints", {}).get("no_network", True),
60
- "no_side_effects": metadata.get("constraints", {}).get("no_side_effects", True),
61
- "no_inventing_data": metadata.get("constraints", {}).get("no_inventing_data", True),
62
- },
63
- "output_quality": {
64
- "require_confidence": metadata.get("constraints", {}).get("require_confidence", True),
65
- "require_rationale": metadata.get("constraints", {}).get("require_rationale", True),
66
- }
67
- }
68
-
69
- # Load schema.json
70
- schema_path = module_path / "schema.json"
71
- if schema_path.exists():
72
- with open(schema_path, 'r', encoding='utf-8') as f:
73
- schema = json.load(f)
74
- input_schema = schema.get("input", {})
75
- output_schema = schema.get("output", {})
76
- else:
77
- input_schema = {}
78
- output_schema = {}
79
-
80
- return {
81
- "name": metadata.get("name", module_path.name),
82
- "path": module_path,
83
- "format": "new",
84
- "metadata": metadata,
85
- "input_schema": input_schema,
86
- "output_schema": output_schema,
87
- "constraints": constraints,
88
- "prompt": prompt,
89
- }
90
-
91
-
92
- def load_old_format(module_path: Path) -> dict:
93
- """Load module in old format (6 files)."""
94
- # Load module.md
95
- with open(module_path / "module.md", 'r', encoding='utf-8') as f:
96
- content = f.read()
97
-
98
- metadata, _ = parse_frontmatter(content)
99
-
100
- # Load schemas
101
- with open(module_path / "input.schema.json", 'r', encoding='utf-8') as f:
102
- input_schema = json.load(f)
103
-
104
- with open(module_path / "output.schema.json", 'r', encoding='utf-8') as f:
105
- output_schema = json.load(f)
106
-
107
- # Load constraints
108
- with open(module_path / "constraints.yaml", 'r', encoding='utf-8') as f:
109
- constraints = yaml.safe_load(f)
110
-
111
- # Load prompt
112
- with open(module_path / "prompt.txt", 'r', encoding='utf-8') as f:
113
- prompt = f.read()
114
-
115
- return {
116
- "name": metadata.get("name", module_path.name),
117
- "path": module_path,
118
- "format": "old",
119
- "metadata": metadata,
120
- "input_schema": input_schema,
121
- "output_schema": output_schema,
122
- "constraints": constraints,
123
- "prompt": prompt,
124
- }
125
-
126
-
127
- def load_module(module_path: Path) -> dict:
128
- """Load a module, auto-detecting format."""
129
- fmt = detect_format(module_path)
130
- if fmt == "new":
131
- return load_new_format(module_path)
132
- else:
133
- return load_old_format(module_path)