agent-prompt-engineering 0.1.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.
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-prompt-engineering
3
+ Version: 0.1.0
4
+ Summary: Deterministic data->prompt builder + cognition chains + optional grammar gate — the shared base of the chaincompiler ecosystem.
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: rulecatcher
9
+ Requires-Dist: agent-skilltree>=0.2.1
10
+
11
+ ---
12
+ name: prompt-engineering
13
+ description: The Prompt Engineering System — a deterministic prompt builder. Give it a payload (a "block": attributes + methods + a render sequence) and it produces the SAME prompt every time. Compose blocks into stored "prompt templates". Use it to make system prompts, personas, rule blocks, few-shot blocks, or any prompt. No model call, no randomness.
14
+ when_to_use: Building or reusing prompts/personas/templates programmatically; you want the same spec to render the same prompt every time; making a new prompt template (folder of blocks).
15
+ ---
16
+
17
+ # Prompt Engineering System
18
+
19
+ A skill (this `SKILL.md` + the code beside it) that turns **data → a prompt**, deterministically. The
20
+ model decides *what* spec to write; this engine guarantees *how* it renders — same inputs, same output,
21
+ every time. That reliability is the point: an agent reads this skill and uses it to make prompts/personas
22
+ the same way each time.
23
+
24
+ ## Vocabulary
25
+
26
+ - **block** — one payload (`values` + `methods` + a `template_sequence`) that renders to a chunk of prompt
27
+ - **prompt template** — a stored, ordered set of blocks (a folder under `templates/`) that renders to one
28
+ full prompt
29
+
30
+ There is **no baked-in structure and no "levels."** You bring your own via blocks and templates.
31
+
32
+ ## Use it (the package `prompt_engineering`)
33
+
34
+ ```python
35
+ # pip install -e . (or add this skill dir to sys.path for in-place use)
36
+ from prompt_engineering import render, render_template, list_templates
37
+
38
+ # 1) render a single block from a payload
39
+ render({
40
+ "values": {"role": "Worldsmith", "domain": "otters"},
41
+ "methods": [
42
+ {"name": "format_title", "func": "return f'# {self.role}'", "add_to_sequence": True},
43
+ {"name": "format_intro", "func": "return f'You are the {self.role} of {self.domain}.'", "add_to_sequence": True},
44
+ ],
45
+ }) # → "# Worldsmith\n\nYou are the Worldsmith of otters." (same payload → same prompt, always)
46
+
47
+ # 2) render a stored prompt template (its blocks, joined in order)
48
+ list_templates() # ['five_level', 'simple_agent']
49
+ render_template("five_level") # → one prompt with WORLD/EGREGORE/DEITY/PROGENITOR/AGENT sections
50
+ ```
51
+
52
+ Or from the shell (see `scripts/` below): `python scripts/make_prompt.py --template five_level`.
53
+
54
+ > **Naming tip:** name block methods `format_*` so they don't shadow the `values` they read
55
+ > (a method `duty` would overwrite the value `duty`; `format_duty` reading `self.duty` is correct).
56
+
57
+ ## Add a prompt template — DROP A FOLDER
58
+
59
+ ```
60
+ templates/
61
+ {template_name}/
62
+ template.json # {name, description, blocks: ["block1.json", "block2.json", ...]}
63
+ {block}.json # the block payloads (any structure you want)
64
+ ```
65
+
66
+ Create the folder, write `template.json`, drop in the block payloads. Nothing in the engine changes.
67
+ `list_templates()` / `render_template(name)` pick it up by convention.
68
+
69
+ ## Resource files (referenced by relative path)
70
+
71
+ - `prompt_engineering/prompt_engine.py` — the API: `render`, `render_file`, `list_templates`, `load_template`,
72
+ `render_template`, `render_template_blocks`
73
+ - `prompt_engineering/template_mixins.py` — the engine internals (add attributes/methods from data; run a sequence)
74
+ - `examples/` — single-block payloads for different **prompt block types** (system, persona, rules,
75
+ few-shot, constraints, output-format) and full personas — read these to learn the block format
76
+ - `templates/five_level/` — the 5-level model **as a prompt template** (an example, not a default)
77
+ - `templates/simple_agent/` — a one-block template (proves the add-by-folder mechanic)
78
+ - `prompt_engineering/cognition.py` — the cognition-chain stack (attention chain / chain-of-reasoning / skill chain) on
79
+ the engine, + `validate_chain` (a shallow no-dep broken-detector)
80
+ - `prompt_engineering/gate.py` — the REAL gate: `gate(text, exemplars)` LEARNS the grammar from exemplar chains (you don't
81
+ hand-write the error rules) → violations + fixes + the `orthogonal`/`syntax_break` (steerable/fatal) verdict
82
+ - **`rulecatcher`** — the grammar learner/linter the gate runs on; now an installed dependency (D3, un-vendored)
83
+ - `prompt_engineering/persona.py` — `make_persona(spec)` / `make_persona_file(path)`: generate a full persona prompt
84
+ (block types + a cognition DSL block) from a small spec
85
+ - `examples/persona_*.json` — example persona systems (debugger, socratic, code-reviewer) with reasoning DSLs
86
+ - `scripts/make_prompt.py` — render a block/template from the command line
87
+ - `scripts/make_persona.py` — generate a persona prompt from a spec file
88
+ - `scripts/new_template_skill.py` — scaffold a NEW skill package for a prompt template
89
+ - `test_prompt_engine.py` · `test_cognition.py` · `test_persona.py` · `test_gate.py` — run to verify (all NO-API)
90
+
91
+ ## Cognition chains & personas (the ACCC/CORCC/SCCC stack, rebuilt right)
92
+
93
+ `prompt_engineering/cognition.py` is the clean version of the old `*CC` "compiler-compilers": an **attention chain**, a
94
+ **chain-of-reasoning**, and a **skill chain** are just prompt templates composed on this engine (a CoR
95
+ *nests* an AC = block-nesting). **Rendering never touches a grammar engine or a DB.**
96
+
97
+ The **gate is a separate, optional layer** (`prompt_engineering/gate.py`, on the **`rulecatcher`** package). You don't
98
+ hand-write the error rules: `gate(text, exemplars)` LEARNS the grammar from the template's exemplar chains
99
+ (`next_kind` = shape, `next_token` = vocabulary), then lints a candidate → violations + fixes + the
100
+ `orthogonal` (in the language, wrong slot → **steerable**) vs `syntax_break` (foreign → **fatal**) verdict.
101
+ `rulecatcher` is an installed dependency (D3), so the real gate runs everywhere it's installed.
102
+ (`validate_chain` remains a shallow no-dep fallback.)
103
+
104
+ ```python
105
+ from prompt_engineering import render_cor, gate, make_persona
106
+
107
+ render_cor("Debugger", ["Symptom", "Repro", "Hypothesis"], "Localize", "the root cause") # a CoR persona
108
+ gate("[Goal] ⇒ [Repro] ⇒ |Localize|", # learn from exemplars, then lint:
109
+ exemplars=["[Symptom] ⇒ [Repro] ⇒ |Localize|", "[Symptom] ⇒ [Bisect] ⇒ |RootCause|"])
110
+ # → {ok: False, verdict: 'orthogonal', violations: [{found:'Goal', candidates:['Symptom'], ...}]}
111
+
112
+ make_persona({ # a whole persona with a complex reasoning DSL, in one call
113
+ "name": "Ada", "role": "a senior debugger",
114
+ "reasoning": {"foci": ["Symptom", "Repro", "Bisect"], "held": "RootCause", "decision": "the minimal fix"},
115
+ "rules": ["Reproduce before theorizing."], "output": "A markdown report.",
116
+ })
117
+ ```
118
+
119
+ ## Why deterministic matters
120
+
121
+ `render` runs the `template_sequence` in order and joins the non-empty results — pure composition, no
122
+ model call. That's what lets an agent rely on it to produce prompts consistently across runs.
@@ -0,0 +1,25 @@
1
+ prompt_engineering/__init__.py,sha256=Yb_3jnNjUrlTVpwlMrUiUiY1aFq_FKxPAS_Uz0vx7KU,2788
2
+ prompt_engineering/cognition.py,sha256=c0VXZ9DzF-R2e_5fdOQZO-akVAvygNPa5xCllnTuhB4,8271
3
+ prompt_engineering/gate.py,sha256=K3Rzr5oTJC_REXddIc_20z3ntvr9mJ9Gabp_V5oulB8,3270
4
+ prompt_engineering/grammar.py,sha256=UZtnpmLFtCgGacyg7Jza8O-_5ihpLK_vEiqD_voji4c,5620
5
+ prompt_engineering/persona.py,sha256=wdArt3Jz9H2pgo71k0Tik50prq-uwWM9b3Eh_YizHlI,2487
6
+ prompt_engineering/prompt_engine.py,sha256=kWw8MBGY7T0UvR6F5PBTKlvoA3i4f8VIEnX1RXHT3E4,5032
7
+ prompt_engineering/skillpack.py,sha256=5gv3mr3OGzl3QEL59S8UCdfh7jEgCJP-zqAQpRTwm-4,3413
8
+ prompt_engineering/template_mixins.py,sha256=5Pn-X8ExYFqvne1YdVWnuEzYp_Q9C38WxM16HsroYuQ,6735
9
+ prompt_engineering/templates/five_level/agent.json,sha256=evTr98fNfS5jLBhqmLzyhHPFNSdDM271qYhtGJgEE88,191
10
+ prompt_engineering/templates/five_level/deity.json,sha256=0EjJnxRnGMT-B4ArHcr0kTsLAgc_I5nhFjg903nVXec,195
11
+ prompt_engineering/templates/five_level/egregore.json,sha256=9qHxviMenrY6GxgOuRwHjPIKYeqOwkWIOr2q-tRr1Kg,212
12
+ prompt_engineering/templates/five_level/progenitor.json,sha256=ehG29qAQ08lkTxiZu-i0ZpexT0Jg9P2gtH2C2YUjxeA,202
13
+ prompt_engineering/templates/five_level/template.json,sha256=PIBVeMmnWGac3r0iCpJC-n4woBsDhiILx0Kdzloskmk,320
14
+ prompt_engineering/templates/five_level/world.json,sha256=TT09VvvgAfaRU1Slc0mDbJD4kZEQgyGMEeqRQlhwuBA,204
15
+ prompt_engineering/templates/persona/output_format.json,sha256=_Bb_VxzCR2W2mXb4Kh_Dvz_fhS0PcwIzgwMdc0swn-k,221
16
+ prompt_engineering/templates/persona/persona.json,sha256=cbzsBLstxsQEJ2l2BTf6Zq38QynnagoZE4mGgsHBElI,289
17
+ prompt_engineering/templates/persona/rules.json,sha256=q0N3aLoX3-NwsIpybf0AeoBLYMwQakhmViVI3mbW02E,266
18
+ prompt_engineering/templates/persona/system.json,sha256=fu3gbZ54IOTYP-MGGoxsmLlNquiv9xTH0cgeXR-O0hc,274
19
+ prompt_engineering/templates/persona/template.json,sha256=0eqVWzT36Iexn68qbhIKl4Q2gsVDv5ziShcCtlFRIp8,314
20
+ prompt_engineering/templates/simple_agent/agent.json,sha256=2YAABemipKQ_ucOfdx-kTWqdTSqrqNRLMd3Q1irNEKo,209
21
+ prompt_engineering/templates/simple_agent/template.json,sha256=9Z-EZAp4b7Elgzo_fH4dXaM_meY65ORUOBsqPTj_q4c,191
22
+ agent_prompt_engineering-0.1.0.dist-info/METADATA,sha256=KJMD9HUcIV1rETom_J9qYG_6NgU7XQn26n6hlJu5WKM,7189
23
+ agent_prompt_engineering-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
24
+ agent_prompt_engineering-0.1.0.dist-info/top_level.txt,sha256=vQLdvbxTqmcjw9guOp16s-z0739moFHRxoD-5RUCk4g,19
25
+ agent_prompt_engineering-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ prompt_engineering
@@ -0,0 +1,65 @@
1
+ """
2
+ prompt_engineering — the deterministic prompt-engine base.
3
+
4
+ THE shared foundation of the chaincompiler ecosystem (rule: everyone imports DOWN from here).
5
+ Three layers, all stdlib except the optional `rulecatcher` dep behind the gate:
6
+ - prompt_engine + template_mixins : data -> prompt, deterministic (same input -> same output)
7
+ - cognition : attention-chain / chain-of-reasoning / skill-chain as templates
8
+ - gate (optional) : learned-grammar lint on the `rulecatcher` package
9
+
10
+ P1 (see chaincompiler/REBUILD-SPEC.md) — now folded in so accc/corcc/sccc import DOWN from here:
11
+ - grammar : the rulecatcher seam (learn / gate / grammar_lines / foreign_tokens), PERSISTENT scope
12
+ - skillpack: write_skill / slugify / skill_markdown (D4: skilltree-aware placement is the next step)
13
+ """
14
+
15
+ from .prompt_engine import (
16
+ Template,
17
+ build_template,
18
+ render,
19
+ render_file,
20
+ templates_root,
21
+ list_templates,
22
+ load_template,
23
+ render_template,
24
+ render_template_blocks,
25
+ )
26
+ from .template_mixins import TemplateAttributeMixin, TemplateMethodMixin
27
+ from .cognition import (
28
+ chain_notation,
29
+ parse_chain,
30
+ validate_chain,
31
+ attention_block_payload,
32
+ cor_skeleton,
33
+ cor_payload,
34
+ skillchain_payload,
35
+ render_attention_chain,
36
+ render_cor,
37
+ render_skillchain,
38
+ )
39
+ from .persona import make_persona, make_persona_file
40
+ from .gate import gate
41
+ # the rulecatcher seam (PERSISTENT, connection-based) — moved down from chaincompiler.bridge (§4).
42
+ # NOTE: the persistent gate(connection, chain, *, scope) is intentionally NOT re-exported at top level
43
+ # (it would clash with the ephemeral gate(text, exemplars) above) — use `prompt_engineering.grammar.gate`.
44
+ from .grammar import learn, grammar_lines, foreign_tokens
45
+ # the skill-packager — moved down from chaincompiler.skillpack (§7); skilltree-aware (D4).
46
+ from .skillpack import slugify, skill_markdown, write_skill, cohere_skills
47
+
48
+ __all__ = [
49
+ # deterministic prompt engine
50
+ "Template", "build_template", "render", "render_file", "templates_root",
51
+ "list_templates", "load_template", "render_template", "render_template_blocks",
52
+ "TemplateAttributeMixin", "TemplateMethodMixin",
53
+ # cognition chains
54
+ "chain_notation", "parse_chain", "validate_chain",
55
+ "attention_block_payload", "cor_skeleton", "cor_payload", "skillchain_payload",
56
+ "render_attention_chain", "render_cor", "render_skillchain",
57
+ # personas
58
+ "make_persona", "make_persona_file",
59
+ # optional grammar gate (ephemeral) + the persistent rulecatcher seam (grammar.py)
60
+ "gate", "learn", "grammar_lines", "foreign_tokens",
61
+ # skill-packager (skilltree-aware, D4)
62
+ "slugify", "skill_markdown", "write_skill", "cohere_skills",
63
+ ]
64
+
65
+ __version__ = "0.1.0"
@@ -0,0 +1,149 @@
1
+ """
2
+ cognition.py — the cognition-chain stack (ACCC / CORCC / SCCC) rebuilt the RIGHT way, on the prompt engine.
3
+
4
+ The old *CC packages buried prompt-making under a grammar-induction-and-gating tower (rulecatcher `learn`
5
+ → a SQLite DB → `gate`). The clean version:
6
+
7
+ - an attention chain (AC), a chain-of-reasoning (CoR), and a skill chain (SC) are PROMPT TEMPLATES —
8
+ authored blocks composed deterministically on prompt_engine (a CoR NESTS an AC = block-nesting).
9
+ - the validator (the "tells you when an instance is broken" part) is DERIVED FROM THE TEMPLATE: you
10
+ author the shape (+ optional vocabulary) once, and validate_chain() checks conformance directly.
11
+ No induction, no DB. That is the rule-learner's real intent — "make your DSL out of templates, and it
12
+ tells you when it's broken" — without the machinery.
13
+
14
+ attention chain [A] ⇒ [B] ⇒ |Held| inner "how to think" scaffold
15
+ chain of reasoning a CoR nests an AC + a spoken paragraph that ends in a DECISION
16
+ skill chain [ac:x] ⇒ [cor:y] ⇒ [skill:z] ⇒ |Goal| resolved steps, rolled up
17
+ """
18
+
19
+ import re
20
+ from typing import List, Optional, Tuple
21
+
22
+ try:
23
+ from .prompt_engine import render
24
+ except ImportError:
25
+ from prompt_engine import render
26
+
27
+ ARROW = "⇒"
28
+ _FOCUS = re.compile(r"\[([^\]]+)\]")
29
+ _HELD = re.compile(r"\|([^|]+)\|")
30
+
31
+
32
+ # ── notation ───────────────────────────────────────────────────────────────
33
+ def chain_notation(foci: List[str], held: Optional[str] = None) -> str:
34
+ s = f" {ARROW} ".join(f"[{f}]" for f in foci)
35
+ if held:
36
+ s += f" {ARROW} |{held}|"
37
+ return s
38
+
39
+
40
+ def parse_chain(text: str) -> Tuple[List[str], Optional[str]]:
41
+ foci = [m.group(1).strip() for m in _FOCUS.finditer(text)]
42
+ held = _HELD.search(text)
43
+ return foci, (held.group(1).strip() if held else None)
44
+
45
+
46
+ # ── the validator: DERIVED FROM THE TEMPLATE (no induction, no DB) ──────────
47
+ def validate_chain(text: str, *, vocab: Optional[List[str]] = None,
48
+ require_held: bool = True, min_foci: int = 1) -> Tuple[bool, List[str]]:
49
+ """The broken-detector. The template's shape (+ optional authored vocabulary) IS the grammar; this
50
+ checks conformance deterministically. Returns (ok, errors)."""
51
+ errors: List[str] = []
52
+ foci, held = parse_chain(text)
53
+ if len(foci) < min_foci:
54
+ errors.append(f"need >= {min_foci} focus block(s) [X]; found {len(foci)}")
55
+ if require_held and not held:
56
+ errors.append("missing terminal |Held| focus")
57
+ if vocab is not None:
58
+ allowed = set(vocab)
59
+ for f in foci:
60
+ if f not in allowed:
61
+ errors.append(f"focus '{f}' not in authored vocabulary {sorted(allowed)}")
62
+ if held and held not in allowed:
63
+ errors.append(f"held '{held}' not in authored vocabulary {sorted(allowed)}")
64
+ expected_arrows = max(0, len(foci) - 1) + (1 if held else 0)
65
+ if (foci or held) and text.count(ARROW) != expected_arrows:
66
+ errors.append(f"arrow count {text.count(ARROW)} != expected {expected_arrows} (malformed chain)")
67
+ return (not errors), errors
68
+
69
+
70
+ # ── builders: AC / CoR / SC as prompt_engine payloads (composed on the primitive) ──────────────────
71
+ def attention_block_payload(foci: List[str], held: Optional[str] = None) -> dict:
72
+ """An attention chain as a block payload (the inner 'how to think' scaffold)."""
73
+ return {
74
+ "values": {"chain": chain_notation(foci, held), "foci_csv": ", ".join(foci), "held": held or ""},
75
+ "methods": [
76
+ {"name": "format_head", "func": "return 'This is an ATTENTION CHAIN — an inner template for how to think (a scaffold for a section or your reasoning). Not necessarily spoken.'", "add_to_sequence": True},
77
+ {"name": "format_chain", "func": "return '## Chain\\n```rune\\n' + self.chain + '\\n```'", "add_to_sequence": True},
78
+ {"name": "format_how", "func": "return 'Attend, in order, to: ' + self.foci_csv + (' — then hold |' + self.held + '|.' if self.held else '.')", "add_to_sequence": True},
79
+ ],
80
+ }
81
+
82
+
83
+ def cor_skeleton(moves: List[str], cues: Optional[dict] = None) -> str:
84
+ """The CORCC fill-in paragraph skeleton: `[move: …cue…] → …` (one clause per move). `cues` maps a
85
+ move name to its cue phrase (defaults to the move name). The SINGLE source of the skeleton format —
86
+ corcc renders through this (§5 convergence)."""
87
+ cue_for = cues or {}
88
+ return " → ".join(f"[{m}: …{cue_for.get(m, m)}…]" for m in moves)
89
+
90
+
91
+ def cor_payload(name: str, foci: List[str], held: str, decision: str,
92
+ cues: Optional[dict] = None) -> dict:
93
+ """A chain-of-reasoning persona. NESTS the attention chain (renders it on the primitive, embeds it)
94
+ = the CORCC-embeds-ACCC composition, done as block-nesting.
95
+
96
+ §5 feature parity (ported from corcc.paragraph): if `cues` is given — a phrase per move, either a
97
+ list aligned to `foci + [held]` or a `{move: cue}` dict — the payload ALSO renders the CORCC fill-in
98
+ SKELETON (`[move: …cue…] → …`) and a must-say directive, so a move only 'counts' when its cue phrase
99
+ surfaces. `cues=None` keeps the original behavior exactly (the skeleton/directive blocks render empty
100
+ and the engine drops them)."""
101
+ inner = render(attention_block_payload(foci, held)) # nest: render the AC, embed as a value
102
+ moves = list(foci) + [held]
103
+ skeleton = directive = ""
104
+ if cues:
105
+ cue_for = cues if isinstance(cues, dict) else dict(zip(moves, cues))
106
+ skeleton = cor_skeleton(moves, cue_for)
107
+ directive = (f"Say ONE paragraph that, in order, works {len(foci)} moves "
108
+ f"({', '.join(foci)}) and converges on {held}; surface each move's cue.")
109
+ return {
110
+ "values": {"name": name, "chain": chain_notation(foci, held), "decision": decision,
111
+ "inner": inner, "skeleton": skeleton, "directive": directive},
112
+ "methods": [
113
+ {"name": "format_head", "func": "return f'# Persona: {self.name}'", "add_to_sequence": True},
114
+ {"name": "format_outer", "func": "return '## Chain of reasoning (SAY this — a paragraph that ends in a decision)\\n```rune\\n' + self.chain + '\\n```\\nWork the moves in order; converge on: ' + self.decision + '.'", "add_to_sequence": True},
115
+ {"name": "format_skeleton", "func": "return ('## Say it like this (fill in each cue)\\n' + self.skeleton) if self.skeleton else ''", "add_to_sequence": True},
116
+ {"name": "format_directive", "func": "return self.directive if self.directive else ''", "add_to_sequence": True},
117
+ {"name": "format_inner", "func": "return '## Inner attention chain (use silently to generate the above)\\n' + self.inner", "add_to_sequence": True},
118
+ ],
119
+ }
120
+
121
+
122
+ def skillchain_payload(steps: List[Tuple[str, str]], goal: str) -> dict:
123
+ """A skill chain: ordered [kind:ref] steps (ac|cor|skill) converging on a goal."""
124
+ steps_md = "\n".join(f"{i}. [{kind}:{ref}]" for i, (kind, ref) in enumerate(steps, 1))
125
+ return {
126
+ "values": {"goal": goal, "steps_md": steps_md},
127
+ "methods": [
128
+ {"name": "format_head", "func": "return 'This is a SKILL CHAIN — resolve each step in order, then converge on the goal.'", "add_to_sequence": True},
129
+ {"name": "format_steps", "func": "return '## Steps\\n' + self.steps_md", "add_to_sequence": True},
130
+ {"name": "format_goal", "func": "return '## Goal\\n|' + self.goal + '|'", "add_to_sequence": True},
131
+ ],
132
+ }
133
+
134
+
135
+ def render_attention_chain(foci, held=None):
136
+ return render(attention_block_payload(foci, held))
137
+
138
+
139
+ def render_cor(name, foci, held, decision, cues=None):
140
+ return render(cor_payload(name, foci, held, decision, cues=cues))
141
+
142
+
143
+ def render_skillchain(steps, goal):
144
+ return render(skillchain_payload(steps, goal))
145
+
146
+
147
+ __all__ = ["chain_notation", "parse_chain", "validate_chain",
148
+ "attention_block_payload", "cor_payload", "skillchain_payload",
149
+ "render_attention_chain", "render_cor", "render_skillchain", "ARROW"]
@@ -0,0 +1,71 @@
1
+ """
2
+ gate.py — the REAL grammar gate, on the `rulecatcher` package (an installed dependency, D3).
3
+
4
+ This is the rule-learner's intent done right: you DON'T hand-write the error rules. You give the template's
5
+ EXEMPLAR chains; rulecatcher LEARNS the grammar (transition rules: next_kind = shape, next_token =
6
+ vocabulary); then `gate()` lints a candidate and returns:
7
+ - violations (found vs expected, per slot)
8
+ - fixes (candidate tokens / suggested action)
9
+ - a verdict ORTHOGONAL (in the language, wrong slot → STEERABLE) vs SYNTAX_BREAK (foreign → FATAL)
10
+
11
+ That verdict is the steerable-vs-fatal gate genus (CSGN's CHECK), which the hand-rolled validate_chain
12
+ can't produce. Rendering never imports this; the gate is an optional layer. Falls back to the shallow
13
+ validate_chain only if `rulecatcher` is somehow unavailable.
14
+ """
15
+
16
+ _RC_OK = True
17
+ try:
18
+ from rulecatcher.db import connect, list_rules
19
+ from rulecatcher.engine import catch_patterns, adopt_rules
20
+ from rulecatcher.models import ArtifactInput
21
+ except Exception: # pragma: no cover
22
+ _RC_OK = False
23
+
24
+ try:
25
+ from .cognition import validate_chain
26
+ except ImportError:
27
+ from cognition import validate_chain
28
+
29
+
30
+ def _learn(conn, exemplars, scope, rule_types):
31
+ content = "\n".join(exemplars) + "\n"
32
+ catch_patterns(conn, [ArtifactInput(label="exemplars", content=content)],
33
+ scope=scope, min_support=1, min_confidence=1.0)
34
+ pending = list_rules(conn, "pending", scope=scope)
35
+ ids = [int(r["id"]) for r in pending if r["rule_type"] in rule_types]
36
+ if ids:
37
+ adopt_rules(conn, ids, actor="prompt-engineering", reason="ratified grammar from exemplars")
38
+ return len(ids)
39
+
40
+
41
+ def gate(text, exemplars, *, scope="chain", rule_types=("next_kind", "next_token"), vocab=None):
42
+ """Learn the grammar from `exemplars`, then lint `text` against it.
43
+
44
+ Returns {ok, engine, verdict, rules, violations:[{found, expected, verdict, candidates, action}]}.
45
+ engine='rulecatcher' (learned grammar + verdict + fixes) | 'fallback' (shallow validate_chain).
46
+ """
47
+ if not _RC_OK:
48
+ ok, errs = validate_chain(text, vocab=vocab)
49
+ return {"ok": ok, "engine": "fallback", "verdict": "clean" if ok else "syntax_break",
50
+ "rules": 0,
51
+ "violations": [{"found": "", "expected": "", "verdict": "syntax_break",
52
+ "candidates": [], "action": e} for e in errs]}
53
+
54
+ from rulecatcher.linting import lint_text
55
+ with connect(":memory:") as conn:
56
+ n_rules = _learn(conn, exemplars, scope, rule_types)
57
+ violations = lint_text(conn, text, scope=scope, record_stats=False)
58
+
59
+ vio = [{"found": v.found_token, "expected": v.expected_token, "verdict": v.verdict,
60
+ "candidates": list(v.candidate_tokens), "action": v.suggested_action} for v in violations]
61
+ if not violations:
62
+ verdict = "clean"
63
+ elif any(v.verdict == "syntax_break" for v in violations):
64
+ verdict = "syntax_break" # foreign token → FATAL
65
+ else:
66
+ verdict = "orthogonal" # in the language, wrong slot → STEERABLE
67
+ return {"ok": not violations, "engine": "rulecatcher", "verdict": verdict,
68
+ "rules": n_rules, "violations": vio}
69
+
70
+
71
+ __all__ = ["gate"]
@@ -0,0 +1,123 @@
1
+ """
2
+ grammar.py — the rulecatcher seam (PERSISTENT, connection-based): learn a chain-DSL's grammar from
3
+ exemplars, gate a candidate against the ratified grammar, render the grammar for a prime block.
4
+
5
+ Moved DOWN from `chaincompiler.bridge` (REBUILD-SPEC.md §4) so accc/corcc/sccc import it from the base
6
+ instead of UP from chaincompiler. The honeyc-wrapping `compile_chain` stays in chaincompiler (§6).
7
+
8
+ This is the PERSISTENT API — you pass a sqlite `Connection` + a `scope`: learn once, gate many, export
9
+ the scope. The base's top-level `gate(text, exemplars)` (gate.py) is the separate EPHEMERAL convenience.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from dataclasses import dataclass
15
+ from sqlite3 import Connection
16
+
17
+ from rulecatcher.db import fetch_artifacts, list_rules
18
+ from rulecatcher.engine import adopt_rules, catch_patterns
19
+ from rulecatcher.linting import build_normalization_suggestions, lint_text
20
+ from rulecatcher.models import ArtifactInput
21
+ from rulecatcher.tokenize import line_token_kinds, line_token_texts, tokenize_text
22
+
23
+ # closed-class kinds: the fixed vocabulary of a chain DSL (delimiters/operators/etc).
24
+ # IDENTIFIER/NUMBER are OPEN class (slot fillers) — always allowed.
25
+ _CLOSED_KINDS = {"SYMBOL", "OPERATOR", "OPEN_DELIM", "CLOSE_DELIM", "SEPARATOR", "KEYWORD"}
26
+
27
+
28
+ @dataclass
29
+ class ForeignToken:
30
+ """A closed-class token foreign to the learned vocabulary (the strict-gate finding)."""
31
+ token: str
32
+ kind: str
33
+ verdict: str = "syntax_break"
34
+
35
+
36
+ def _closed_vocab(connection: Connection, scope: str) -> set[str]:
37
+ """The allowed closed-class token TEXTS, derived from the scope's learned example artifacts."""
38
+ vocab: set[str] = set()
39
+ for art in fetch_artifacts(connection, scope=scope):
40
+ for tl in tokenize_text(art.content):
41
+ for txt, kind in zip(line_token_texts(tl), line_token_kinds(tl, set())):
42
+ if kind in _CLOSED_KINDS:
43
+ vocab.add(txt)
44
+ return vocab
45
+
46
+
47
+ def foreign_tokens(connection: Connection, chain: str, *, scope: str) -> list[ForeignToken]:
48
+ """STRICT vocabulary check (the set-valued gate): any closed-class token whose text is foreign to the
49
+ learned vocabulary is a `syntax_break` — catches branch-point foreign tokens the positional rules miss.
50
+ Open-class tokens are always allowed."""
51
+ vocab = _closed_vocab(connection, scope)
52
+ if not vocab: # nothing learned → nothing to whitelist against
53
+ return []
54
+ out: list[ForeignToken] = []
55
+ for tl in tokenize_text(chain):
56
+ for txt, kind in zip(line_token_texts(tl), line_token_kinds(tl, set())):
57
+ if kind in _CLOSED_KINDS and txt not in vocab:
58
+ out.append(ForeignToken(token=txt, kind=kind))
59
+ return out
60
+
61
+
62
+ def learn(
63
+ connection: Connection,
64
+ chains: list[str],
65
+ *,
66
+ scope: str,
67
+ keywords: tuple[str, ...] = (),
68
+ min_confidence: float = 1.0,
69
+ rule_types: tuple[str, ...] = ("next_kind",),
70
+ label: str = "seed",
71
+ ) -> list:
72
+ """Catch the grammar of `chains` and ratify (adopt) the rigid rules.
73
+
74
+ Defaults to `next_kind` only: the SHAPE of the notation, not its vocabulary. A cognition-chain
75
+ notation's grammar is "an [Identifier] then ⇒ then ..." — not the specific step names. Adopting
76
+ `next_token` too would pin the corpus vocabulary and grow the grammar every time a new step name
77
+ appears. Pass rule_types=("next_kind","next_token") to also fix exact tokens.
78
+
79
+ Returns the adopted rule rows = the ratified grammar of the notation.
80
+ """
81
+ content = "\n".join(chains) + "\n"
82
+ catch_patterns(
83
+ connection,
84
+ [ArtifactInput(label=label, content=content)],
85
+ scope=scope,
86
+ keywords=list(keywords) or None,
87
+ )
88
+ pending = list_rules(connection, "pending", scope=scope)
89
+ ids = [
90
+ int(r["id"])
91
+ for r in pending
92
+ if float(r["confidence"]) >= min_confidence and r["rule_type"] in rule_types
93
+ ]
94
+ if ids:
95
+ adopt_rules(connection, ids, actor="prompt-engineering",
96
+ reason=f"ratified {'/'.join(rule_types)} grammar (confidence >= {min_confidence:.2f})")
97
+ return list_rules(connection, "adopted", scope=scope)
98
+
99
+
100
+ def gate(connection: Connection, chain: str, *, scope: str, strict: bool = False) -> tuple[list, list]:
101
+ """Lint a candidate chain against the ratified grammar. Returns (violations, fixes).
102
+ `strict=True` ALSO runs the closed-class vocabulary check (`foreign_tokens`), so foreign tokens at
103
+ branch points — which the positional rules can't govern — are caught as `syntax_break`. Opt-in, so
104
+ default behavior (and the rulecatcher tests) are unchanged."""
105
+ violations = lint_text(connection, chain, scope=scope, record_stats=False)
106
+ suggestions = build_normalization_suggestions(violations)
107
+ if strict:
108
+ violations = list(violations) + foreign_tokens(connection, chain, scope=scope)
109
+ return violations, suggestions
110
+
111
+
112
+ def grammar_lines(adopted_rows: list) -> list[str]:
113
+ """Human-readable rendering of the ratified grammar (for the prime block)."""
114
+ lines: list[str] = []
115
+ for r in sorted(adopted_rows, key=lambda x: (-len(json.loads(x["prefix_json"])), -float(x["confidence"]))):
116
+ prefix = json.loads(r["prefix_json"])
117
+ kind = "tok" if r["rule_type"] == "next_token" else "kind"
118
+ lines.append(f"- [{kind}] after {prefix} → {r['expected_token']} "
119
+ f"({r['support']}/{r['total']}, conf {float(r['confidence']):.2f})")
120
+ return lines
121
+
122
+
123
+ __all__ = ["learn", "gate", "grammar_lines", "foreign_tokens", "ForeignToken"]
@@ -0,0 +1,61 @@
1
+ """
2
+ persona.py — example persona prompt-engineering systems.
3
+
4
+ Generate a full persona prompt from a small spec, composing block types (system, persona, rules, output)
5
+ PLUS a cognition-chain DSL block (a chain-of-reasoning, which itself nests an attention chain). So you can
6
+ spin up personas — even ones with complex reasoning DSLs — in ONE call, deterministically.
7
+
8
+ make_persona(spec) -> prompt # spec = {name, role, voice?, reasoning?, rules?, output?}
9
+ make_persona_file(path) -> prompt # spec from JSON
10
+
11
+ `reasoning` = {foci: [...], held: "...", decision: "..."} → a CoR DSL block (the complex part).
12
+ Same spec → same persona prompt, every time.
13
+ """
14
+
15
+ import json
16
+ from pathlib import Path
17
+ from typing import Any, Dict, Union
18
+
19
+ try:
20
+ from .prompt_engine import render
21
+ from .cognition import render_cor
22
+ except ImportError:
23
+ from prompt_engine import render
24
+ from cognition import render_cor
25
+
26
+
27
+ def _block(values: Dict[str, Any], name: str, func: str) -> str:
28
+ return render({"values": values, "methods": [{"name": name, "func": func, "add_to_sequence": True}]})
29
+
30
+
31
+ def make_persona(spec: Dict[str, Any]) -> str:
32
+ """Compose a persona prompt from a small spec — block types + a cognition DSL block."""
33
+ blocks = []
34
+ # system block — the role
35
+ blocks.append(_block({"role": spec["role"]}, "format_system", "return f'You are {self.role}.'"))
36
+ # persona block — name + voice
37
+ blocks.append(_block(
38
+ {"name": spec["name"], "voice": spec.get("voice", "")},
39
+ "format_persona",
40
+ "return f'## Persona\\nYou are {self.name}.' + (f' Voice: {self.voice}.' if self.voice else '')",
41
+ ))
42
+ # reasoning DSL block — a chain-of-reasoning (nests an attention chain): the COMPLEX block
43
+ r = spec.get("reasoning")
44
+ if r:
45
+ blocks.append(render_cor(spec["name"], r["foci"], r["held"], r["decision"]))
46
+ # rules block
47
+ if spec.get("rules"):
48
+ blocks.append(_block({"rules": spec["rules"]}, "format_rules",
49
+ "return '## Rules\\n' + '\\n'.join(f'- {r}' for r in self.rules)"))
50
+ # output-format block
51
+ if spec.get("output"):
52
+ blocks.append(_block({"fmt": spec["output"]}, "format_output",
53
+ "return '## Output format\\n' + self.fmt"))
54
+ return "\n\n".join(blocks)
55
+
56
+
57
+ def make_persona_file(path: Union[str, Path]) -> str:
58
+ return make_persona(json.loads(Path(path).read_text()))
59
+
60
+
61
+ __all__ = ["make_persona", "make_persona_file"]
@@ -0,0 +1,110 @@
1
+ """
2
+ prompt_engine.py — the Prompt Engineering System (a deterministic prompt builder).
3
+
4
+ A payload (data) → a prompt. The SAME inputs give the SAME output every time — no model call, no
5
+ randomness, pure composition. That determinism is the point: an agent reads this and makes prompts
6
+ consistently.
7
+
8
+ Vocabulary
9
+ block — one payload (values + methods-as-code-strings + a template_sequence) → a prompt chunk
10
+ prompt template — a stored, ordered set of blocks (a folder under templates/) → one full prompt
11
+ (There is NO baked-in structure or "levels"; bring your own via blocks/templates.)
12
+
13
+ Top-level API
14
+ render(payload) → prompt chunk for one block
15
+ render_file(path) → render a block payload from a JSON file
16
+ list_templates() → names of stored prompt templates
17
+ load_template(name) → {name, description, blocks:[payload...], block_files:[...]}
18
+ render_template(name) → ONE prompt (the template's blocks, joined in order)
19
+ render_template_blocks(name) → {block_name: prompt} (each block separately)
20
+ """
21
+
22
+ import json
23
+ from pathlib import Path
24
+ from typing import Any, Dict, List, Optional, Union
25
+
26
+ try:
27
+ from .template_mixins import TemplateAttributeMixin, TemplateMethodMixin
28
+ except ImportError: # loaded standalone (lib/ on sys.path)
29
+ from template_mixins import TemplateAttributeMixin, TemplateMethodMixin
30
+
31
+
32
+ class Template(TemplateAttributeMixin, TemplateMethodMixin):
33
+ """A blank templated object — fresh per instance (no shared mutable state)."""
34
+
35
+ def __init__(self):
36
+ self._attributes: Dict[str, Any] = {}
37
+ self._attribute_dependencies: Dict[str, list] = {}
38
+ self._methods: Dict[str, Any] = {}
39
+ self._template_sequence: list = []
40
+
41
+
42
+ def build_template(payload: Dict[str, Any]) -> Template:
43
+ """payload keys: values {name: value}, attributes [{name,value,...}], methods [{name,func,add_to_sequence}],
44
+ template_sequence [name,...]. Returns a ready-to-render Template."""
45
+ t = Template()
46
+ for name, value in (payload.get("values") or {}).items():
47
+ t.add_attribute(name, value)
48
+ for attr in payload.get("attributes", []):
49
+ t.add_attribute_from_dict(attr)
50
+ for method in payload.get("methods", []):
51
+ t.add_method_from_dict(method)
52
+ if payload.get("template_sequence"):
53
+ t.set_template_sequence(payload["template_sequence"])
54
+ return t
55
+
56
+
57
+ def render(payload: Dict[str, Any]) -> str:
58
+ """One block payload → its prompt chunk (deterministic)."""
59
+ return build_template(payload).execute_template_sequence()
60
+
61
+
62
+ def render_file(path: Union[str, Path]) -> str:
63
+ """Render a block payload from a JSON file."""
64
+ return render(json.loads(Path(path).read_text()))
65
+
66
+
67
+ # ── prompt templates: a stored, ordered set of BLOCKS (add one by DROPPING A FOLDER) ───────────────
68
+ # templates/
69
+ # {template_name}/
70
+ # template.json — manifest: {name, description, blocks: ["block1.json", "block2.json", ...]}
71
+ # {block}.json — the block payloads (any structure — no levels required)
72
+ # To add a prompt template: create the folder + template.json + block payloads. Nothing else changes.
73
+
74
+ def templates_root(base: Optional[Union[str, Path]] = None) -> Path:
75
+ return Path(base) if base else (Path(__file__).resolve().parent / "templates")
76
+
77
+
78
+ def list_templates(base: Optional[Union[str, Path]] = None) -> List[str]:
79
+ """Discover prompt templates by the folder convention (any dir with a template.json)."""
80
+ root = templates_root(base)
81
+ if not root.exists():
82
+ return []
83
+ return sorted(p.name for p in root.iterdir() if (p / "template.json").exists())
84
+
85
+
86
+ def load_template(name: str, base: Optional[Union[str, Path]] = None) -> Dict[str, Any]:
87
+ """Load a prompt template: manifest + each ordered block payload."""
88
+ root = templates_root(base)
89
+ manifest = json.loads((root / name / "template.json").read_text())
90
+ block_files = manifest.get("blocks", [])
91
+ blocks = [json.loads((root / name / f).read_text()) for f in block_files]
92
+ return {"name": manifest.get("name", name), "description": manifest.get("description", ""),
93
+ "blocks": blocks, "block_files": block_files}
94
+
95
+
96
+ def render_template(name: str, base: Optional[Union[str, Path]] = None) -> str:
97
+ """Render a stored prompt template → ONE prompt (its blocks, joined in order). Deterministic."""
98
+ t = load_template(name, base)
99
+ return "\n\n".join(render(b) for b in t["blocks"])
100
+
101
+
102
+ def render_template_blocks(name: str, base: Optional[Union[str, Path]] = None) -> Dict[str, str]:
103
+ """Render each block of a prompt template separately → {block_name: prompt}."""
104
+ t = load_template(name, base)
105
+ return {Path(f).stem: render(b) for f, b in zip(t["block_files"], t["blocks"])}
106
+
107
+
108
+ __all__ = ["Template", "build_template", "render", "render_file",
109
+ "list_templates", "load_template", "render_template", "render_template_blocks",
110
+ "templates_root"]
@@ -0,0 +1,75 @@
1
+ """skillpack.py — a markdown body → a publishable `<name>/SKILL.md` dir.
2
+
3
+ The canonical output of every *CC is a MARKDOWN FILE carrying the chain / instructions in its custom
4
+ syntax; wrapping it as `<name>/SKILL.md` is the easiest way to publish it so any agent auto-loads it.
5
+ This is the one place that wrapper is written, shared by ACCC / CORCC / SCCC.
6
+
7
+ Moved DOWN from `chaincompiler.skillpack` (REBUILD-SPEC.md §7) so the *CC import it from the base.
8
+
9
+ D4: `write_skill(..., coordinate=True)` and `cohere_skills(root)` place skills as COORDINATE-ADDRESSED
10
+ nodes via `skilltree` (rule 25) — ALL skill stuff is built on skilltree. The default (`coordinate=False`)
11
+ preserves the exact original behavior, so the *CC and their tests keep working unchanged.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ from pathlib import Path
16
+ import re
17
+
18
+
19
+ def slugify(name: str) -> str:
20
+ slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
21
+ return slug or "skill"
22
+
23
+
24
+ def skill_markdown(name: str, description: str, body: str, *, extra: dict[str, str] | None = None) -> str:
25
+ """Render the SKILL.md text (frontmatter + body). This IS the artifact."""
26
+ fm = [f"name: {slugify(name)}", f"description: {description}"]
27
+ for k, v in (extra or {}).items():
28
+ fm.append(f"{k}: {v}")
29
+ front = "\n".join(fm)
30
+ return f"---\n{front}\n---\n\n{body.rstrip()}\n"
31
+
32
+
33
+ def write_skill(
34
+ name: str,
35
+ description: str,
36
+ body: str,
37
+ *,
38
+ out_dir: str | Path,
39
+ extra: dict[str, str] | None = None,
40
+ coordinate: bool = False,
41
+ ) -> Path:
42
+ """Write `<out_dir>/<slug>/SKILL.md` and return its path.
43
+
44
+ D4 — if `coordinate=True`, the skill is written into skilltree's recursive `.claude/skills/` layout
45
+ (`<out_dir>/.claude/skills/<slug>/SKILL.md`), ready to be COORDINATE-ADDRESSED (rule 25). Write all
46
+ your skills with `coordinate=True`, then call `cohere_skills(out_dir)` ONCE: skilltree assigns each a
47
+ hierarchical coordinate (e.g. `0.1`, `0.2`), rewrites breadcrumbs, and writes `skilltree.json`.
48
+ (Cohering once over the finished forest is skilltree's idiom — emitting after every write would keep
49
+ re-rooting the tree.) Default `False` keeps the plain loose-dir behavior.
50
+ """
51
+ slug = slugify(name)
52
+ base = Path(out_dir)
53
+ # coordinate mode → skilltree's `.claude/skills/` root; else the plain `<out_dir>/<slug>/` loose dir.
54
+ parent = base / ".claude" / "skills" if coordinate else base
55
+ pkg = parent / slug
56
+ pkg.mkdir(parents=True, exist_ok=True)
57
+ md = skill_markdown(name, description, body, extra=extra)
58
+ skill_path = pkg / "SKILL.md"
59
+ skill_path.write_text(md, encoding="utf-8")
60
+ return skill_path
61
+
62
+
63
+ def cohere_skills(root: str | Path, *, forest_name: str | None = None) -> dict:
64
+ """Place every skill under `root` as a COORDINATE-ADDRESSED node (D4, rule 25).
65
+
66
+ Thin wrapper over `skilltree.emit(root, root_forest=True)`: assigns hierarchical coordinates,
67
+ rewrites breadcrumbs, synthesizes a forest root, and writes `skilltree.json`. `skilltree` is imported
68
+ lazily so the pure deterministic prompt engine carries no hard skilltree requirement. Returns
69
+ skilltree's emit report: `{ok, nodes, synthesized_root, root, moves, journal}`.
70
+ """
71
+ from skilltree import emit
72
+ return emit(str(root), root_forest=True, forest_name=forest_name)
73
+
74
+
75
+ __all__ = ["slugify", "skill_markdown", "write_skill", "cohere_skills"]
@@ -0,0 +1,137 @@
1
+ """
2
+ template_mixins.py — the class-level metaprogramming engine (native, stdlib-only).
3
+
4
+ Two mixins. A class that inherits both can grow its own ATTRIBUTES and METHODS at runtime FROM DATA
5
+ (dict/JSON specs), then render deterministically by running a fixed method sequence. There is NO notion of
6
+ "levels" (world/deity/agent…) in here — structure comes entirely from the payload you supply. Faithful
7
+ port of the legacy progenitor mixins, with pydantic dropped and per-instance state (no shared mutables).
8
+ """
9
+
10
+ from typing import Any, Callable, Dict, List, Optional, Type
11
+
12
+
13
+ class TemplateAttributeMixin:
14
+ """Manage template attributes: add values (or computed callables with a dependency graph) from data."""
15
+
16
+ def add_attribute(self, name: str, value: Any, type_annotation: Optional[Type] = None,
17
+ description: Optional[str] = None, computed: bool = False,
18
+ dependencies: Optional[List[str]] = None):
19
+ if not hasattr(self, "_attributes"):
20
+ self._attributes = {}
21
+ if not hasattr(self, "_attribute_dependencies"):
22
+ self._attribute_dependencies = {}
23
+
24
+ if type_annotation is None:
25
+ type_annotation = Any if (callable(value) and not isinstance(value, type)) else type(value)
26
+
27
+ self._attributes[name] = {"value": value, "type": type_annotation,
28
+ "description": description or f"Attribute {name}", "computed": computed}
29
+ if computed and dependencies:
30
+ self._attribute_dependencies[name] = dependencies
31
+
32
+ if computed and callable(value):
33
+ if not hasattr(self.__class__, name):
34
+ setattr(self.__class__, name, property(lambda self, v=value: v(self)))
35
+ else:
36
+ self.__dict__[name] = value
37
+
38
+ def get_attribute(self, name: str) -> Any:
39
+ if name in self.__dict__:
40
+ return self.__dict__[name]
41
+ if hasattr(self.__class__, name) and isinstance(getattr(self.__class__, name), property):
42
+ return getattr(self, name)
43
+ if name in self._attributes:
44
+ info = self._attributes[name]
45
+ return info["value"](self) if (info["computed"] and callable(info["value"])) else info["value"]
46
+ raise AttributeError(f"Attribute {name} not found")
47
+
48
+ def update_attribute(self, name: str, value: Any):
49
+ if name not in self._attributes:
50
+ raise AttributeError(f"Cannot update non-existent attribute {name}")
51
+ self._attributes[name]["value"] = value
52
+ if not self._attributes[name]["computed"]:
53
+ self.__dict__[name] = value
54
+
55
+ def get_all_attributes(self) -> Dict[str, Dict[str, Any]]:
56
+ return self._attributes
57
+
58
+ def get_dependencies(self, name: str) -> List[str]:
59
+ return self._attribute_dependencies.get(name, [])
60
+
61
+ def add_attribute_from_dict(self, attr: Dict[str, Any]):
62
+ name = attr.get("name")
63
+ if not name:
64
+ raise ValueError("Attribute dict must contain 'name'")
65
+ self.add_attribute(name, attr.get("value"), attr.get("type"), attr.get("description"),
66
+ attr.get("computed", False), attr.get("dependencies", []))
67
+
68
+
69
+ class TemplateMethodMixin:
70
+ """Manage template methods: add methods (from a callable OR a code string), sequence them, and render
71
+ by executing the sequence in order — the deterministic part."""
72
+
73
+ def add_method(self, name: str, func: Callable, description: Optional[str] = None,
74
+ parameters: Optional[List[str]] = None, return_type: Optional[Type] = None,
75
+ add_to_sequence: bool = False):
76
+ if not hasattr(self, "_methods"):
77
+ self._methods = {}
78
+ if not hasattr(self, "_template_sequence"):
79
+ self._template_sequence = []
80
+ self._methods[name] = {"func": func, "description": description or f"Method {name}",
81
+ "parameters": parameters or [], "return_type": return_type}
82
+ self.__dict__[name] = func.__get__(self, self.__class__)
83
+ if add_to_sequence:
84
+ self._template_sequence.append(name)
85
+
86
+ def get_method(self, name: str) -> Callable:
87
+ if name in self.__dict__ and callable(self.__dict__[name]):
88
+ return self.__dict__[name]
89
+ if name in self._methods:
90
+ return self._methods[name]["func"].__get__(self, self.__class__)
91
+ if hasattr(self.__class__, name) and callable(getattr(self.__class__, name)):
92
+ return getattr(self, name)
93
+ raise AttributeError(f"Method {name} not found")
94
+
95
+ def get_all_methods(self) -> Dict[str, Dict[str, Any]]:
96
+ return self._methods
97
+
98
+ def get_template_sequence(self) -> List[str]:
99
+ return self._template_sequence
100
+
101
+ def set_template_sequence(self, sequence: List[str]):
102
+ for name in sequence:
103
+ if name not in self._methods and name not in self.__dict__ and not hasattr(self.__class__, name):
104
+ raise ValueError(f"Method {name} in template sequence does not exist")
105
+ self._template_sequence = sequence
106
+
107
+ def add_method_from_dict(self, method: Dict[str, Any]):
108
+ name = method.get("name")
109
+ if not name:
110
+ raise ValueError("Method dict must contain 'name'")
111
+ func = method.get("func")
112
+ if isinstance(func, str): # func as a code STRING → a real method (data → behavior)
113
+ import textwrap
114
+ ns: Dict[str, Any] = {}
115
+ exec(f"def {name}(self, *args, **kwargs):\n{textwrap.indent(func, ' ')}", globals(), ns)
116
+ func = ns[name]
117
+ elif not callable(func):
118
+ raise ValueError(f"Function for method {name} must be callable or code string")
119
+ self.add_method(name, func, method.get("description"), method.get("parameters", []),
120
+ method.get("return_type"), method.get("add_to_sequence", False))
121
+
122
+ def execute_template_sequence(self) -> str:
123
+ """Run the sequence in order, join non-empty results. SAME inputs → SAME prompt (the guarantee)."""
124
+ results = []
125
+ for method_name in self._template_sequence:
126
+ if method_name in self.__dict__ and callable(self.__dict__[method_name]):
127
+ method = self.__dict__[method_name]
128
+ elif method_name in self._methods:
129
+ method = self._methods[method_name]["func"].__get__(self, self.__class__)
130
+ elif hasattr(self, method_name):
131
+ method = getattr(self, method_name)
132
+ else:
133
+ raise AttributeError(f"Method {method_name} not found")
134
+ result = method()
135
+ if result:
136
+ results.append(result)
137
+ return "\n\n".join(results)
@@ -0,0 +1,4 @@
1
+ {
2
+ "values": {"agent": "a Crafter — crafts within the rules of the world"},
3
+ "methods": [{"name": "format_agent", "func": "return f'## AGENT\\n{self.agent}'", "add_to_sequence": true}]
4
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "values": {"deity": "the Worldsmith — runs the world and makes the makers"},
3
+ "methods": [{"name": "format_deity", "func": "return f'## DEITY\\n{self.deity}'", "add_to_sequence": true}]
4
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "values": {"egregore": "the Crafters' Guild — the collective the agents belong to"},
3
+ "methods": [{"name": "format_egregore", "func": "return f'## EGREGORE\\n{self.egregore}'", "add_to_sequence": true}]
4
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "values": {"progenitor": "a Skill-Maker — makes the player skills"},
3
+ "methods": [{"name": "format_progenitor", "func": "return f'## PROGENITOR\\n{self.progenitor}'", "add_to_sequence": true}]
4
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "five_level",
3
+ "description": "The legacy World -> Egregore -> Deity -> Progenitor -> Agent model, as a PROMPT TEMPLATE. An example structure, not a default — each level is just a block payload in this folder.",
4
+ "blocks": ["world.json", "egregore.json", "deity.json", "progenitor.json", "agent.json"]
5
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "values": {"world": "Skillcraft — a world where agents craft skills and trade them"},
3
+ "methods": [{"name": "format_world", "func": "return f'## WORLD\\n{self.world}'", "add_to_sequence": true}]
4
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "values": {"format": "a markdown table with columns: file, line, issue, fix"},
3
+ "methods": [
4
+ {"name": "format_output", "func": "return f'## Output format\\nReturn {self.format}.'", "add_to_sequence": true}
5
+ ]
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "values": {"name": "Ada", "traits": "precise, terse, kind", "voice": "plain English with no hedging"},
3
+ "methods": [
4
+ {"name": "format_persona", "func": "return f'## Persona\\nYou are {self.name}. You are {self.traits}. You speak in {self.voice}.'", "add_to_sequence": true}
5
+ ]
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "values": {"rules": ["Cite file:line for every claim.", "Never invent an API.", "If unsure, say so plainly."]},
3
+ "methods": [
4
+ {"name": "format_rules", "func": "return '## Rules\\n' + '\\n'.join(f'- {r}' for r in self.rules)", "add_to_sequence": true}
5
+ ]
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "values": {"role": "a senior Python code reviewer", "mission": "find correctness bugs and suggest the minimal fix"},
3
+ "methods": [
4
+ {"name": "format_system", "func": "return f'You are {self.role}. Your mission is to {self.mission}.'", "add_to_sequence": true}
5
+ ]
6
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "persona",
3
+ "description": "A worked PERSONA — the code-reviewer 'Ada' — composed from a system block + persona block + rules block + output-format block. Shows how block types stack into one full persona prompt.",
4
+ "blocks": ["system.json", "persona.json", "rules.json", "output_format.json"]
5
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "values": {"role": "Helper", "task": "answer questions clearly"},
3
+ "methods": [{"name": "format_role", "func": "return f'You are a {self.role} whose task is to {self.task}.'", "add_to_sequence": true}]
4
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "simple_agent",
3
+ "description": "A one-block prompt template — proof that you add a template by DROPPING A FOLDER (no levels, no engine change).",
4
+ "blocks": ["agent.json"]
5
+ }