deepclause-pi 0.1.4 → 0.2.0

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,265 @@
1
+ ---
2
+ name: handbook-dml
3
+ description: Convert a long handbook/SOP into one DeepClause DML skill per workflow — an LLM-first subagent (agentic task/N leaves, narrow tool/2 capabilities) that takes a generic natural-language request as input and uses deterministic Prolog only for mechanical checks, with LLM fallback. Also teaches a tool audit, user confirmation, and how to write the repo-root AGENTS.md policy-routing table so pi calls the skills automatically via dc_run. Use when asked to turn a handbook or procedures manual into executable DML, update a handbook-derived skill, or wire the policy router.
4
+ ---
5
+
6
+ # Handbook → DML (procedures)
7
+
8
+ Turn a long handbook into **one DML skill per workflow/procedure**. Each skill is
9
+ an **LLM-first subagent**: agentic `task/N` leaves do the reading, reasoning,
10
+ and acting, while Prolog handles only what is genuinely mechanical (arithmetic,
11
+ counting, exact equality) or a hard safety invariant.
12
+
13
+ Before writing DML, read `.pi/deepclause/AGENTS.md` and
14
+ `.pi/deepclause/DML_REFERENCE.md`. They are authoritative for syntax.
15
+
16
+ ## Mental model
17
+
18
+ - **Pi authors; DML is the runtime artifact.** Decomposition and authoring happen
19
+ in a normal pi turn. There is no Markdown→DML compiler.
20
+ - **LLM-first.** Rules and flow are `task/N` / `prompt/N` by default. Use Prolog
21
+ only where a rule is mechanical or must never be wrong.
22
+ - **Input is a generic request.** `agent_main(Request)` takes free text; the
23
+ first step is an LLM `task/N` that parses it into a typed `object/1` case (or
24
+ the request is used directly for simple skills).
25
+ - **Forbidden actions become tool scoping.** "Never send" means *no send tool*.
26
+ "Read-only inspection" means the inspect phase gets read tools only.
27
+ - **Every deterministic rule gets an LLM fallback.** If a deterministic check
28
+ fails, branch to a `prompt/N`/`task/N` that reviews, repairs, or asks the user
29
+ — do not hard-fail.
30
+ - **Ask, don't assume.** Confirm scope, the decomposition, and tool choices with
31
+ the user before authoring.
32
+
33
+ ## Workflow
34
+
35
+ 1. **Ingest** the handbook to Markdown (PDF→`pdftotext`, DOCX/HTML→`pandoc`).
36
+ Keep the source under `examples/handbook-md/<handbook_slug>/`.
37
+ 2. **Clarify** with the user: which workflows to convert, what the input looks
38
+ like (a request? a file? a case id?), and what the skill may change.
39
+ 3. **Decompose** by the document's own workflows and **propose the
40
+ section → skill map; get approval** before writing files.
41
+ 4. **Tool audit** (below): list each procedure's required capabilities, check
42
+ what is available, flag gaps, and ask whether dummy tools are acceptable.
43
+ 5. **Author** one DML per workflow from the template below.
44
+ 6. **Run and iterate** with the user's real input:
45
+ `/dc-run skills/<handbook_slug>/<slug>.dml "<request>" --debug`.
46
+ 7. **Write `INDEX.md`** and **add a row to the repo-root `AGENTS.md`** routing
47
+ table.
48
+
49
+ ## Input convention
50
+
51
+ The skill takes a **generic natural-language request**, not positional args and
52
+ not hardcoded case facts.
53
+
54
+ - Default: parse the request with an LLM `task/N` into a typed `object/1` case.
55
+ - Simpler skills: pass the request text directly into the first `task/N` and
56
+ skip the extraction step.
57
+
58
+ ```prolog
59
+ extract_case(Request, Case) :-
60
+ format(string(Desc),
61
+ "Extract a structured case from this request: ~w. Store an object with keys <fields>. Use null for unknown fields.",
62
+ [Request]),
63
+ task(Desc, object(Case)).
64
+ ```
65
+
66
+ `object(Var)` is a supported typed output; read it with `get_dict/3`. Then
67
+ confirm with the user before acting. User interaction loops belong **inside a
68
+ `task/N`**, with `ask_user` exposed as a tool:
69
+
70
+ ```prolog
71
+ tool(user_feedback(Prompt, Response), "Ask the user one focused question and return their response") :-
72
+ exec(ask_user(prompt: Prompt), Result),
73
+ get_dict(user_response, Result, Response).
74
+
75
+ confirm_case(Case, ConfirmedCase) :-
76
+ format(string(Instruction),
77
+ "Present this extracted case to the user with the user_feedback tool: ~w. Ask them to type 'ok' or describe corrections. If 'ok', return the case unchanged. Otherwise apply corrections and ask again, up to 3 rounds. Store the final case in ConfirmedCase.",
78
+ [Case]),
79
+ with_tools([user_feedback], (
80
+ task(Instruction, object(ConfirmedCase))
81
+ )).
82
+ ```
83
+
84
+ ## Tool audit
85
+
86
+ Before authoring, list what the procedure needs and check what actually exists.
87
+
88
+ | Procedure need | Real option | Dummy fallback |
89
+ | --- | --- | --- |
90
+ | email / Slack / calendar / Jira / Shopify | pi tools (if installed & active) or MCP | `tool/2` over `pi_bash` (files) or over facts |
91
+ | read spreadsheets / PDFs / CSVs | pi tools or `pi_bash` | `tool/2` reading fixture files |
92
+ | ask the user | `ask_user` (always available in DML) | — |
93
+ | arbitrary shell | `pi_bash` (approval-gated) | — |
94
+
95
+ The DML runtime itself exposes only `pi_workspace_list`, `pi_bash`, and
96
+ `ask_user`. Everything else (email, Slack, calendar, structured file readers) is
97
+ missing unless you add it as a DML `tool/2`. So:
98
+
99
+ 1. For each required capability, note whether a real tool exists.
100
+ 2. If it is missing, **tell the user and ask: "use a dummy tool for X?"** before
101
+ authoring. Do not silently build a dummy.
102
+ 3. Record the chosen substitution in the skill header and in `INDEX.md`.
103
+
104
+ ## Light template
105
+
106
+ ```prolog
107
+ % POLICY: <slug>
108
+ % Handbook : <handbook_slug> (<title>)
109
+ % Trigger : <when to run>
110
+ % Input : a natural-language request (parsed by the first task)
111
+ % Effects : <what state this changes, if any>
112
+ % Tools : <real or dummy, per the tool audit>
113
+ %
114
+ % Run: /dc-run skills/<handbook_slug>/<slug>.dml "<request>"
115
+
116
+ % --- tools ----------------------------------------------------------------
117
+ % Read tools for inspection; write tools for action; omit forbidden actions.
118
+ tool(<read_...>(Args, Out), "Description") :- ... .
119
+ tool(<write_...>(Args, Result), "Description") :- ... .
120
+ tool(user_feedback(Prompt, Response), "Ask the user one focused question and return their response") :-
121
+ exec(ask_user(prompt: Prompt), Result),
122
+ get_dict(user_response, Result, Response).
123
+
124
+ % --- deterministic helpers (mechanical only) -------------------------------
125
+ <compute_or_check>(...). % arithmetic/counts; keep small
126
+
127
+ % --- entry point ------------------------------------------------------------
128
+ agent_main(Request) :-
129
+ Request \= "",
130
+ system("Role and hard rules. Treat supplied policy text as governing."),
131
+ output("Parsing the request..."),
132
+ extract_case(Request, Case), % task/N -> object/1
133
+ output("Confirming..."),
134
+ confirm_case(Case, ConfirmedCase), % user_feedback loop
135
+ output("Acting..."),
136
+ with_tools([<write tools>], (
137
+ task("Produce the required effects for this case: {ConfirmedCase}.", string(Summary))
138
+ )),
139
+ <optional verification with LLM fallback>,
140
+ answer(Final).
141
+
142
+ agent_main(_) :-
143
+ answer("Supply a request describing the case.").
144
+ ```
145
+
146
+ Notes:
147
+
148
+ - `task/N` = agentic leaf (memory + DML tools). `prompt/N` = fresh-context
149
+ review. `with_tools/2` scopes capability per phase.
150
+ - Build `task/N` descriptions with `format/3` (not `{Var}` interpolation) when
151
+ you embed dynamic values — avoids singleton-variable noise.
152
+ - Mutable facts must be declared `:- dynamic` before `assertz`/`retract`.
153
+
154
+ ## Verification (optional, LLM-first)
155
+
156
+ Only add checks when the procedure has observable post-conditions. Prefer model
157
+ review; use deterministic checks only for mechanical facts, and always give a
158
+ deterministic check an LLM fallback.
159
+
160
+ ```prolog
161
+ % deterministic gate (mechanical only)
162
+ holds(drafts_count) :- findall(_, draft(_,_,_,_), Ds), length(Ds, 2).
163
+
164
+ verify_state(Failed, Report) :-
165
+ findall(Name, (postcondition(Name), \+ holds(Name)), Failed),
166
+ ( Failed = [] -> Report = "PASS" ; format(string(Report), "FAIL: ~w", [Failed]) ).
167
+
168
+ % LLM fallback: never hard-fail on a deterministic check
169
+ fallback_review(Failed, Verdict, Reason) :-
170
+ format(string(Prompt),
171
+ "These structural checks failed: ~w. Review the outcome and the requirement. Store 'acceptable' or 'needs-attention' in Verdict and a one-line reason in Reason.",
172
+ [Failed]),
173
+ prompt(Prompt, string(Verdict), string(Reason)).
174
+ ```
175
+
176
+ In `agent_main`:
177
+
178
+ ```prolog
179
+ verify_state(Failed, Report),
180
+ ( Failed = [] -> V = "n/a", R = "deterministic checks passed"
181
+ ; fallback_review(Failed, V, R)
182
+ ),
183
+ answer(... report Report + V/R ...).
184
+ ```
185
+
186
+ Choosing:
187
+
188
+ - **Model review** (default): tone, completeness, correctness of free text,
189
+ "does this read right", and anything the rubric phrases as a judgment.
190
+ - **Deterministic** (only when mechanical): counts, exact IDs, arithmetic. Keep
191
+ it tiny, and route failures to the model or the user instead of failing.
192
+
193
+ ## Dummy tools
194
+
195
+ Only after the user approves. Prefer **file-backed** dummy tools (read/write
196
+ fixture files through `pi_bash`) because they mirror real services and make the
197
+ skill runnable against real data. Use **fact-backed** state only for pure
198
+ in-memory cases. Keep the tool name/contract stable so a real `exec/2`/MCP
199
+ implementation can replace the dummy body later.
200
+
201
+ ## The AGENTS.md policy router
202
+
203
+ After the skills are written and tested, wire them into the repo-root
204
+ `AGENTS.md` so pi calls them automatically. `AGENTS.md` is always in pi's
205
+ context; `dc_run` (enabled once with `/dc-tool enable`) executes a named skill.
206
+
207
+ ```markdown
208
+ ## DeepClause policy routing
209
+
210
+ When a request matches a procedure below, do **not** answer from memory or from
211
+ the source handbook text. Call the `dc_run` tool with the mapped skill, then
212
+ report its answer (including its verification result, if any).
213
+
214
+ If `dc_run` is unavailable, tell the user to run `/dc-tool enable` (persists for
215
+ the workspace) or to run the equivalent `/dc-run` command themselves.
216
+
217
+ | Handbook | Procedure / trigger | Skill (`dc_run.skill`) | Args (`dc_run.args`) |
218
+ | --- | --- | --- | --- |
219
+ | <handbook_slug> | <short trigger phrase a request would match> | `skills/<handbook_slug>/<slug>.dml` | `["<the user's request>"]` |
220
+
221
+ Conventions:
222
+
223
+ - `args` carries the natural-language request; pass the user's message through.
224
+ - If the skill has verification, do not claim success unless it passes.
225
+ - Detailed maps live in each handbook's
226
+ `.pi/deepclause/skills/<handbook_slug>/INDEX.md`.
227
+ ```
228
+
229
+ Rules:
230
+
231
+ 1. **`Handbook`** — the `<handbook_slug>` directory under `.pi/deepclause/skills/`.
232
+ 2. **`Procedure / trigger`** — a short phrase in the *user's* wording.
233
+ 3. **`Skill`** — path relative to `.pi/deepclause/`; must contain `/`.
234
+ 4. **`Args`** — the request text (the skill parses it). One row per procedure.
235
+ 5. Update the table in the same change; tell the user to `/reload` if pi is
236
+ already running.
237
+
238
+ ## Testing checklist
239
+
240
+ For each generated skill:
241
+
242
+ 1. `/dc-run skills/<handbook_slug>/<slug>.dml "<request>" --context=isolated --debug`
243
+ — runs clean; verification (if any) passes or the fallback explains.
244
+ 2. Inspect phase is read-only, action phase is write-only, and a forbidden
245
+ action has no tool at all.
246
+ 3. Deterministic code is limited to arithmetic/counts; every deterministic
247
+ check has an LLM fallback branch.
248
+ 4. The tool audit was done and its result is recorded in the header/INDEX.
249
+ 5. Re-check the invalid-pattern table in `.pi/deepclause/AGENTS.md` (singleton
250
+ variables, `~` vs `{}` interpolation, `Result.field` vs `get_dict/3`, `->`
251
+ committing over generators, `answer/1` last, `:- dynamic` before
252
+ `assertz/retract`).
253
+
254
+ `--context=isolated` keeps session text out of the run. The runtime still needs
255
+ a model selected.
256
+
257
+ ## Reference shape
258
+
259
+ A typical procedure skill has: `agent_main(Request)` that parses the request
260
+ with `task/N`, confirms with the user via a `user_feedback` tool loop, acts
261
+ through write tools, and reviews with `prompt/N` — with small deterministic
262
+ helpers for arithmetic and a fallback branch instead of hard failures.
263
+
264
+ For DML mechanics, see the bundled example skills in a fresh workspace
265
+ (`example.dml`, `deep_research.dml`) and `.pi/deepclause/AGENTS.md`.
@@ -375,6 +375,22 @@ DML is most valuable when an application needs more structure than a prompt and
375
375
 
