perspt-sdk 0.6.6

Domain-neutral SRBN agent SDK for Perspt: residual energy, measured acceptance gate, spectral diagnostics, and stabilization-kernel adapter (PSP-8)
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! The base tool catalog (PSP-9 system 5).
//!
//! Domain-neutral entries mapping onto the `EffectKind` variants PSP-8
//! declares. `sed_replace` and `awk_filter` are deliberately absent: their
//! argument contracts lack the exact-match and state-witness preconditions
//! governed mutation requires, and `edit_file` / `apply_diff` cover their
//! uses. They are removed rather than retained through an internal bypass,
//! because this PSP preserves no unmediated effect path.

use super::entry::{ToolEntry, ToolOrigin};
use super::footprint::{AccessMode, FootprintSpec, ResourceSelector};
use crate::capability::{EffectKind, RiskClass};

/// Shorthand: an object schema from `(name, type, description, required)`.
fn schema(fields: &[(&str, &str, &str, bool)]) -> serde_json::Value {
    let mut properties = serde_json::Map::new();
    let mut required = Vec::new();
    for (name, kind, description, is_required) in fields {
        properties.insert(
            (*name).to_string(),
            serde_json::json!({"type": kind, "description": description}),
        );
        if *is_required {
            required.push(serde_json::Value::String((*name).to_string()));
        }
    }
    serde_json::json!({
        "type": "object",
        "properties": properties,
        "required": required,
        "additionalProperties": false,
    })
}

fn path_read() -> FootprintSpec {
    FootprintSpec::new(vec![ResourceSelector::PathArgument {
        field: "path".into(),
        access: AccessMode::Read,
    }])
}

fn path_write() -> FootprintSpec {
    FootprintSpec::new(vec![ResourceSelector::PathArgument {
        field: "path".into(),
        access: AccessMode::Write,
    }])
}

fn entry(
    name: &str,
    description: &str,
    effect: EffectKind,
    risk: RiskClass,
    arg_schema: serde_json::Value,
    footprint: FootprintSpec,
    durable: bool,
) -> ToolEntry {
    ToolEntry {
        name: name.into(),
        description: description.into(),
        discovery_summary: String::new(),
        description_templates: None,
        effect,
        risk,
        schema: arg_schema,
        footprint,
        proposal_bindings: Vec::new(),
        durable,
        origin: ToolOrigin::Builtin,
        hot: false,
    }
}

/// Host-side tool-surface entries (deferred discovery and composition).
fn surface_entries() -> Vec<ToolEntry> {
    vec![
        entry(
            "tool_search",
            "Find governed tools by capability, name, and description; matching \
             schemas become available on the next turn",
            EffectKind::ToolSearch,
            RiskClass::Low,
            schema(&[
                ("query", "string", "Capability or operation to find", true),
                ("limit", "integer", "Maximum matches, from 1 to 12", false),
            ]),
            FootprintSpec::default(),
            false,
        )
        .hot(),
        entry(
            "tool_program",
            "Run a bounded pure Starlark program that returns nested tool \
             proposals; each nested call is mediated separately",
            EffectKind::ToolProgram,
            RiskClass::Low,
            schema(&[(
                "source",
                "string",
                "Starlark whose final expression is main and whose main() returns call JSON",
                true,
            )]),
            FootprintSpec::default(),
            false,
        )
        .hot(),
    ]
    .into_iter()
    .chain(recall_entries())
    .collect()
}

