sinter-io 0.44.0

sinter command-line interface
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
//! Workspaces acceptance: federation across
//! member repos, boundary links by import evidence only, declared links
//! carrying their own evidence kind, deterministic output.

use std::path::Path;
use std::process::Command;

fn sinter(cwd: &Path, args: &[&str]) -> (bool, String) {
    let out = Command::new(env!("CARGO_BIN_EXE_sinter"))
        .args(args)
        .env("HOME", cwd)
        .env("USERPROFILE", cwd)
        .current_dir(cwd)
        .output()
        .expect("run sinter");
    (
        out.status.success(),
        format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        ),
    )
}

/// Three-member distributed system: auth and billing both import the
/// shared lib `common` by Go module path; billing also consumes a queue
/// topic that auth publishes (declared link).
fn build_workspace(root: &Path) -> std::path::PathBuf {
    let write = |rel: &str, content: &str| {
        let path = root.join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, content).unwrap();
    };
    write(
        "common/pkg/retry/retry.go",
        "package retry\n\n// Backoff retries an operation with backoff.\nfunc Backoff(attempts int) int {\n\treturn attempts\n}\n",
    );
    write(
        "common/go.mod",
        "module example.com/org/common\n\ngo 1.22\n",
    );
    write(
        "auth/main.go",
        "package main\n\nimport \"example.com/org/common/pkg/retry\"\n\n// Login authenticates with retries.\nfunc Login(user string) int {\n\treturn retry.Backoff(3)\n}\n\n// PublishSettled emits the settled event.\nfunc PublishSettled() {}\n",
    );
    write("auth/go.mod", "module example.com/org/auth\n\ngo 1.22\n");
    write(
        "billing/main.go",
        "package main\n\nimport \"example.com/org/common/pkg/retry\"\n\n// Charge bills a customer with retries.\nfunc Charge(amount int) int {\n\treturn retry.Backoff(amount)\n}\n\n// ConsumeSettled handles the settled event.\nfunc ConsumeSettled() {}\n",
    );
    write(
        "billing/go.mod",
        "module example.com/org/billing\n\ngo 1.22\n",
    );
    write(
        "workspace.toml",
        r#"[workspace]
name = "shop"

[members]
auth = "auth"
billing = "billing"
common = "common"

[[links]]
from_member = "billing"
from_symbol = "ConsumeSettled"
to_member = "auth"
to_symbol = "PublishSettled"
via = "topic payments.settled"
"#,
    );
    root.join("workspace.toml")
}

#[test]
fn workspace_end_to_end() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    let manifest = build_workspace(root);
    let m = manifest.to_str().unwrap();

    // Build members + refresh links in one verb.
    let (ok, out) = sinter(root, &["workspace", m]);
    assert!(ok, "{out}");
    assert!(out.contains("boundary links:"), "{out}");
    // At least: auth->Backoff call, billing->Backoff call, two import
    // edges to the common file/module, one declared link.
    let count: usize = out
        .lines()
        .find_map(|l| l.strip_prefix("boundary links: "))
        .unwrap()
        .trim()
        .parse()
        .unwrap();
    assert!(
        count >= 4,
        "expected >=4 boundary links, got {count}:\n{out}"
    );

    // Cross-repo blast radius: who depends on common's Backoff?
    let (ok, out) = sinter(root, &["affected", "Backoff", "--workspace", m]);
    assert!(ok, "{out}");
    assert!(out.contains("auth:Login"), "{out}");
    assert!(out.contains("billing:Charge"), "{out}");
    assert!(out.contains("import"), "{out}");

    // Declared link: PublishSettled's dependents include billing's
    // consumer, tagged with declared evidence; filtering to import-only
    // evidence excludes it.
    let (ok, out) = sinter(root, &["affected", "PublishSettled", "--workspace", m]);
    assert!(ok, "{out}");
    assert!(out.contains("billing:ConsumeSettled"), "{out}");
    assert!(out.contains("declared"), "{out}");
    let (ok, out) = sinter(
        root,
        &[
            "affected",
            "PublishSettled",
            "--workspace",
            m,
            "--evidence",
            "import",
        ],
    );
    // Filtered to nothing: grep-style exit 1.
    assert!(!ok, "{out}");
    assert!(
        !out.contains("ConsumeSettled"),
        "declared link not filterable:\n{out}"
    );
    // Relation filter crosses the boundary too: the declared link is
    // `uses`, so restricting traversal to `calls` drops it.
    let (ok, out) = sinter(
        root,
        &[
            "affected",
            "PublishSettled",
            "--workspace",
            m,
            "--relations",
            "calls",
        ],
    );
    assert!(!ok, "{out}");
    assert!(
        !out.contains("ConsumeSettled"),
        "declared link not relation-filterable:\n{out}"
    );

    // Cross-repo path: billing's Charge reaches common's Backoff.
    let (ok, out) = sinter(
        root,
        &["path", "billing:Charge", "common:Backoff", "--workspace", m],
    );
    assert!(ok, "{out}");
    assert!(out.contains("-[calls/import]->"), "{out}");
    assert!(out.contains("common:Backoff"), "{out}");

    // Fan-out ask finds the shared symbol with member attribution.
    let (ok, out) = sinter(root, &["ask", "retry backoff", "--workspace", m]);
    assert!(ok, "{out}");
    let first = out.lines().find(|l| l.starts_with("1. ")).unwrap();
    assert!(first.contains("common:"), "{out}");
    assert!(first.contains("Backoff"), "{out}");

    // Determinism: byte-identical across runs.
    let (_, again) = sinter(root, &["affected", "Backoff", "--workspace", m]);
    let (_, first_run) = sinter(root, &["affected", "Backoff", "--workspace", m]);
    assert_eq!(again, first_run, "workspace traversal not deterministic");
}

