zagens-cli 0.7.5

Zagens headless CLI + HTTP/SSE runtime sidecar (`zagens`, `zagens-runtime` binaries)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Audit scratchpad tools (`scratchpad_status`, `scratchpad_append`, …).

use async_trait::async_trait;
use serde_json::{Value, json};

use crate::scratchpad::AreaStatus;
use crate::scratchpad::{
    ScratchpadStore, default_init_areas, display_run_path, parse_init_areas, resolve_run_id,
    resolve_run_id_for_init, verify_note, workspace_audit_inventory,
};

fn persist_scratchpad_run(ctx: &ToolContext, run_id: &str) {
    if let Ok(mut guard) = ctx.runtime.wire.scratchpad_run_id.lock() {
        *guard = Some(run_id.to_string());
    }
    if let Some(persist) = &ctx.runtime.wire.persist_scratchpad_run_id {
        persist(run_id.to_string());
    }
}
use crate::tools::spec::{
    ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
    optional_str, required_str,
};

fn run_id_property() -> Value {
    json!({
        "type": "string",
        "description": "Scratchpad run directory name. Defaults to active thread_id or task_id when that directory exists."
    })
}

fn run_id_property_for_init() -> Value {
    json!({
        "type": "string",
        "description": "Scratchpad run directory name. Defaults to active thread_id or task_id (creates the directory if missing)."
    })
}

#[derive(Debug, Default)]
pub struct ScratchpadInitTool;

#[async_trait]
impl ToolSpec for ScratchpadInitTool {
    fn name(&self) -> &'static str {
        "scratchpad_init"
    }

    fn description(&self) -> &'static str {
        "Bootstrap an audit scratchpad run under .zagens/scratchpad/{run_id}/ (inventory.json + notes.jsonl). Idempotent when inventory already exists."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "run_id": run_id_property_for_init(),
                "scope": {
                    "type": "string",
                    "description": "Optional human-readable audit scope stored in inventory.json"
                },
                "areas": {
                    "type": "array",
                    "description": "Inventory rows (default: one pending area for workspace root)",
                    "items": {
                        "type": "object",
                        "properties": {
                            "id": { "type": "string" },
                            "path": { "type": "string" },
                            "notes": { "type": "string" }
                        },
                        "required": ["id", "path"],
                        "additionalProperties": false
                    }
                },
                "template": {
                    "type": "string",
                    "enum": ["workspace_audit"],
                    "description": "When set to workspace_audit, auto-build inventory from workspace Cargo.toml members (includes runtime-server, desktop web-ui areas). Ignores default single-row inventory."
                }
            },
            "additionalProperties": false
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::WritesFiles]
    }

    fn approval_requirement(&self) -> ApprovalRequirement {
        ApprovalRequirement::Auto
    }

    async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
        let run_id = resolve_run_id_for_init(context, optional_str(&input, "run_id"))?;
        let scope = optional_str(&input, "scope");
        let areas = if optional_str(&input, "template") == Some("workspace_audit") {
            workspace_audit_inventory(&context.workspace)?
        } else {
            match input.get("areas").and_then(|v| v.as_array()) {
                Some(raw) => parse_init_areas(raw)?,
                None => default_init_areas(),
            }
        };
        let store = ScratchpadStore::init(context, &run_id, areas, scope)?;
        persist_scratchpad_run(context, &run_id);
        let status = store.build_status()?;
        Ok(ToolResult::success(
            serde_json::to_string_pretty(&json!({
                "run_id": run_id,
                "path": display_run_path(&run_id),
                "status": status,
            }))
            .unwrap_or_default(),
        ))
    }
}

#[derive(Debug, Default)]
pub struct ScratchpadStatusTool;