/// Host-side retrieval of evicted context and stored artifacts.
fn recall_entries() -> Vec<ToolEntry> {
    vec![
        entry(
            "context_recall",
            "Restore evicted context pages by page id (from an eviction note \
             or the page index), by path, or by typed diagnostic/test key; \
             returns the pages' original content",
            EffectKind::DataRead,
            RiskClass::Low,
            schema(&[
                (
                    "page_id",
                    "string",
                    "Content-addressed page id or its 16-hex prefix",
                    false,
                ),
                ("path", "string", "A path a tool call named", false),
                ("diagnostic_id", "string", "A typed diagnostic id", false),
                ("test_id", "string", "A typed test id", false),
                ("symbol", "string", "A typed symbol name", false),
                (
                    "provenance_key",
                    "string",
                    "A provenance key (the page's content address)",
                    false,
                ),
            ]),
            FootprintSpec::opaque(),
            false,
        )
        .hot(),
        entry(
            "read_artifact",
            "Read a window of a stored artifact by the artifact:<handle> shown in a \
             truncated-output note; returns bytes offset..offset+limit with a \
             continuation hint",
            EffectKind::DataRead,
            RiskClass::Low,
            schema(&[
                (
                    "handle",
                    "string",
                    "The content handle from a [full output: artifact:…] note",
                    true,
                ),
                (
                    "offset",
                    "integer",
                    "0-based byte offset (default 0)",
                    false,
                ),
                ("limit", "integer", "Bytes to return, capped at 7168", false),
            ]),
            FootprintSpec::opaque(),
            false,
        )
        .hot(),
    ]
}

/// The read-only half of the base catalog.
fn read_entries() -> Vec<ToolEntry> {
    let mut entries = surface_entries();
    entries.extend([
        entry(
            "read_file",
            "Read a file's contents with optional offset/limit windows; returns line-numbered text",
            EffectKind::ReadFile,
            RiskClass::Low,
            schema(&[
                ("path", "string", "Workspace-relative file path", true),
                ("offset", "integer", "1-based first line to read", false),
                (
                    "limit",
                    "integer",
                    "Maximum number of lines (capped at 2000)",
                    false,
                ),
            ]),
            path_read(),
            false,
        )
        .hot(),
        entry(
            "list_files",
            "List files in a directory, respecting ignore files",
            EffectKind::List,
            RiskClass::Low,
            schema(&[
                (
                    "path",
                    "string",
                    "Directory to list (default workspace root)",
                    false,
                ),
                ("offset", "integer", "0-based entry to continue from", false),
                ("limit", "integer", "Maximum entries to return", false),
            ]),
            path_read(),
            false,
        ),
    ]);
    entries.extend(search_read_entries());
    entries
}

/// The pattern-search half of the read catalog.
fn search_read_entries() -> Vec<ToolEntry> {
    vec![
        entry(
            "glob",
            "Match files by glob pattern, sorted by modification time",
            EffectKind::Search,
            RiskClass::Low,
            schema(&[
                ("pattern", "string", "Glob pattern, e.g. src/**/*.rs", true),
                ("offset", "integer", "0-based match to continue from", false),
                ("limit", "integer", "Maximum matches to return", false),
            ]),
            FootprintSpec::default(),
            false,
        )
        .hot(),
        entry(
            "grep",
            "Search file contents by regex with optional path filter and context lines",
            EffectKind::Search,
            RiskClass::Low,
            schema(&[
                ("query", "string", "Regex to search for", true),
                ("path", "string", "Directory or file to search in", false),
                (
                    "context",
                    "integer",
                    "Context lines around each match",
                    false,
                ),
            ]),
            path_read(),
            false,
        )
        .hot(),
    ]
}

/// Language-intelligence read entries.
fn intel_entries() -> Vec<ToolEntry> {
    vec![entry(
        "lsp_query",
        "Query language intelligence: definitions, references, hover, diagnostics",
        EffectKind::LspQuery,
        RiskClass::Low,
        schema(&[
            (
                "kind",
                "string",
                "definition | references | hover | diagnostics",
                true,
            ),
            ("path", "string", "File the query targets", true),
            ("symbol", "string", "Symbol name, when applicable", false),
        ]),
        path_read(),
        false,
    )]
}

/// Repository and escalation entries.
fn context_entries() -> Vec<ToolEntry> {
    vec![
        entry(
            "git_read",
            "Read repository state: status, diff, log, show",
            EffectKind::GitRead,
            RiskClass::Low,
            schema(&[
                ("subcommand", "string", "status | diff | log | show", true),
                ("args", "string", "Additional read-only arguments", false),
            ]),
            FootprintSpec::default(),
            false,
        ),
        entry(
            "ask_user",
            "Escalate to the user for approval, a capability grant, or a decision",
            EffectKind::AskUser,
            RiskClass::Low,
            schema(&[("question", "string", "The question or request", true)]),
            FootprintSpec::default(),
            false,
        )
        .hot(),
    ]
}

