cognitive-modules 0.1.1__py3-none-any.whl → 0.2.0__py3-none-any.whl

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.
cognitive/loader.py CHANGED
@@ -1,17 +1,22 @@
1
1
  """
2
- Module Loader - Load cognitive modules in both old and new formats.
2
+ Module Loader - Load cognitive modules in all formats.
3
3
 
4
- Old format (6 files):
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):
5
15
  - module.md (YAML frontmatter)
6
16
  - input.schema.json
7
17
  - output.schema.json
8
18
  - constraints.yaml
9
19
  - prompt.txt
10
- - examples/
11
-
12
- New format (2 files):
13
- - MODULE.md (YAML frontmatter + prompt)
14
- - schema.json (input + output combined)
15
20
  """
16
21
 
17
22
  import json
@@ -22,13 +27,15 @@ import yaml
22
27
 
23
28
 
24
29
  def detect_format(module_path: Path) -> str:
25
- """Detect module format: 'new' or 'old'."""
26
- if (module_path / "MODULE.md").exists():
27
- return "new"
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"
28
35
  elif (module_path / "module.md").exists():
29
- return "old"
36
+ return "v0"
30
37
  else:
31
- raise FileNotFoundError(f"No MODULE.md or module.md found in {module_path}")
38
+ raise FileNotFoundError(f"No module.yaml, MODULE.md, or module.md found in {module_path}")
32
39
 
33
40
 
34
41
  def parse_frontmatter(content: str) -> tuple[dict, str]:
@@ -45,8 +52,79 @@ def parse_frontmatter(content: str) -> tuple[dict, str]:
45
52
  return frontmatter, body
46
53
 
47
54
 
48
- def load_new_format(module_path: Path) -> dict:
49
- """Load module in new format (MODULE.md + schema.json)."""
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)."""
50
128
  # Load MODULE.md
51
129
  with open(module_path / "MODULE.md", 'r', encoding='utf-8') as f:
52
130
  content = f.read()
@@ -79,8 +157,11 @@ def load_new_format(module_path: Path) -> dict:
79
157
 
80
158
  return {
81
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", []),
82
163
  "path": module_path,
83
- "format": "new",
164
+ "format": "v1",
84
165
  "metadata": metadata,
85
166
  "input_schema": input_schema,
86
167
  "output_schema": output_schema,
@@ -89,8 +170,8 @@ def load_new_format(module_path: Path) -> dict:
89
170
  }
90
171
 
91
172
 
92
- def load_old_format(module_path: Path) -> dict:
93
- """Load module in old format (6 files)."""
173
+ def load_v0_format(module_path: Path) -> dict:
174
+ """Load module in v0 format (old 6-file format)."""
94
175
  # Load module.md
95
176
  with open(module_path / "module.md", 'r', encoding='utf-8') as f:
96
177
  content = f.read()
@@ -114,8 +195,11 @@ def load_old_format(module_path: Path) -> dict:
114
195
 
115
196
  return {
116
197
  "name": metadata.get("name", module_path.name),
198
+ "version": metadata.get("version", "1.0.0"),
199
+ "responsibility": metadata.get("responsibility", ""),
200
+ "excludes": [],
117
201
  "path": module_path,
118
- "format": "old",
202
+ "format": "v0",
119
203
  "metadata": metadata,
120
204
  "input_schema": input_schema,
121
205
  "output_schema": output_schema,
@@ -127,7 +211,37 @@ def load_old_format(module_path: Path) -> dict:
127
211
  def load_module(module_path: Path) -> dict:
128
212
  """Load a module, auto-detecting format."""
129
213
  fmt = detect_format(module_path)
130
- if fmt == "new":
131
- return load_new_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)
132
218
  else:
133
- return load_old_format(module_path)
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
cognitive/templates.py CHANGED
@@ -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,15 +1,15 @@
1
1
  cognitive/__init__.py,sha256=uSX5NuOWyW0qtq1bnxbzabZ0OQakAtsjF0MWbjQBvwE,401
2
2
  cognitive/cli.py,sha256=q0vHCHFmig9gQ85KRyIrX6vrJZFm5nXF_bW5qQRGEPU,14608
3
- cognitive/loader.py,sha256=E_lSuy2ERBWfziOHr3f13nLq-wEYvBqIKrGlPk4PQyA,4031
3
+ cognitive/loader.py,sha256=i9ulJtd5Itj4QYhUYfuHOXtzCBBtY8L1EkMu5yM-0SU,8094
4
4
  cognitive/registry.py,sha256=aBkkpg5PtL_tKDIOXpv6vblB7x_Ax0eVaWgejuQTfCE,8851
5
5
  cognitive/runner.py,sha256=9uxBAGd3gtXnwUm5x2CjhXi_S1gd2nfjRfM3Q_1f30Q,4362
6
6
  cognitive/subagent.py,sha256=fb7LWwNF6YcJtC_T1dK0EvzqWMBnav-kiCIpvVohEBw,8142
7
- cognitive/templates.py,sha256=fEd1Tj5A12PUE256dC7-cnsulWzm6MTrcQ0yLPWrtx0,4692
7
+ cognitive/templates.py,sha256=lKC197X9aQIA-npUvVCaplSwvhxjsH_KYVCQtrTZrL4,4712
8
8
  cognitive/validator.py,sha256=1v1HUHYOlAc2sYCkIq_gnUMMnca0fdtQwr7UMBFpp04,12200
9
9
  cognitive/providers/__init__.py,sha256=hqhVA1IEXpVtyCAteXhO5yD8a8ikQpVIPEKJVHLtRFY,7492
10
- cognitive_modules-0.1.1.dist-info/licenses/LICENSE,sha256=NXFYUy2hPJdh3NHRxMChTnMiQD9k8zFxkmR7gWefexc,1064
11
- cognitive_modules-0.1.1.dist-info/METADATA,sha256=oonLUUD0fO3t7bo8DVZKlqC1vM5ZyHFUw7KXP46SLdI,8242
12
- cognitive_modules-0.1.1.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
13
- cognitive_modules-0.1.1.dist-info/entry_points.txt,sha256=PKHlfrFmve5K2349ryipySKbOOsKxo_vIq1NNT-iBV0,42
14
- cognitive_modules-0.1.1.dist-info/top_level.txt,sha256=kGIfDucCKylo8cRBtxER_v3DHIea-Sol9x9YSJo1u3Y,10
15
- cognitive_modules-0.1.1.dist-info/RECORD,,
10
+ cognitive_modules-0.2.0.dist-info/licenses/LICENSE,sha256=NXFYUy2hPJdh3NHRxMChTnMiQD9k8zFxkmR7gWefexc,1064
11
+ cognitive_modules-0.2.0.dist-info/METADATA,sha256=d6Jm2ALcRX56UBBvKDWn8uiLx8MIcnUhK4RLl8x2uvg,11381
12
+ cognitive_modules-0.2.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
13
+ cognitive_modules-0.2.0.dist-info/entry_points.txt,sha256=PKHlfrFmve5K2349ryipySKbOOsKxo_vIq1NNT-iBV0,42
14
+ cognitive_modules-0.2.0.dist-info/top_level.txt,sha256=kGIfDucCKylo8cRBtxER_v3DHIea-Sol9x9YSJo1u3Y,10
15
+ cognitive_modules-0.2.0.dist-info/RECORD,,