#[async_trait]
impl ToolSpec for ScratchpadStatusTool {
    fn name(&self) -> &'static str {
        "scratchpad_status"
    }

    fn description(&self) -> &'static str {
        "Return audit scratchpad progress: inventory completion, note counts, resume_area_id, and findings tallies."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "run_id": run_id_property()
            },
            "additionalProperties": false
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::ReadOnly]
    }

    fn approval_requirement(&self) -> ApprovalRequirement {
        ApprovalRequirement::Auto
    }

    async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
        let run_id = resolve_run_id(context, optional_str(&input, "run_id"))?;
        let store = ScratchpadStore::open(context, &run_id)?;
        persist_scratchpad_run(context, &run_id);
        let status = store.build_status()?;
        Ok(ToolResult::success(
            serde_json::to_string_pretty(&status).unwrap_or_default(),
        ))
    }
}

#[derive(Debug, Default)]
pub struct ScratchpadAppendTool;

#[async_trait]
impl ToolSpec for ScratchpadAppendTool {
    fn name(&self) -> &'static str {
        "scratchpad_append"
    }

    fn description(&self) -> &'static str {
        "Append one validated line to notes.jsonl (auto id, ts). area_id must exist in inventory.json (except kind=meta with area_id=_global)."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "run_id": run_id_property(),
                "line": {
                    "type": "object",
                    "description": "One notes.jsonl row (runtime adds id, ts).",
                    "properties": {
                        "area_id": { "type": "string" },
                        "area": { "type": "string" },
                        "kind": { "type": "string", "enum": ["finding", "todo", "cleared", "meta"] },
                        "severity": { "type": "string" },
                        "title": { "type": "string" },
                        "file": { "type": "string" },
                        "line": { "type": "integer" },
                        "line_end": { "type": "integer" },
                        "claim": { "type": "string" },
                        "evidence": { "type": "string" },
                        "status": { "type": "string" },
                        "source": { "type": "string" },
                        "supersedes": { "type": "string" }
                    },
                    "additionalProperties": false
                }
            },
            "required": ["line"],
            "additionalProperties": false
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::WritesFiles]
    }

    fn approval_requirement(&self) -> ApprovalRequirement {
        ApprovalRequirement::Auto
    }

    async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
        let run_id = resolve_run_id(context, optional_str(&input, "run_id"))?;
        let line = input
            .get("line")
            .cloned()
            .ok_or_else(|| ToolError::missing_field("line"))?;
        let store = ScratchpadStore::open(context, &run_id)?;
        let note = store.append_note(line)?;
        persist_scratchpad_run(context, &run_id);
        let out = json!({
            "id": note.id,
            "path": format!("{}/notes.jsonl", display_run_path(&run_id))
        });
        Ok(ToolResult::success(
            serde_json::to_string_pretty(&out).unwrap_or_default(),
        ))
    }
}

#[derive(Debug, Default)]
pub struct ScratchpadListNotesTool;

#[async_trait]
impl ToolSpec for ScratchpadListNotesTool {
    fn name(&self) -> &'static str {
        "scratchpad_list_notes"
    }

    fn description(&self) -> &'static str {
        "List recent notes.jsonl entries for one area_id (full JSON objects, not summaries)."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "run_id": run_id_property(),
                "area_id": {
                    "type": "string",
                    "description": "Inventory area id to filter on"
                },
                "limit": {
                    "type": "integer",
                    "description": "Max notes to return (default 20)",
                    "minimum": 1,
                    "maximum": 100
                }
            },
            "required": ["area_id"],
            "additionalProperties": false
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::ReadOnly]
    }

    fn approval_requirement(&self) -> ApprovalRequirement {
        ApprovalRequirement::Auto
    }

    async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
        let run_id = resolve_run_id(context, optional_str(&input, "run_id"))?;
        persist_scratchpad_run(context, &run_id);
        let area_id = required_str(&input, "area_id")?;
        let limit = input
            .get("limit")
            .and_then(|v| v.as_u64())
            .unwrap_or(20)
            .clamp(1, 100) as usize;
        let store = ScratchpadStore::open(context, &run_id)?;
        let notes = store.list_notes(area_id, limit)?;
        let out = json!({ "area_id": area_id, "notes": notes });
        Ok(ToolResult::success(
            serde_json::to_string_pretty(&out).unwrap_or_default(),
        ))
    }
}