#[test]
fn workspace_impact_crosses_members() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    let manifest = build_workspace(root);
    let m = manifest.to_str().unwrap();
    let common = root.join("common");

    // common is a git repo with one committed baseline, then a change to
    // Backoff.
    let git = |args: &[&str]| {
        assert!(
            Command::new("git")
                .args(args)
                .current_dir(&common)
                .env("GIT_AUTHOR_NAME", "t")
                .env("GIT_AUTHOR_EMAIL", "t@t")
                .env("GIT_COMMITTER_NAME", "t")
                .env("GIT_COMMITTER_EMAIL", "t@t")
                .output()
                .unwrap()
                .status
                .success()
        );
    };
    git(&["init", "-q"]);
    git(&["add", "."]);
    git(&["commit", "-qm", "base"]);
    std::fs::write(
        common.join("pkg/retry/retry.go"),
        "package retry\n\n// Backoff retries an operation with backoff.\nfunc Backoff(attempts int) int {\n\treturn attempts * 2\n}\n",
    )
    .unwrap();
    git(&["add", "."]);
    git(&["commit", "-qm", "change backoff"]);

    let (ok, out) = sinter(root, &["workspace", m]);
    assert!(ok, "{out}");
    let (ok, out) = sinter(
        root,
        &[
            "impact",
            "HEAD~1..HEAD",
            "--repo",
            common.to_str().unwrap(),
            "--workspace",
            m,
        ],
    );
    assert!(ok, "{out}");
    assert!(out.contains("Backoff"), "{out}");
    assert!(
        out.contains("auth:"),
        "cross-member radius missing auth:\n{out}"
    );
    assert!(
        out.contains("billing:"),
        "cross-member radius missing billing:\n{out}"
    );

    // Same answer over MCP: the workspace impact tool names the member.
    use std::io::Write;
    let mut child = Command::new(env!("CARGO_BIN_EXE_sinter"))
        .args(["serve", "--workspace", m])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn()
        .expect("spawn serve");
    writeln!(
        child.stdin.as_mut().unwrap(),
        r#"{{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{{"name":"impact","arguments":{{"member":"common","rev_range":"HEAD~1..HEAD"}}}}}}"#
    )
    .unwrap();
    drop(child.stdin.take());
    let output = child.wait_with_output().unwrap();
    let text = String::from_utf8_lossy(&output.stdout);
    let response: serde_json::Value = serde_json::from_str(text.lines().next().unwrap()).unwrap();
    let body = response["result"]["content"][0]["text"].as_str().unwrap();
    let parsed: serde_json::Value = serde_json::from_str(body).unwrap();
    assert!(
        parsed["changed_symbols"]
            .as_array()
            .unwrap()
            .iter()
            .any(|s| s["qualified"].as_str().unwrap().contains("Backoff")),
        "{body}"
    );
    let radius = parsed["blast_radius"].as_array().unwrap();
    assert!(
        radius
            .iter()
            .any(|s| s["file"].as_str().unwrap().starts_with("auth:")),
        "cross-member radius missing auth over MCP: {body}"
    );
    assert!(
        radius
            .iter()
            .any(|s| s["file"].as_str().unwrap().starts_with("billing:")),
        "cross-member radius missing billing over MCP: {body}"
    );
}