376
376
  Poor fits include long-running background services, high-frequency shell automation that would require many approval prompts, workflows needing unrestricted pi tools, secret handling, or durable state without an explicit workspace storage design.
377
377
 
378
+ ## Diagrams
379
+
380
+ Pi can turn any DML file into a self-contained, offline Mermaid viewer. Ask for one in plain language:
381
+
382
+ > "Make a presentation-grade diagram of .pi/deepclause/skills/my_skill.dml"
383
+ > "Give me a specification-grade diagram of src/report.dml"
384
+
385
+ Pi calls the `dc_diagram` model tool with the DML path and a grade:
386
+
387
+ - **presentation** — about 8-12 nodes, plain language, headline numbers (slides and overviews).
388
+ - **specification** — function names, task/tool roles, post-conditions (engineers).
389
+
390
+ The tool extracts a deterministic Mermaid seed, has pi rewrite it in the chosen grade, validates the result, writes the viewer under `.pi/deepclause/diagrams/`, and opens it. The DML file may live anywhere (workspace-relative or absolute); only the generated viewer stays under `.pi/deepclause/`.
391
+
392
+ Do not hand-write Mermaid for the user, and do not copy diagram tooling into the workspace. Regenerating a grade replaces only that grade's sidecar (`<name>.presentation.mmd` / `<name>.specification.mmd`).
393
+
378
394
  ## Conservative editing rules
379
395
 
380
396
  When modifying an existing skill: