deepclause-pi 0.1.3

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,116 @@
1
+ import { access, mkdir, readFile, realpath, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { DEFAULT_CONFIG } from "./config.js";
5
+ export const EXAMPLE_DML = `% Pi-hosted DeepClause tour.
6
+ % Demonstrates deterministic CLP(FD), read-only and approved bash pi tools,
7
+ % progress events, typed LLM output, and a final answer.
8
+ % Run with: /dc-run example --debug
9
+ :- use_module(library(clpfd)).
10
+
11
+ solve_pair(X, Y) :-
12
+ X in 1..20,
13
+ Y in 1..20,
14
+ X #< Y,
15
+ X + Y #= 14,
16
+ X * Y #= 48,
17
+ labeling([], [X, Y]).
18
+
19
+ agent_main :-
20
+ output("Phase 1/4: solving X + Y = 14 and X * Y = 48 with CLP(FD)..."),
21
+ solve_pair(X, Y),
22
+ format(string(Solved), "The deterministic solution is X=~w and Y=~w.", [X, Y]),
23
+ output(Solved),
24
+ output("Phase 2/4: listing the active workspace through pi_workspace_list..."),
25
+ exec(pi_workspace_list("."), WorkspaceResult),
26
+ get_dict(entries, WorkspaceResult, Entries),
27
+ length(Entries, EntryCount),
28
+ format(string(ToolSummary), "pi.exec returned ~w top-level workspace entries: ~w", [EntryCount, Entries]),
29
+ output(ToolSummary),
30
+ output("Phase 3/4: requesting an approved bash command through pi_bash..."),
31
+ exec(pi_bash("printf 'bash bridge cwd=%s' \\"$PWD\\""), BashResult),
32
+ get_dict(stdout, BashResult, BashStdout),
33
+ normalize_space(string(BashSummary), BashStdout),
34
+ output(BashSummary),
35
+ output("Phase 4/4: asking pi's active model for a concise explanation..."),
36
+ format(string(Request),
37
+ "Explain in two short sentences why X=~w and Y=~w satisfy X + Y = 14 and X * Y = 48. Mention that the pi-hosted workspace tool observed ~w top-level entries and the approved bash bridge returned: ~w. Store only the explanation in Explanation.",
38
+ [X, Y, EntryCount, BashSummary]),
39
+ task(Request, string(Explanation)),
40
+ format(string(Result), "~w\\n~w\\nBash: ~w\\n\\nModel explanation: ~w", [Solved, ToolSummary, BashSummary, Explanation]),
41
+ answer(Result).
42
+ `;
43
+ export function getPaths(cwd) {
44
+ const root = path.join(cwd, ".pi", "deepclause");
45
+ return {
46
+ root,
47
+ skills: path.join(root, "skills"),
48
+ plans: path.join(root, "plans"),
49
+ config: path.join(root, "config.json"),
50
+ agents: path.join(root, "AGENTS.md"),
51
+ reference: path.join(root, "DML_REFERENCE.md"),
52
+ };
53
+ }
54
+ async function writeIfMissing(filePath, content) {
55
+ try {
56
+ await writeFile(filePath, content, { encoding: "utf8", flag: "wx" });
57
+ }
58
+ catch (error) {
59
+ if (error.code !== "EEXIST")
60
+ throw error;
61
+ }
62
+ }
63
+ async function bundledReference() {
64
+ const sdkEntry = fileURLToPath(import.meta.resolve("deepclause-sdk"));
65
+ const referencePath = path.join(path.dirname(sdkEntry), "system", "assets", "docs", "DML_REFERENCE.md");
66
+ return readFile(referencePath, "utf8");
67
+ }
68
+ async function bundledAuthoringGuide() {
69
+ return readFile(fileURLToPath(new URL("./assets/AGENTS.md", import.meta.url)), "utf8");
70
+ }
71
+ async function bundledDeepResearch() {
72
+ return readFile(fileURLToPath(new URL("./assets/deep_research.dml", import.meta.url)), "utf8");
73
+ }
74
+ export async function initializeWorkspace(cwd) {
75
+ const paths = getPaths(cwd);
76
+ await Promise.all([
77
+ mkdir(paths.skills, { recursive: true }),
78
+ mkdir(paths.plans, { recursive: true }),
79
+ ]);
80
+ await Promise.all([
81
+ writeIfMissing(paths.config, `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\n`),
82
+ writeIfMissing(paths.agents, await bundledAuthoringGuide()),
83
+ writeIfMissing(paths.reference, await bundledReference()),
84
+ writeIfMissing(path.join(paths.skills, "example.dml"), EXAMPLE_DML),
85
+ writeIfMissing(path.join(paths.skills, "deep_research.dml"), await bundledDeepResearch()),
86
+ ]);
87
+ return paths;
88
+ }
89
+ function isInside(parent, child) {
90
+ const relative = path.relative(parent, child);
91
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
92
+ }
93
+ export async function resolveDmlPath(paths, request) {
94
+ if (!request || path.isAbsolute(request))
95
+ throw new Error("A relative skill name or path is required");
96
+ const hasPathSyntax = request.includes("/") || request.includes("\\");
97
+ const candidate = hasPathSyntax
98
+ ? path.resolve(paths.root, request)
99
+ : path.resolve(paths.skills, request.endsWith(".dml") ? request : `${request}.dml`);
100
+ if (!isInside(path.resolve(paths.root), candidate))
101
+ throw new Error("DML path escapes .pi/deepclause");
102
+ try {
103
+ await access(candidate);
104
+ const [realRoot, realCandidate] = await Promise.all([realpath(paths.root), realpath(candidate)]);
105
+ if (!isInside(realRoot, realCandidate))
106
+ throw new Error("DML path escapes .pi/deepclause through a symlink");
107
+ if (!realCandidate.endsWith(".dml"))
108
+ throw new Error("DeepClause programs must use the .dml extension");
109
+ return realCandidate;
110
+ }
111
+ catch (error) {
112
+ if (error.code === "ENOENT")
113
+ throw new Error(`DML file not found: ${request}`);
114
+ throw error;
115
+ }
116
+ }
@@ -0,0 +1,172 @@
1
+ # DML authoring guide analysis
2
+
3
+ ## Purpose
4
+
5
+ This document records the evidence and design decisions behind the pi-specific guide seeded as `.pi/deepclause/AGENTS.md`. The guide is intentionally not a copy of one SDK document: the SDK corpus addresses several runtimes, includes legacy examples, and contains both implemented and proposed features.
6
+
7
+ The proposed pi-native plan-generation and delegated-execution architecture is documented separately in [DC_PLAN_PROPOSAL.md](DC_PLAN_PROPOSAL.md).
8
+
9
+ ## Corpus reviewed
10
+
11
+ The review covered these source categories in `deepclause-sdk`:
12
+
13
+ - Language references: `docs/DML_REFERENCE.md`, `docs/DML_FILE_PATTERNS.md`, and the packaged reference under `src/system/assets/docs/`.
14
+ - Model instructions: `DML_COMPILER_PROMPT.md`, `TASK_PROMPT.md`, `CONDUCTOR_PROMPT.md`, and the coding-workflow recipe.
15
+ - Runtime implementation: `src/agent.ts`, `src/runner.ts`, `src/types.ts`, `src/prolog/bridge.ts`, and `src/prolog-src/deepclause_mi.pl`.
16
+ - Examples: research, coding, conversational, knowledge-base, CLP(FD), data-analysis, file, nested-task, type, and tool-scoping programs under `dml-examples/`.
17
+ - System DML: planner, conductor, security planner, skill creator, and compactors.
18
+ - Planning benchmarks: travel variants and worker plans under `benchmarks/deepplanning/` and `benchmarks/worker/`.
19
+ - Benchmark and design Markdown: SWE-bench design, retry design, travel-planner specification, and natural-language examples.
20
+ - Pi integration: workspace initialization, context import, active-model adapter, event mapping, command parsing, restricted tools, examples, and tests.
21
+
22
+ Generated `dist/` copies and dependency trees were excluded where their source equivalents existed.
23
+
24
+ ## Findings
25
+
26
+ ### The runtime is the source of truth
27
+
28
+ The current meta-interpreter dispatches `agent_main/0` through `agent_main/3`, while some older reference text only mentions arities through 2. It transforms `task` calls with zero through four output variables. The pi command supplies positional strings and does not expose arbitrary named user parameters.
29
+
30
+ The guide therefore documents the implemented pi surface rather than repeating older limits.
31
+
32
+ ### The compiler prompt contains useful hard-earned rules, but cannot be copied directly
33
+
34
+ The compiler prompt has the strongest catalog of common generation failures:
35
+
36
+ - exact variable names in task descriptions
37
+ - `{Variable}` interpolation
38
+ - correct `format/3` and `get_dict/3` use
39
+ - typed task outputs
40
+ - output before long operations
41
+ - explicit fallback clauses
42
+ - safe list and dict idioms
43
+
44
+ However, it assumes the general CLI environment, `.deepclause/`, compiler and validation commands, package installation, and tools such as `web_search`, `url_fetch`, `write_file`, and generic `bash`. Those assumptions are wrong for pi. The new guide retains language rules while replacing the environment and tool sections with pi's actual boundary.
45
+
46
+ ### Examples are pattern evidence, not API guarantees
47
+
48
+ The examples demonstrate valuable architectures:
49
+
50
+ - `deep_research.dml`: staged planning, feedback, gathering, and synthesis
51
+ - `coding-agent.dml`: failure-driven control and explicit progress
52
+ - `knowledge-agent.dml`: symbolic facts exposed through model-callable tools
53
+ - `clpfd-planner.dml`: model creativity followed by deterministic constraints
54
+ - nested-task and tool-scoping examples: capability composition and memory isolation
55
+
56
+ Many SDK examples use legacy or CLI-only tools such as `vm_exec`, `web_search`, and unrestricted file operations. The guide uses their architecture but never advertises those tools as available in pi.
57
+
58
+ ### The planning benchmarks contain the strongest DML design principle
59
+
60
+ The later travel benchmark decomposes work into:
61
+
62
+ 1. typed model extraction
63
+ 2. candidate gathering
64
+ 3. Prolog candidate selection
65
+ 4. deterministic hard-constraint checks
66
+ 5. model scheduling or presentation
67
+ 6. backtracking to another candidate on failure
68
+
69
+ This yields the guide's central model: **a deterministic workflow with probabilistic leaves**. It is more useful than presenting DML as prompt chaining because it explains when DML provides value over a script or a single model call.
70
+
71
+ ### Design documents may describe unimplemented features
72
+
73
+ `benchmarks/RETRY_DESIGN.md` proposes `retry_atmost/2` and `retry_with_analysis/2`. It is a design document, not evidence that those predicates exist in the current runtime. The guide does not expose them. It uses implemented Prolog clauses, recursion, failure, and backtracking instead.
74
+
75
+ ### Backtracking needs an effects warning
76
+
77
+ Model memory can roll back with Prolog control flow, but external commands, file writes, user-visible output, and other side effects are not transactional. Examples that celebrate retry behavior without this distinction can lead to duplicate or destructive actions. The guide makes the distinction explicit.
78
+
79
+ ### Pi changes the safety and usability model
80
+
81
+ The pi integration provides:
82
+
83
+ - pi's selected model and credentials
84
+ - `turn`, `branch`, and `isolated` session import
85
+ - cancellation and usage accounting
86
+ - progress, tool, input, answer, and error events
87
+ - `pi_workspace_list/1`
88
+ - approval-gated `pi_bash/1` and argv-mode `pi_bash/2`
89
+ - internal `ask_user` input that can be wrapped in DML
90
+
91
+ It intentionally does not provide the full pi tool registry, compilation, unrestricted paths, concurrent runs, or separate persistent sessions. The authoring guide treats these constraints as application design inputs, not footnotes.
92
+
93
+ ## Guide design
94
+
95
+ The seeded guide is organized for an AI coding agent rather than as a language encyclopedia:
96
+
97
+ 1. non-negotiable workspace rules
98
+ 2. useful mental model
99
+ 3. before/after authoring workflow
100
+ 4. executable entry-point contract
101
+ 5. choosing `task`, `prompt`, or `llm`
102
+ 6. memory and typed results
103
+ 7. interpolation and Prolog formatting
104
+ 8. direct host calls versus model-callable DML tools
105
+ 9. exact pi runtime capabilities and approvals
106
+ 10. progress and completion
107
+ 11. backtracking, deterministic validation, and CLP
108
+ 12. reusable architecture patterns
109
+ 13. application space
110
+ 14. conservative editing rules
111
+ 15. common invalid patterns
112
+ 16. robust starting template
113
+
114
+ The full SDK reference remains available beside it for breadth. The guide acts as the opinionated pi-specific layer that resolves conflicts and prioritizes reliable patterns.
115
+
116
+ ## Application space
117
+
118
+ ### Evidence and research systems
119
+
120
+ Architecture: plan → optional user review → several narrow retrieval calls → deterministic source normalization → synthesis → independent review.
121
+
122
+ Examples include literature reviews, claim/evidence matrices, competitive intelligence, policy monitoring, and due-diligence briefs. The current pi runtime can use approved `curl` in argv mode, as demonstrated by the Bing RSS example.
123
+
124
+ ### Constrained planners and configurators
125
+
126
+ Architecture: extract typed constraints → gather options → solve with Prolog or CLP → explain the selected solution.
127
+
128
+ Examples include schedules, budgets, event plans, staffing, package/configuration selection, eligibility, and resource allocation. This is where DML most clearly outperforms unconstrained prompt chaining.
129
+
130
+ ### Workspace engineering agents
131
+
132
+ Architecture: inspect workspace → create a bounded action plan → ask for confirmation when needed → run approved commands → parse test/build results → repair or report.
133
+
134
+ Examples include release audits, migration preparation, repository triage, test orchestration, dependency checks, and code-review pipelines. Repeated command approvals make high-frequency autonomous shell loops a poor fit unless the permission model later evolves.
135
+
136
+ ### Compliance and quality gates
137
+
138
+ Architecture: model extracts or drafts structured artifacts → deterministic predicates enforce policy → failures select remediation or a static fallback.
139
+
140
+ Examples include requirements traceability, security review, editorial rubrics, policy checks, and structured acceptance gates.
141
+
142
+ ### Interactive expert systems
143
+
144
+ Architecture: Prolog facts and rules hold stable domain knowledge → narrow tools expose queries or state transitions → a task provides natural-language interaction → `ask_user` handles missing decisions.
145
+
146
+ Examples include troubleshooting, guided intake, product configuration, and rule-based decision support.
147
+
148
+ ### Data and content pipelines
149
+
150
+ Architecture: approved command retrieves data → Prolog parses and filters → typed tasks classify or summarize → deterministic aggregation → final report.
151
+
152
+ Examples include JSON/CSV triage, issue classification, report generation, brief-to-draft workflows, and independent editorial review.
153
+
154
+ ### Pure symbolic applications
155
+
156
+ A DML skill need not call a model. Prolog recursion, facts, parsing, and CLP can provide deterministic validators, transformations, finite search, simulations, and optimization while still benefiting from pi's command, cancellation, and UI integration.
157
+
158
+ ## Poor fits under the current boundary
159
+
160
+ - background services and concurrent workers
161
+ - silent or high-frequency shell automation requiring many approvals
162
+ - workflows requiring arbitrary pi tools
163
+ - secret discovery or credential management
164
+ - unbounded web crawling or large raw-context ingestion
165
+ - durable application state without an explicit, user-approved workspace storage design
166
+
167
+ ## Maintenance policy
168
+
169
+ - Keep the guide aligned with implementation and tests, not aspirational design files.
170
+ - Add a pi capability only after it is registered and policy-tested.
171
+ - Do not silently overwrite an existing workspace guide. New bundled guidance applies to newly initialized workspaces until an explicit non-destructive documentation versioning mechanism is introduced.
172
+ - When SDK behavior changes, review entry arity, task result typing, interpolation, memory, tool scoping, and side-effect semantics first.