#[test]
fn init_workspace_scaffolds_without_clobber() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    let (ok, out) = sinter(root, &["init", "--workspace", "--name", "shop"]);
    assert!(ok, "{out}");
    let manifest = std::fs::read_to_string(root.join("ws.toml")).unwrap();
    assert!(manifest.contains("name = \"shop\""), "{manifest}");
    // Template must parse as a valid (empty) workspace as written.
    let (ok, out) = sinter(root, &["workspace", "ws.toml"]);
    assert!(ok, "{out}");
    // Second run refuses to overwrite.
    let (ok, out) = sinter(root, &["init", "--workspace"]);
    assert!(!ok, "{out}");
    assert!(out.contains("refusing to overwrite"), "{out}");
    assert!(manifest == std::fs::read_to_string(root.join("ws.toml")).unwrap());
}

#[test]
fn workspace_stale_and_declared_errors() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    let manifest = build_workspace(root);
    let m = manifest.to_str().unwrap();
    let (ok, out) = sinter(root, &["workspace", m]);
    assert!(ok, "{out}");

    // A bogus declared symbol fails loudly, never guesses.
    let bad = std::fs::read_to_string(&manifest)
        .unwrap()
        .replace("PublishSettled", "NoSuchSymbol");
    std::fs::write(root.join("workspace.toml"), bad).unwrap();
    let (ok, out) = sinter(root, &["workspace", m]);
    assert!(!ok, "{out}");
    assert!(out.contains("NoSuchSymbol"), "{out}");
}

/// Workspace traversal has no JSON renderer; `--json --workspace` must
/// refuse loudly (usage error, exit 2) instead of silently dropping the
/// flag.
#[test]
fn json_conflicts_with_workspace() {
    for argv in [
        vec!["ask", "anything", "--workspace", "ws.toml", "--json"],
        vec!["affected", "Backoff", "--workspace", "ws.toml", "--json"],
        vec!["path", "A", "B", "--workspace", "ws.toml", "--json"],
    ] {
        let out = Command::new(env!("CARGO_BIN_EXE_sinter"))
            .args(&argv)
            .output()
            .expect("run sinter");
        assert_eq!(
            out.status.code(),
            Some(2),
            "{argv:?} should be a usage error: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(
            String::from_utf8_lossy(&out.stderr).contains("--workspace"),
            "{argv:?} error should name the conflict"
        );
    }
}