/// The mutating half of the base catalog.
fn write_entries() -> Vec<ToolEntry> {
    vec![
        entry(
            "write_file",
            "Create or replace a whole file",
            EffectKind::WriteArtifact,
            RiskClass::Medium,
            schema(&[
                ("path", "string", "Workspace-relative file path", true),
                ("content", "string", "Complete new file contents", true),
            ]),
            path_write(),
            false,
        ),
        entry(
            "edit_file",
            "Exact-string replace with a uniqueness check; fails closed on ambiguity",
            EffectKind::ApplyPatch,
            RiskClass::Medium,
            schema(&[
                ("path", "string", "File to edit", true),
                (
                    "old_string",
                    "string",
                    "Exact text to replace (must be unique)",
                    true,
                ),
                ("new_string", "string", "Replacement text", true),
            ]),
            path_write(),
            false,
        )
        .hot(),
        entry(
            "apply_diff",
            "Apply a unified diff to a file",
            EffectKind::ApplyPatch,
            RiskClass::Medium,
            schema(&[
                ("path", "string", "File to patch", true),
                ("diff", "string", "Unified diff content", true),
            ]),
            path_write(),
            false,
        )
        .hot(),
    ]
}

/// File relocation entries.
fn relocation_entries() -> Vec<ToolEntry> {
    vec![
        entry(
            "move_file",
            "Move or rename a file",
            EffectKind::MoveFile,
            RiskClass::Medium,
            schema(&[
                ("path", "string", "Source path", true),
                ("to", "string", "Destination path", true),
            ]),
            FootprintSpec::new(vec![
                ResourceSelector::PathArgument {
                    field: "path".into(),
                    access: AccessMode::Write,
                },
                ResourceSelector::PathArgument {
                    field: "to".into(),
                    access: AccessMode::Write,
                },
            ]),
            false,
        ),
        entry(
            "delete_file",
            "Delete a file",
            EffectKind::DeleteFile,
            RiskClass::Medium,
            schema(&[("path", "string", "File to delete", true)]),
            path_write(),
            false,
        ),
    ]
}

/// Verifier and command entries; footprints are opaque because their touched
/// state depends on the workspace, so they serialize rather than race.
fn command_entries() -> Vec<ToolEntry> {
    vec![
        entry(
            "exec",
            "Run one shell-free, read-only OS program in the workspace sandbox; \
             use rg, git diff/status/log/show, awk, sed -n, or coreutils. For \
             tests use run_test, for builds run_build, for formatting \
             run_formatter — exec denies them",
            EffectKind::Search,
            RiskClass::Low,
            schema(&[(
                "command",
                "string",
                "One direct program invocation; pipes, redirects, expansion, and \
                 mutation commands are denied",
                true,
            )]),
            FootprintSpec::opaque(),
            false,
        )
        .hot(),
        entry(
            "run_test",
            "Run the domain's declared test command; output is parsed into residuals",
            EffectKind::RunTest,
            RiskClass::Medium,
            schema(&[("filter", "string", "Optional test name filter", false)]),
            FootprintSpec::opaque(),
            false,
        )
        .hot(),
        entry(
            "run_build",
            "Run the domain's declared build command",
            EffectKind::RunBuild,
            RiskClass::Medium,
            schema(&[]),
            FootprintSpec::opaque(),
            false,
        )
        .hot(),
        entry(
            "run_formatter",
            "Run the domain's declared formatter",
            EffectKind::RunFormatter,
            RiskClass::Medium,
            schema(&[]),
            FootprintSpec::opaque(),
            false,
        )
        .hot(),
        entry(
            "run_repo_script",
            "Run a script declared in the project profile",
            EffectKind::RunRepoScript,
            RiskClass::Medium,
            schema(&[("name", "string", "Declared script name", true)]),
            FootprintSpec::opaque(),
            false,
        ),
        dependency_entry(),
    ]
}

