deepclause-pi 0.2.0 → 0.4.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.
package/dist/planner.d.ts CHANGED
@@ -10,6 +10,8 @@ export interface PlanStepSpec {
10
10
  requiredTools: string[];
11
11
  relevantSkills: string[];
12
12
  expectedResult: string;
13
+ satisfies: string[];
14
+ checks: string[];
13
15
  }
14
16
  export interface PlanSpec {
15
17
  slug: string;
@@ -19,6 +21,11 @@ export interface PlanSpec {
19
21
  steps: PlanStepSpec[];
20
22
  finalSynthesis?: string;
21
23
  failureMessage: string;
24
+ change?: string;
25
+ }
26
+ export interface ValidatePlanOptions {
27
+ requireChecks?: boolean;
28
+ change?: string;
22
29
  }
23
30
  export interface PlanningSnapshot {
24
31
  model: string;
@@ -36,10 +43,28 @@ export interface ValidatedPlan {
36
43
  warnings: string[];
37
44
  }
38
45
  export declare function normalizePlanSlug(value: string): string;
39
- export declare function validatePlanSpec(value: unknown, snapshot: PlanningSnapshot, nameOverride?: string): ValidatedPlan;
46
+ export declare function validatePlanSpec(value: unknown, snapshot: PlanningSnapshot, nameOverride?: string, options?: ValidatePlanOptions): ValidatedPlan;
47
+ export interface ParsedCheck {
48
+ kind: "cmd" | "exists" | "model";
49
+ value: string;
50
+ }
51
+ /** Parse an encoded verification check: cmd:<command>, exists:<path>, model:<question>. */
52
+ export declare function parseCheck(encoded: string): ParsedCheck;
53
+ /**
54
+ * Assemble the `tasks.dml` data artifact for a change: plan_task/2 definitions plus
55
+ * the managed plan_task_status/2 block. Verified by /dc-check and executed by /dc-apply.
56
+ */
57
+ export declare function assembleTasksDml(plan: ValidatedPlan, snapshot: PlanningSnapshot): string;
58
+ /** Write changes/<slug>/tasks.dml, refusing to clobber an existing plan unless overwrite=true. */
59
+ export declare function writeChangeTasks(paths: DeepClausePaths, slug: string, text: string, overwrite?: boolean): Promise<string>;
40
60
  export declare function assemblePlanDml(plan: ValidatedPlan, snapshot: PlanningSnapshot): string;
41
61
  export declare function validateGeneratedPlan(dml: string): Promise<void>;
62
+ /**
63
+ * Data-only artifact (tasks.dml): no agent_main of its own, so validation appends a
64
+ * trivial entry point to parse the facts without changing what is written.
65
+ */
66
+ export declare function validateGeneratedTasks(dml: string): Promise<void>;
42
67
  export declare function writePlanNonDestructively(paths: DeepClausePaths, slug: string, dml: string): Promise<string>;
43
68
  export declare function isContextualPlan(filePath: string): Promise<boolean>;
44
69
  export declare function readPlanRequiredTools(filePath: string): Promise<string[]>;
45
- export declare function buildPlanningPrompt(request: string, snapshot: PlanningSnapshot, nameOverride?: string): string;
70
+ export declare function buildPlanningPrompt(request: string, snapshot: PlanningSnapshot, nameOverride?: string, change?: string, update?: boolean): string;
package/dist/planner.js CHANGED
@@ -31,7 +31,7 @@ export function normalizePlanSlug(value) {
31
31
  throw new Error("Plan slug must contain a letter or digit");
32
32
  return slug;
33
33
  }
34
- export function validatePlanSpec(value, snapshot, nameOverride) {
34
+ export function validatePlanSpec(value, snapshot, nameOverride, options = {}) {
35
35
  if (!value || typeof value !== "object" || Array.isArray(value))
36
36
  throw new Error("Plan specification must be an object");
37
37
  const raw = value;
@@ -48,8 +48,8 @@ export function validatePlanSpec(value, snapshot, nameOverride) {
48
48
  throw new Error(`steps[${index}] must be an object`);
49
49
  const step = entry;
50
50
  const id = requireText(step.id ?? `step_${index + 1}`, `steps[${index}].id`, 80);
51
- if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(id))
52
- throw new Error(`steps[${index}].id must be a simple identifier`);
51
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(id))
52
+ throw new Error(`steps[${index}].id must be a simple identifier (letters, digits, dot, dash, underscore)`);
53
53
  if (ids.has(id))
54
54
  throw new Error(`Duplicate plan step id: ${id}`);
55
55
  ids.add(id);
@@ -58,6 +58,13 @@ export function validatePlanSpec(value, snapshot, nameOverride) {
58
58
  throw new Error(`steps[${index}].executor must be pi or dml`);
59
59
  const requiredTools = stringArray(step.requiredTools, `steps[${index}].requiredTools`, 16);
60
60
  const relevantSkills = stringArray(step.relevantSkills, `steps[${index}].relevantSkills`, 16);
61
+ const satisfies = stringArray(step.satisfies, `steps[${index}].satisfies`, 32);
62
+ const checks = stringArray(step.checks, `steps[${index}].checks`, 16);
63
+ for (const check of checks)
64
+ parseCheck(check);
65
+ if (options.requireChecks && checks.length === 0) {
66
+ throw new Error(`Plan step ${id} must declare at least one verification check (cmd:..., exists:... or model:...)`);
67
+ }
61
68
  if (executor === "dml" && requiredTools.length > 0) {
62
69
  throw new Error(`DML step ${id} cannot request pi tools; use executor=pi`);
63
70
  }
@@ -81,6 +88,8 @@ export function validatePlanSpec(value, snapshot, nameOverride) {
81
88
  requiredTools: [...new Set(requiredTools)],
82
89
  relevantSkills: [...new Set(relevantSkills)],
83
90
  expectedResult: requireText(step.expectedResult, `steps[${index}].expectedResult`, 1_000),
91
+ satisfies: [...new Set(satisfies)],
92
+ checks: [...new Set(checks)],
84
93
  };
85
94
  });
86
95
  const spec = {
@@ -93,6 +102,7 @@ export function validatePlanSpec(value, snapshot, nameOverride) {
93
102
  ? requireText(raw.finalSynthesis, "finalSynthesis", 2_000)
94
103
  : undefined,
95
104
  failureMessage: requireText(raw.failureMessage, "failureMessage", 1_000),
105
+ change: options.change ? normalizePlanSlug(options.change) : undefined,
96
106
  };
97
107
  return {
98
108
  spec,
@@ -109,6 +119,71 @@ function dmlStringList(values) {
109
119
  function commentText(value) {
110
120
  return value.replace(/[\r\n]+/g, " ").replace(/%/g, "percent").trim();
111
121
  }
122
+ /** Parse an encoded verification check: cmd:<command>, exists:<path>, model:<question>. */
123
+ export function parseCheck(encoded) {
124
+ const separator = encoded.indexOf(":");
125
+ if (separator <= 0)
126
+ throw new Error(`Check must be cmd:..., exists:... or model:...; got '${encoded}'`);
127
+ const kind = encoded.slice(0, separator).trim();
128
+ const value = encoded.slice(separator + 1).trim();
129
+ if (kind !== "cmd" && kind !== "exists" && kind !== "model")
130
+ throw new Error(`Unknown check kind '${kind}' in '${encoded}'`);
131
+ if (!value)
132
+ throw new Error(`Check '${encoded}' has an empty value`);
133
+ return { kind, value };
134
+ }
135
+ /**
136
+ * Assemble the `tasks.dml` data artifact for a change: plan_task/2 definitions plus
137
+ * the managed plan_task_status/2 block. Verified by /dc-check and executed by /dc-apply.
138
+ */
139
+ export function assembleTasksDml(plan, snapshot) {
140
+ const { spec } = plan;
141
+ const taskBlocks = spec.steps.map((step) => {
142
+ const checks = step.checks.map((encoded) => {
143
+ const { kind, value } = parseCheck(encoded);
144
+ return `${kind}(${dmlString(value)})`;
145
+ });
146
+ return [
147
+ `plan_task(${dmlString(step.id)}, task{`,
148
+ ` executor: ${step.executor},`,
149
+ ` do: ${dmlString(step.instruction)},`,
150
+ ` tools: ${dmlStringList(step.requiredTools)},`,
151
+ ` expected: ${dmlString(step.expectedResult)},`,
152
+ ` satisfies: ${dmlStringList(step.satisfies)},`,
153
+ ` checks: [${checks.join(", ")}]`,
154
+ `}).`,
155
+ ].join("\n");
156
+ });
157
+ const statusLines = spec.steps.map((step) => `plan_task_status(${dmlString(step.id)}, pending).`);
158
+ const metadata = [
159
+ "% tasks.dml — generated by /dc-plan. Edit conservatively.",
160
+ `% Change: ${commentText(spec.change ?? spec.slug)}`,
161
+ `% Title: ${commentText(spec.title)}`,
162
+ `% Planning model: ${commentText(snapshot.model)}`,
163
+ `% Required pi tools: ${plan.requiredTools.join(", ") || "none"}`,
164
+ ].join("\n");
165
+ return `${metadata}\n\n${taskBlocks.join("\n\n")}\n\n% --- execution state (managed by apply.dml; do not edit by hand) ---\n${statusLines.join("\n")}\n`;
166
+ }
167
+ /** Write changes/<slug>/tasks.dml, refusing to clobber an existing plan unless overwrite=true. */
168
+ export async function writeChangeTasks(paths, slug, text, overwrite = false) {
169
+ const dir = path.join(paths.changes, slug);
170
+ await mkdir(dir, { recursive: true });
171
+ const filePath = path.join(dir, "tasks.dml");
172
+ if (overwrite) {
173
+ await writeFile(filePath, text, { encoding: "utf8" });
174
+ return filePath;
175
+ }
176
+ try {
177
+ await writeFile(filePath, text, { encoding: "utf8", flag: "wx" });
178
+ }
179
+ catch (error) {
180
+ if (error.code === "EEXIST") {
181
+ throw new Error(`changes/${slug}/tasks.dml already exists; re-run with --update to regenerate it`);
182
+ }
183
+ throw error;
184
+ }
185
+ return filePath;
186
+ }
112
187
  export function assemblePlanDml(plan, snapshot) {
113
188
  const { spec } = plan;
114
189
  const resultVariables = [];
@@ -167,6 +242,17 @@ export async function validateGeneratedPlan(dml) {
167
242
  if (!validation.valid)
168
243
  throw new Error(`Generated DML failed validation: ${validation.errors.join("; ")}`);
169
244
  }
245
+ /**
246
+ * Data-only artifact (tasks.dml): no agent_main of its own, so validation appends a
247
+ * trivial entry point to parse the facts without changing what is written.
248
+ */
249
+ export async function validateGeneratedTasks(dml) {
250
+ if (dml.includes(".deepclause/"))
251
+ throw new Error("Generated tasks may not reference .deepclause/");
252
+ const validation = await validateWithProlog(`${dml}\nagent_main :- true.\n`);
253
+ if (!validation.valid)
254
+ throw new Error(`Generated tasks.dml failed validation: ${validation.errors.join("; ")}`);
255
+ }
170
256
  export async function writePlanNonDestructively(paths, slug, dml) {
171
257
  await mkdir(paths.plans, { recursive: true });
172
258
  for (let suffix = 1; suffix <= 100; suffix++) {
@@ -193,7 +279,7 @@ export async function readPlanRequiredTools(filePath) {
193
279
  return [];
194
280
  return [...new Set(match[1].split(",").map((name) => name.trim()).filter(Boolean))];
195
281
  }
196
- export function buildPlanningPrompt(request, snapshot, nameOverride) {
282
+ export function buildPlanningPrompt(request, snapshot, nameOverride, change, update = false) {
197
283
  const tools = snapshot.allTools.map((tool) => ({
198
284
  name: tool.name,
199
285
  active: snapshot.activeTools.includes(tool.name),
@@ -202,6 +288,24 @@ export function buildPlanningPrompt(request, snapshot, nameOverride) {
202
288
  guidelines: tool.promptGuidelines ?? [],
203
289
  source: tool.sourceInfo,
204
290
  }));
291
+ const changeInstructions = change
292
+ ? [
293
+ update
294
+ ? `This regenerates the change '${change}'. Read the existing .pi/deepclause/changes/${change}/proposal.md, specs/**, design.md and tasks.dml first, then revise them as needed.`
295
+ : `This plan is for the change '${change}'. Before committing, create .pi/deepclause/changes/${change}/ with normal file tools:`,
296
+ ...(update
297
+ ? []
298
+ : [
299
+ "- proposal.md — why / what / capabilities / impact.",
300
+ "- specs/<capability>.spec.md — delta(s) using ## ADDED|MODIFIED|REMOVED Requirements.",
301
+ "- design.md — optional approach and trade-offs.",
302
+ ]),
303
+ "Specs describe behaviour only: no commands, file paths, library choices or implementation steps.",
304
+ "Use exactly three hashes for ### Requirement and four for #### Scenario; every requirement needs at least one scenario.",
305
+ "Each committed step must list the scenario ids it satisfies (capability#scenario-slug) and at least one check encoded as cmd:<command>, exists:<path> or model:<question>.",
306
+ "The committed tasks.dml replaces any previous one; every plan_task_status entry resets to pending.",
307
+ ]
308
+ : [];
205
309
  return [
206
310
  "Create an executable DeepClause plan for the request below.",
207
311
  "You are in a normal pi turn: inspect the workspace and use currently active tools when that materially improves the plan.",
@@ -211,6 +315,7 @@ export function buildPlanningPrompt(request, snapshot, nameOverride) {
211
315
  "Choose executor='dml' for contained reasoning that needs no pi tool; requiredTools must then be empty.",
212
316
  "Use only exact active tool names. Never request dc_run, dc_plan_commit, or pi_agent_step.",
213
317
  "Keep steps bounded, concrete, ordered, and independently observable. Prefer 3-8 steps.",
318
+ ...changeInstructions,
214
319
  nameOverride ? `The user requested the plan filename slug: ${nameOverride}` : "Choose a concise lowercase slug.",
215
320
  `User request:\n${request}`,
216
321
  `Current model: ${snapshot.model}; thinking level: ${snapshot.thinkingLevel}`,
package/dist/runtime.d.ts CHANGED
@@ -3,6 +3,20 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
3
3
  import type { DeepClauseConfig } from "./config.js";
4
4
  export declare const PI_WORKSPACE_LIST_TOOL = "pi_workspace_list";
5
5
  export declare const PI_BASH_TOOL = "pi_bash";
6
+ export declare const DC_VERIFY_RUN_TOOL = "dc_verify_run";
7
+ export declare const DC_APPLY_SNAPSHOT_TOOL = "dc_apply_snapshot";
8
+ export declare const DC_APPLY_ACCEPT_TOOL = "dc_apply_accept";
9
+ export declare const DC_APPLY_RESTORE_TOOL = "dc_apply_restore";
10
+ /**
11
+ * Record a git snapshot ref, refusing a dirty working tree. If an apply is already
12
+ * in progress for this change, the existing ref is returned so the run resumes
13
+ * instead of starting over or rejecting the (intentionally) dirty tree.
14
+ */
15
+ export declare function gitSnapshot(pi: Pick<ExtensionAPI, "exec">, cwd: string, changeJsonPath: string): Promise<string>;
16
+ /** Restore the recorded snapshot (hard reset plus clean of untracked files). */
17
+ export declare function gitRestore(pi: Pick<ExtensionAPI, "exec">, cwd: string, changeJsonPath: string): Promise<string | null>;
18
+ /** Mark the apply accepted and clear the snapshot. */
19
+ export declare function gitAccept(changeJsonPath: string): Promise<void>;
6
20
  export type BashApproval = (command: string, signal: AbortSignal) => Promise<boolean>;
7
21
  export declare function registerPiRuntimeTools(sdk: DeepClauseSDK, pi: Pick<ExtensionAPI, "exec">, cwd: string, signal: AbortSignal, approveBash?: BashApproval): void;
8
22
  export interface ExecutionCallbacks {
@@ -27,4 +41,6 @@ export interface ExecutionResult {
27
41
  errors: string[];
28
42
  usage: LLMUsage;
29
43
  }
30
- export declare function executeDml(filePath: string, args: string[], initialMessages: MemoryMessage[], config: DeepClauseConfig, pi: ExtensionAPI, ctx: ExtensionContext, controller: AbortController, callbacks: ExecutionCallbacks, runPiAgentStep?: (request: PiAgentStepRequest, signal: AbortSignal) => Promise<PiAgentStepResult>): Promise<ExecutionResult>;
44
+ export declare function executeDml(filePath: string, args: string[], initialMessages: MemoryMessage[], config: DeepClauseConfig & {
45
+ judgeBackend?: string;
46
+ }, pi: ExtensionAPI, ctx: ExtensionContext, controller: AbortController, callbacks: ExecutionCallbacks, runPiAgentStep?: (request: PiAgentStepRequest, signal: AbortSignal) => Promise<PiAgentStepResult>, verifyCommands?: string[], applyChangeJsonPath?: string): Promise<ExecutionResult>;
package/dist/runtime.js CHANGED
@@ -1,9 +1,71 @@
1
- import { realpath, readFile } from "node:fs/promises";
1
+ import { realpath, readFile, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { createDeepClause } from "deepclause-sdk";
3
+ import { createDeepClause, createJevJudgeBackend, createLLMJudgeBackend } from "deepclause-sdk";
4
4
  import { PI_AGENT_STEP_TOOL } from "./planner.js";
5
5
  export const PI_WORKSPACE_LIST_TOOL = "pi_workspace_list";
6
6
  export const PI_BASH_TOOL = "pi_bash";
7
+ export const DC_VERIFY_RUN_TOOL = "dc_verify_run";
8
+ export const DC_APPLY_SNAPSHOT_TOOL = "dc_apply_snapshot";
9
+ export const DC_APPLY_ACCEPT_TOOL = "dc_apply_accept";
10
+ export const DC_APPLY_RESTORE_TOOL = "dc_apply_restore";
11
+ async function readChangeJson(changeJsonPath) {
12
+ try {
13
+ const parsed = JSON.parse(await readFile(changeJsonPath, "utf8"));
14
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
15
+ }
16
+ catch {
17
+ return {};
18
+ }
19
+ }
20
+ async function patchChangeJson(changeJsonPath, patch) {
21
+ let existing = {};
22
+ try {
23
+ const parsed = JSON.parse(await readFile(changeJsonPath, "utf8"));
24
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
25
+ existing = parsed;
26
+ }
27
+ catch {
28
+ // start a fresh manifest
29
+ }
30
+ await writeFile(changeJsonPath, `${JSON.stringify({ ...existing, ...patch }, null, 2)}\n`, "utf8");
31
+ }
32
+ /**
33
+ * Record a git snapshot ref, refusing a dirty working tree. If an apply is already
34
+ * in progress for this change, the existing ref is returned so the run resumes
35
+ * instead of starting over or rejecting the (intentionally) dirty tree.
36
+ */
37
+ export async function gitSnapshot(pi, cwd, changeJsonPath) {
38
+ const existing = await readChangeJson(changeJsonPath);
39
+ const resumable = typeof existing.snapshot === "string" && existing.snapshot && existing.applyState === "in_progress";
40
+ if (resumable)
41
+ return existing.snapshot;
42
+ const status = await pi.exec("git", ["status", "--porcelain"], { cwd });
43
+ if (status.code !== 0)
44
+ throw new Error("git is unavailable or this is not a repository");
45
+ if (status.stdout.trim())
46
+ throw new Error("working tree is dirty; commit or stash before applying, or resume with /dc-apply (which preserves an interrupted apply)");
47
+ const head = await pi.exec("git", ["rev-parse", "HEAD"], { cwd });
48
+ if (head.code !== 0)
49
+ throw new Error("could not read git HEAD");
50
+ const ref = head.stdout.trim();
51
+ await patchChangeJson(changeJsonPath, { snapshot: ref, applyState: "in_progress" });
52
+ return ref;
53
+ }
54
+ /** Restore the recorded snapshot (hard reset plus clean of untracked files). */
55
+ export async function gitRestore(pi, cwd, changeJsonPath) {
56
+ const existing = await readChangeJson(changeJsonPath);
57
+ const ref = typeof existing.snapshot === "string" && existing.snapshot ? existing.snapshot : null;
58
+ if (!ref)
59
+ return null;
60
+ await pi.exec("git", ["reset", "--hard", ref], { cwd });
61
+ await pi.exec("git", ["clean", "-fd"], { cwd });
62
+ await patchChangeJson(changeJsonPath, { snapshot: null, applyState: "aborted" });
63
+ return ref;
64
+ }
65
+ /** Mark the apply accepted and clear the snapshot. */
66
+ export async function gitAccept(changeJsonPath) {
67
+ await patchChangeJson(changeJsonPath, { snapshot: null, applyState: "done" });
68
+ }
7
69
  function isInside(parent, child) {
8
70
  const relative = path.relative(parent, child);
9
71
  return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
@@ -198,17 +260,38 @@ function createPiBackend(ctx, maxTokens, onDiagnostic) {
198
260
  },
199
261
  };
200
262
  }
201
- export async function executeDml(filePath, args, initialMessages, config, pi, ctx, controller, callbacks, runPiAgentStep) {
263
+ export async function executeDml(filePath, args, initialMessages, config, pi, ctx, controller, callbacks, runPiAgentStep, verifyCommands = [], applyChangeJsonPath) {
202
264
  const model = ctx.model;
203
265
  if (!model)
204
266
  throw new Error("Select a pi model before running DeepClause");
205
267
  const backend = createPiBackend(ctx, config.maxTokens, callbacks.onDiagnostic ?? (() => { }));
268
+ // Judgment backends. `llm` reuses pi's active model and credentials; `jev`
269
+ // is opt-in and only registered when enabled and its key is present.
270
+ const judgeBackends = {
271
+ llm: createLLMJudgeBackend({ llmBackend: backend, model: model.id }),
272
+ };
273
+ const jev = config.judgment.jev;
274
+ if (jev.enabled) {
275
+ const apiKey = process.env[jev.apiKeyEnv];
276
+ if (apiKey) {
277
+ judgeBackends.jev = createJevJudgeBackend({ apiKey, model: jev.model });
278
+ }
279
+ else {
280
+ callbacks.onDiagnostic?.(`judgment backend 'jev' is enabled but ${jev.apiKeyEnv} is not set; falling back to 'llm'`);
281
+ }
282
+ }
283
+ const requestedJudge = config.judgeBackend ?? config.judgment.default;
284
+ if (!judgeBackends[requestedJudge]) {
285
+ throw new Error(`Judgment backend '${requestedJudge}' is not available. Enable it in .pi/deepclause/config.json or use --judge=llm.`);
286
+ }
206
287
  const sdk = await createDeepClause({
207
288
  model: model.id,
208
289
  maxTokens: config.maxTokens,
209
290
  streaming: true,
210
291
  debug: config.verbose,
211
292
  llmBackend: backend,
293
+ judgeBackends,
294
+ defaultJudge: requestedJudge,
212
295
  });
213
296
  registerPiRuntimeTools(sdk, pi, ctx.cwd, controller.signal, async (command, signal) => {
214
297
  if (!ctx.hasUI)
@@ -242,9 +325,60 @@ export async function executeDml(filePath, args, initialMessages, config, pi, ct
242
325
  },
243
326
  });
244
327
  }
328
+ if (verifyCommands.length > 0) {
329
+ sdk.registerTool(DC_VERIFY_RUN_TOOL, {
330
+ description: "Run one of the change's pre-approved verification commands in the workspace and return its exit code, stdout and stderr.",
331
+ parameters: {
332
+ type: "object",
333
+ properties: {
334
+ command: { type: "string", description: "Exact approved command string" },
335
+ },
336
+ required: ["command"],
337
+ },
338
+ execute: async (args) => {
339
+ const command = typeof args.command === "string" ? args.command.trim() : "";
340
+ if (!verifyCommands.includes(command)) {
341
+ throw new Error(`verification command was not approved for this run: ${command}`);
342
+ }
343
+ const result = await pi.exec("bash", ["-lc", command], {
344
+ cwd: ctx.cwd,
345
+ signal: controller.signal,
346
+ timeout: 120_000,
347
+ });
348
+ return { command, stdout: result.stdout, stderr: result.stderr, exitCode: result.code, killed: result.killed };
349
+ },
350
+ });
351
+ }
352
+ if (applyChangeJsonPath) {
353
+ const changeJsonPath = applyChangeJsonPath;
354
+ sdk.registerTool(DC_APPLY_SNAPSHOT_TOOL, {
355
+ description: "Record a git snapshot of the workspace before applying tasks. Refuses a dirty working tree.",
356
+ parameters: { type: "object", properties: {}, required: [] },
357
+ execute: async () => gitSnapshot(pi, ctx.cwd, changeJsonPath),
358
+ });
359
+ sdk.registerTool(DC_APPLY_ACCEPT_TOOL, {
360
+ description: "Accept the apply so the working tree is not restored.",
361
+ parameters: { type: "object", properties: {}, required: [] },
362
+ execute: async () => {
363
+ await gitAccept(changeJsonPath);
364
+ return "accepted";
365
+ },
366
+ });
367
+ sdk.registerTool(DC_APPLY_RESTORE_TOOL, {
368
+ description: "Restore the recorded snapshot, discarding task changes.",
369
+ parameters: { type: "object", properties: {}, required: [] },
370
+ execute: async () => (await gitRestore(pi, ctx.cwd, changeJsonPath)) ?? "none",
371
+ });
372
+ }
245
373
  sdk.setToolPolicy({
246
374
  mode: "whitelist",
247
- tools: [PI_WORKSPACE_LIST_TOOL, PI_BASH_TOOL, ...(runPiAgentStep ? [PI_AGENT_STEP_TOOL] : [])],
375
+ tools: [
376
+ PI_WORKSPACE_LIST_TOOL,
377
+ PI_BASH_TOOL,
378
+ ...(runPiAgentStep ? [PI_AGENT_STEP_TOOL] : []),
379
+ ...(verifyCommands.length > 0 ? [DC_VERIFY_RUN_TOOL] : []),
380
+ ...(applyChangeJsonPath ? [DC_APPLY_SNAPSHOT_TOOL, DC_APPLY_ACCEPT_TOOL, DC_APPLY_RESTORE_TOOL] : []),
381
+ ],
248
382
  });
249
383
  const result = {
250
384
  errors: [],
@@ -258,6 +392,7 @@ export async function executeDml(filePath, args, initialMessages, config, pi, ct
258
392
  gasLimit: config.gasLimit,
259
393
  signal: controller.signal,
260
394
  initialMessages,
395
+ judgeBackend: config.judgeBackend,
261
396
  onUserInput: (prompt) => callbacks.onInput(prompt, controller.signal),
262
397
  })) {
263
398
  callbacks.onEvent(event);
@@ -2,6 +2,9 @@ export interface DeepClausePaths {
2
2
  root: string;
3
3
  skills: string;
4
4
  plans: string;
5
+ specs: string;
6
+ changes: string;
7
+ lib: string;
5
8
  config: string;
6
9
  agents: string;
7
10
  reference: string;
package/dist/workspace.js CHANGED
@@ -46,6 +46,9 @@ export function getPaths(cwd) {
46
46
  root,
47
47
  skills: path.join(root, "skills"),
48
48
  plans: path.join(root, "plans"),
49
+ specs: path.join(root, "specs"),
50
+ changes: path.join(root, "changes"),
51
+ lib: path.join(root, "lib"),
49
52
  config: path.join(root, "config.json"),
50
53
  agents: path.join(root, "AGENTS.md"),
51
54
  reference: path.join(root, "DML_REFERENCE.md"),
@@ -68,6 +71,9 @@ async function bundledReference() {
68
71
  async function bundledAuthoringGuide() {
69
72
  return readFile(fileURLToPath(new URL("./assets/AGENTS.md", import.meta.url)), "utf8");
70
73
  }
74
+ async function bundledAsset(name) {
75
+ return readFile(fileURLToPath(new URL(`./assets/${name}`, import.meta.url)), "utf8");
76
+ }
71
77
  async function bundledDeepResearch() {
72
78
  return readFile(fileURLToPath(new URL("./assets/deep_research.dml", import.meta.url)), "utf8");
73
79
  }
@@ -76,6 +82,9 @@ export async function initializeWorkspace(cwd) {
76
82
  await Promise.all([
77
83
  mkdir(paths.skills, { recursive: true }),
78
84
  mkdir(paths.plans, { recursive: true }),
85
+ mkdir(paths.specs, { recursive: true }),
86
+ mkdir(paths.changes, { recursive: true }),
87
+ mkdir(paths.lib, { recursive: true }),
79
88
  ]);
80
89
  await Promise.all([
81
90
  writeIfMissing(paths.config, `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\n`),
@@ -83,6 +92,17 @@ export async function initializeWorkspace(cwd) {
83
92
  writeIfMissing(paths.reference, await bundledReference()),
84
93
  writeIfMissing(path.join(paths.skills, "example.dml"), EXAMPLE_DML),
85
94
  writeIfMissing(path.join(paths.skills, "deep_research.dml"), await bundledDeepResearch()),
95
+ writeIfMissing(path.join(paths.lib, "specs.dml"), await bundledAsset("specs.dml")),
96
+ writeIfMissing(path.join(paths.lib, "apply.dml"), await bundledAsset("apply.dml")),
97
+ writeIfMissing(path.join(paths.skills, "spec_validate.dml"), await bundledAsset("spec_validate.dml")),
98
+ writeIfMissing(path.join(paths.skills, "spec_status.dml"), await bundledAsset("spec_status.dml")),
99
+ writeIfMissing(path.join(paths.skills, "spec_query.dml"), await bundledAsset("spec_query.dml")),
100
+ writeIfMissing(path.join(paths.skills, "spec_graph.dml"), await bundledAsset("spec_graph.dml")),
101
+ writeIfMissing(path.join(paths.skills, "spec_merge.dml"), await bundledAsset("spec_merge.dml")),
102
+ writeIfMissing(path.join(paths.skills, "spec_archive.dml"), await bundledAsset("spec_archive.dml")),
103
+ writeIfMissing(path.join(paths.skills, "spec_coverage.dml"), await bundledAsset("spec_coverage.dml")),
104
+ writeIfMissing(path.join(paths.skills, "spec_scaffold.dml"), await bundledAsset("spec_scaffold.dml")),
105
+ writeIfMissing(path.join(paths.skills, "spec_apply.dml"), await bundledAsset("spec_apply.dml")),
86
106
  ]);
87
107
  return paths;
88
108
  }