/// Parallel workspace queries share the link store; opens must ride out
/// contention instead of failing with DatabaseAlreadyOpen.
#[test]
fn parallel_workspace_queries_all_succeed() {
    let root = tempfile::tempdir().unwrap();
    let manifest = build_workspace(root.path());
    let (ok, out) = sinter(root.path(), &["workspace", manifest.to_str().unwrap()]);
    assert!(ok, "{out}");
    let threads: Vec<_> = (0..8)
        .map(|_| {
            let manifest = manifest.clone();
            std::thread::spawn(move || {
                Command::new(env!("CARGO_BIN_EXE_sinter"))
                    .args([
                        "affected",
                        "common:Backoff",
                        "--workspace",
                        manifest.to_str().unwrap(),
                    ])
                    .output()
                    .expect("run sinter")
            })
        })
        .collect();
    for t in threads {
        let out = t.join().unwrap();
        assert!(
            out.status.success(),
            "workspace query failed under contention: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }
}

/// Workspace scope over MCP: one server spans the members, tools/list is
/// the honest cross-repo surface, and affected crosses repositories.
#[test]
fn serve_workspace_answers_across_members() {
    use std::io::Write;
    let root = tempfile::tempdir().unwrap();
    let manifest = build_workspace(root.path());
    let (ok, out) = sinter(root.path(), &["workspace", manifest.to_str().unwrap()]);
    assert!(ok, "{out}");

    let mut child = Command::new(env!("CARGO_BIN_EXE_sinter"))
        .args(["serve", "--workspace", manifest.to_str().unwrap()])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn()
        .expect("spawn serve");
    {
        let stdin = child.stdin.as_mut().unwrap();
        writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"tools/list"}}"#).unwrap();
        writeln!(
            stdin,
            r#"{{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{{"name":"affected","arguments":{{"symbol":"common:Backoff"}}}}}}"#
        )
        .unwrap();
        writeln!(
            stdin,
            r#"{{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{{"name":"ask","arguments":{{"question":"retry backoff"}}}}}}"#
        )
        .unwrap();
        writeln!(
            stdin,
            r#"{{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{{"name":"show","arguments":{{"symbol":"common:Backoff"}}}}}}"#
        )
        .unwrap();
        writeln!(
            stdin,
            r#"{{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{{"name":"unresolved","arguments":{{"limit":5}}}}}}"#
        )
        .unwrap();
    }
    drop(child.stdin.take());
    let output = child.wait_with_output().unwrap();
    let text = String::from_utf8_lossy(&output.stdout);
    let mut lines = text.lines();

    let tools: serde_json::Value = serde_json::from_str(lines.next().unwrap()).unwrap();
    let names: Vec<&str> = tools["result"]["tools"]
        .as_array()
        .unwrap()
        .iter()
        .map(|t| t["name"].as_str().unwrap())
        .collect();
    assert_eq!(
        names,
        [
            "ask",
            "show",
            "query",
            "affected",
            "path",
            "unresolved",
            "impact"
        ],
        "honest ws surface"
    );

    let affected: serde_json::Value = serde_json::from_str(lines.next().unwrap()).unwrap();
    let body = affected["result"]["content"][0]["text"].as_str().unwrap();
    let parsed: serde_json::Value = serde_json::from_str(body).unwrap();
    assert_eq!(parsed["symbol"]["member"], "common", "{body}");
    assert!(parsed["total"].as_u64().unwrap() >= 1, "{body}");
    let deps = parsed["dependents"].as_array().unwrap();
    assert!(
        deps.iter().any(|d| {
            let s = d["s"].as_str().unwrap();
            s.starts_with("auth:") || s.starts_with("billing:")
        }),
        "terse dependents must cross into other members: {body}"
    );

    // ask fans out across members; top hit carries member attribution.
    let ask: serde_json::Value = serde_json::from_str(lines.next().unwrap()).unwrap();
    let body = ask["result"]["content"][0]["text"].as_str().unwrap();
    let parsed: serde_json::Value = serde_json::from_str(body).unwrap();
    let first = &parsed["hits"].as_array().unwrap()[0];
    assert_eq!(first["member"], "common", "{body}");
    assert_eq!(first["name"], "Backoff", "{body}");

    // show carries in-member edges plus boundary links from other members.
    let show: serde_json::Value = serde_json::from_str(lines.next().unwrap()).unwrap();
    let body = show["result"]["content"][0]["text"].as_str().unwrap();
    let parsed: serde_json::Value = serde_json::from_str(body).unwrap();
    assert_eq!(parsed["symbol"]["member"], "common", "{body}");
    let boundary_in = parsed["boundary_incoming"].as_array().unwrap();
    assert!(
        boundary_in.iter().any(|l| {
            let m = l["member"].as_str().unwrap();
            m == "auth" || m == "billing"
        }),
        "boundary links must name the other members: {body}"
    );

    // unresolved spans members; every entry is tagged with its member.
    let unresolved: serde_json::Value = serde_json::from_str(lines.next().unwrap()).unwrap();
    let body = unresolved["result"]["content"][0]["text"].as_str().unwrap();
    let parsed: serde_json::Value = serde_json::from_str(body).unwrap();
    assert!(parsed["total"].is_u64(), "{body}");
    for e in parsed["unresolved"].as_array().unwrap() {
        let member = e["member"].as_str().unwrap();
        assert!(
            e["file"]
                .as_str()
                .unwrap()
                .starts_with(&format!("{member}:")),
            "{body}"
        );
    }
}