/// The governed dependency-mutation entry (Gate J).
fn dependency_entry() -> ToolEntry {
    entry(
        "mutate_dependencies",
        "Add, remove, or update dependencies via the domain package manager",
        EffectKind::MutateDependencies,
        RiskClass::High,
        serde_json::json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "description": "add | remove | update"
                },
                "packages": {
                    "type": "array",
                    "description": "Package names (optionally versioned)",
                    "items": {"type": "string"},
                    "maxItems": 16
                },
                "dev": {
                    "type": "boolean",
                    "description": "Add as a development dependency"
                }
            },
            "required": ["action", "packages"],
            "additionalProperties": false
        }),
        FootprintSpec::new(vec![
            ResourceSelector::Literal {
                resource: crate::scheduler::Resource::Manifest("workspace".into()),
                access: AccessMode::Write,
            },
            ResourceSelector::Literal {
                resource: crate::scheduler::Resource::Lockfile("workspace".into()),
                access: AccessMode::Write,
            },
            ResourceSelector::Literal {
                resource: crate::scheduler::Resource::Toolchain("workspace".into()),
                access: AccessMode::Read,
            },
        ]),
        true,
    )
}

/// High-risk command and network entries.
fn high_risk_entries() -> Vec<ToolEntry> {
    vec![
        entry(
            "run_shell",
            "Run a shell command; requires an explicit RunShell capability",
            EffectKind::RunShell,
            RiskClass::High,
            schema(&[("command", "string", "The command line", true)]),
            FootprintSpec::opaque(),
            true,
        ),
        entry(
            "git_write",
            "Stage and commit; never push or hard-reset by default",
            EffectKind::GitWrite,
            RiskClass::High,
            schema(&[
                ("subcommand", "string", "add | commit", true),
                ("args", "string", "Arguments", false),
            ]),
            FootprintSpec::opaque(),
            true,
        ),
        entry(
            "fetch_url",
            "Fetch a URL; defaults to ask, domain allow-lists permitted",
            EffectKind::NetworkFetch,
            RiskClass::High,
            schema(&[("url", "string", "The URL to fetch", true)]),
            FootprintSpec::opaque(),
            true,
        ),
    ]
}

/// Privileged and delegation entries.
fn privileged_entries() -> Vec<ToolEntry> {
    vec![
        entry(
            "update_graph",
            "Split, add, or retire work-graph nodes under PSP-8 revision rules",
            EffectKind::UpdateGraph,
            RiskClass::Critical,
            schema(&[(
                "revision",
                "string",
                "Serialized graph revision request",
                true,
            )]),
            FootprintSpec::new(vec![ResourceSelector::Literal {
                resource: crate::scheduler::Resource::WorkGraph,
                access: AccessMode::Write,
            }]),
            true,
        ),
        entry(
            "spawn_agent",
            "Delegate to a child agent; the child capability MUST attenuate (Theorem 1)",
            EffectKind::SpawnAgent,
            RiskClass::Critical,
            schema(&[
                ("role", "string", "explorer | worker | reviewer", true),
                ("goal", "string", "The child's goal", true),
            ]),
            FootprintSpec::opaque(),
            true,
        ),
    ]
}

/// Every builtin entry.
pub fn base_entries() -> Vec<ToolEntry> {
    let mut entries = read_entries();
    entries.extend(intel_entries());
    entries.extend(context_entries());
    entries.extend(write_entries());
    entries.extend(relocation_entries());
    entries.extend(command_entries());
    entries.extend(high_risk_entries());
    entries.extend(privileged_entries());
    entries
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_base_entry_validates_at_assembly() {
        for entry in base_entries() {
            entry
                .validate()
                .unwrap_or_else(|e| panic!("{}: {e}", entry.name));
        }
    }

    #[test]
    fn the_governed_catalog_omits_sed_and_awk() {
        let names: Vec<String> = base_entries().into_iter().map(|e| e.name).collect();
        assert!(!names.contains(&"sed_replace".to_string()));
        assert!(!names.contains(&"awk_filter".to_string()));
        assert!(names.contains(&"edit_file".to_string()));
    }

    #[test]
    fn privileged_effects_are_critical_risk() {
        for entry in base_entries() {
            if entry.effect.is_privileged() {
                assert_eq!(entry.risk, RiskClass::Critical, "{}", entry.name);
            }
        }
    }

    #[test]
    fn read_only_entries_never_mark_durable() {
        for entry in base_entries() {
            if entry.effect.is_read_only() {
                assert!(!entry.durable, "{}", entry.name);
            }
        }
    }
}