#[derive(Debug, Default)]
pub struct ScratchpadSetAreaTool;

#[async_trait]
impl ToolSpec for ScratchpadSetAreaTool {
    fn name(&self) -> &'static str {
        "scratchpad_set_area"
    }

    fn description(&self) -> &'static str {
        "Update one inventory area status. status=done defaults require_min_notes=1; status=deferred defaults require_min_notes=0 (still needs kind=meta when require_deferred_meta is enabled)."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "run_id": run_id_property(),
                "area_id": { "type": "string" },
                "status": {
                    "type": "string",
                    "enum": ["in_progress", "done", "deferred", "pending"]
                },
                "notes": {
                    "type": "string",
                    "description": "Optional human remark on the inventory row (not used for gates)"
                },
                "require_min_notes": {
                    "type": "integer",
                    "description": "Minimum notes.jsonl lines for this area_id. Default: 1 for done, 0 for deferred/pending/in_progress",
                    "minimum": 0,
                    "maximum": 50
                }
            },
            "required": ["area_id", "status"],
            "additionalProperties": false
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::WritesFiles]
    }

    fn approval_requirement(&self) -> ApprovalRequirement {
        ApprovalRequirement::Auto
    }

    async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
        let run_id = resolve_run_id(context, optional_str(&input, "run_id"))?;
        let area_id = required_str(&input, "area_id")?;
        let status_str = required_str(&input, "status")?;
        let status = AreaStatus::from_str(status_str).ok_or_else(|| {
            ToolError::invalid_input(format!(
                "invalid status '{status_str}'; use pending|in_progress|done|deferred"
            ))
        })?;
        let remark = optional_str(&input, "notes");
        let require_min = input
            .get("require_min_notes")
            .and_then(|v| v.as_u64())
            .map(|v| v as usize)
            .unwrap_or_else(|| match status {
                AreaStatus::Done => 1,
                _ => 0,
            });
        let store = ScratchpadStore::open(context, &run_id)?;
        let scratchpad_cfg = context
            .runtime
            .wire
            .scratchpad_config
            .clone()
            .unwrap_or_default();
        let inventory =
            store.set_area_status(area_id, status, remark, require_min, &scratchpad_cfg)?;
        persist_scratchpad_run(context, &run_id);
        let areas_done = inventory
            .areas
            .iter()
            .filter(|a| a.status == AreaStatus::Done)
            .count();
        Ok(ToolResult::success(
            serde_json::to_string_pretty(&json!({
                "run_id": run_id,
                "area_id": area_id,
                "status": status.as_str(),
                "areas_done": areas_done,
            }))
            .unwrap_or_default(),
        ))
    }
}

#[derive(Debug, Default)]
pub struct ScratchpadVerifyNoteTool;

#[async_trait]
impl ToolSpec for ScratchpadVerifyNoteTool {
    fn name(&self) -> &'static str {
        "scratchpad_verify_note"
    }

    fn description(&self) -> &'static str {
        "Promote an open scratchpad note to status=verified (append-only supersede). \
         Call only after read_file/grep_files confirms the claim. Required before scratchpad_set_area(done) when open HIGH/BLOCKER findings exist."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "run_id": run_id_property(),
                "note_id": {
                    "type": "string",
                    "description": "notes.jsonl id (e.g. note-012)"
                }
            },
            "required": ["note_id"],
            "additionalProperties": false
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::WritesFiles]
    }

    fn approval_requirement(&self) -> ApprovalRequirement {
        ApprovalRequirement::Auto
    }

    async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
        let run_id = resolve_run_id(context, optional_str(&input, "run_id"))?;
        let note_id = required_str(&input, "note_id")?;
        let store = ScratchpadStore::open(context, &run_id)?;
        let note = verify_note(&store, note_id)?;
        persist_scratchpad_run(context, &run_id);
        Ok(ToolResult::success(
            serde_json::to_string_pretty(&json!({
                "verified_id": note.id,
                "supersedes": note_id,
                "status": note.status,
            }))
            .unwrap_or_default(),
        ))
    }
}