tandem-server 0.6.5

HTTP server for Tandem engine APIs
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
#[tokio::test]
async fn memory_promote_blocks_rejected_source_outcome() {
    let state = test_state().await;
    let app = app_router(state.clone());
    let mut rx = state.event_bus.subscribe();

    let capability = json!({
        "run_id": "run-3-rejected",
        "subject": "reviewer-user",
        "org_id": "org-1",
        "workspace_id": "ws-1",
        "project_id": "proj-1",
        "memory": {
            "read_tiers": ["session", "project"],
            "write_tiers": ["session"],
            "promote_targets": ["project"],
            "require_review_for_promote": false,
            "allow_auto_use_tiers": ["curated"]
        },
        "expires_at": 9999999999999u64
    });

    let put_req = Request::builder()
        .method("POST")
        .uri("/memory/put")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "run_id": "run-3-rejected",
                "partition": {
                    "org_id": "org-1",
                    "workspace_id": "ws-1",
                    "project_id": "proj-1",
                    "tier": "session"
                },
                "kind": "fact",
                "content": "rejected outcome must not become reusable memory",
                "artifact_refs": ["artifact://run-3-rejected/output.json"],
                "classification": "internal",
                "metadata": {
                    "source_outcome": {
                        "status": "rejected",
                        "approved": false,
                        "source_run_id": "run-3-rejected",
                        "approval_id": "appr-denied"
                    }
                },
                "capability": capability
            })
            .to_string(),
        ))
        .expect("put request");
    let put_resp = app.clone().oneshot(put_req).await.expect("put response");
    assert_eq!(put_resp.status(), StatusCode::OK);
    let put_body = to_bytes(put_resp.into_body(), usize::MAX)
        .await
        .expect("put body");
    let put_payload: Value = serde_json::from_slice(&put_body).expect("put json");
    let memory_id = put_payload
        .get("id")
        .and_then(Value::as_str)
        .expect("memory id")
        .to_string();
    let _ = next_event_of_type(&mut rx, "memory.put").await;
    let _ = next_event_of_type(&mut rx, "memory.updated").await;

    let promote_req = Request::builder()
        .method("POST")
        .uri("/memory/promote")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "run_id": "run-3-rejected",
                "source_memory_id": memory_id,
                "from_tier": "session",
                "to_tier": "project",
                "partition": {
                    "org_id": "org-1",
                    "workspace_id": "ws-1",
                    "project_id": "proj-1",
                    "tier": "session"
                },
                "reason": "try rejected source",
                "review": {
                    "required": false
                },
                "source_outcome": {
                    "status": "approved",
                    "approved": true
                },
                "capability": capability
            })
            .to_string(),
        ))
        .expect("promote request");
    let promote_resp = app
        .clone()
        .oneshot(promote_req)
        .await
        .expect("promote response");
    assert_eq!(promote_resp.status(), StatusCode::OK);
    let promote_body = to_bytes(promote_resp.into_body(), usize::MAX)
        .await
        .expect("promote body");
    let promote_payload: Value = serde_json::from_slice(&promote_body).expect("promote json");
    assert_eq!(
        promote_payload.get("promoted").and_then(Value::as_bool),
        Some(false)
    );
    let promote_policy_decision_id = promote_payload
        .get("policy_decision_id")
        .and_then(Value::as_str)
        .expect("blocked promote policy decision id")
        .to_string();
    let policy_record = state
        .get_policy_decision(&promote_policy_decision_id)
        .await
        .expect("blocked promote policy decision");
    assert_eq!(
        policy_record.decision,
        tandem_types::PolicyDecisionEffect::Deny
    );
    assert_eq!(policy_record.reason_code, "source_outcome_not_approved");

    let promote_event = next_event_of_type(&mut rx, "memory.promote").await;
    assert_eq!(
        promote_event
            .properties
            .get("status")
            .and_then(Value::as_str),
        Some("blocked")
    );
    assert_eq!(
        promote_event
            .properties
            .get("policyDecisionID")
            .and_then(Value::as_str),
        Some(promote_policy_decision_id.as_str())
    );
    assert!(promote_event
        .properties
        .get("detail")
        .and_then(Value::as_str)
        .is_some_and(|detail| detail.contains("source outcome not approved")));

    let search_req = Request::builder()
        .method("POST")
        .uri("/memory/search")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "run_id": "run-3-rejected",
                "query": "rejected outcome reusable memory",
                "read_scopes": ["project"],
                "partition": {
                    "org_id": "org-1",
                    "workspace_id": "ws-1",
                    "project_id": "proj-1",
                    "tier": "project"
                },
                "capability": capability,
                "limit": 5
            })
            .to_string(),
        ))
        .expect("search request");
    let search_resp = app
        .clone()
        .oneshot(search_req)
        .await
        .expect("search response");
    assert_eq!(search_resp.status(), StatusCode::OK);
    let search_body = to_bytes(search_resp.into_body(), usize::MAX)
        .await
        .expect("search body");
    let search_payload: Value = serde_json::from_slice(&search_body).expect("search json");
    assert_eq!(
        search_payload
            .get("results")
            .and_then(Value::as_array)
            .map(Vec::len),
        Some(0)
    );
}

#[tokio::test]
async fn memory_promote_enterprise_policy_override_blocks_local_allow() {
    let state = test_state().await;
    let app = app_router(state.clone());
    let mut rx = state.event_bus.subscribe();

    state.enterprise.policy_rules.write().await.insert(
        "enterprise-memory-promote-deny".to_string(),
        tandem_enterprise_contract::EnterprisePolicyRule::new(
            "enterprise-memory-promote-deny",
            "enterprise-memory-floor",
            tandem_enterprise_contract::EnterprisePolicyScopeLevel::Enterprise,
            tandem_enterprise_contract::EnterprisePolicyEffect::Deny,
        )
        .with_tool_patterns(vec!["memory.promote".to_string()])
        .with_reason(
            "enterprise_memory_promote_floor",
            "enterprise policy denies memory promotion",
        ),
    );

    let capability = json!({
        "run_id": "run-3-enterprise-deny",
        "subject": "reviewer-user",
        "org_id": "org-1",
        "workspace_id": "ws-1",
        "project_id": "proj-1",
        "memory": {
            "read_tiers": ["session", "project"],
            "write_tiers": ["session"],
            "promote_targets": ["project"],
            "require_review_for_promote": false,
            "allow_auto_use_tiers": ["curated"]
        },
        "expires_at": 9999999999999u64
    });

    let put_req = Request::builder()
        .method("POST")
        .uri("/memory/put")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "run_id": "run-3-enterprise-deny",
                "partition": {
                    "org_id": "org-1",
                    "workspace_id": "ws-1",
                    "project_id": "proj-1",
                    "tier": "session"
                },
                "kind": "fact",
                "content": "enterprise denied memory promotion should stay private",
                "classification": "internal",
                "capability": capability
            })
            .to_string(),
        ))
        .expect("put request");
    let put_resp = app.clone().oneshot(put_req).await.expect("put response");
    assert_eq!(put_resp.status(), StatusCode::OK);
    let put_body = to_bytes(put_resp.into_body(), usize::MAX)
        .await
        .expect("put body");
    let put_payload: Value = serde_json::from_slice(&put_body).expect("put json");
    let memory_id = put_payload
        .get("id")
        .and_then(Value::as_str)
        .expect("memory id")
        .to_string();
    let _ = next_event_of_type(&mut rx, "memory.put").await;
    let _ = next_event_of_type(&mut rx, "memory.updated").await;

    let promote_req = Request::builder()
        .method("POST")
        .uri("/memory/promote")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "run_id": "run-3-enterprise-deny",
                "source_memory_id": memory_id,
                "from_tier": "session",
                "to_tier": "project",
                "partition": {
                    "org_id": "org-1",
                    "workspace_id": "ws-1",
                    "project_id": "proj-1",
                    "tier": "session"
                },
                "reason": "enterprise override test",
                "review": {
                    "required": false
                },
                "source_outcome": {
                    "status": "approved",
                    "approved": true
                },
                "capability": capability
            })
            .to_string(),
        ))
        .expect("promote request");
    let promote_resp = app
        .clone()
        .oneshot(promote_req)
        .await
        .expect("promote response");
    assert_eq!(promote_resp.status(), StatusCode::OK);
    let promote_body = to_bytes(promote_resp.into_body(), usize::MAX)
        .await
        .expect("promote body");
    let promote_payload: Value = serde_json::from_slice(&promote_body).expect("promote json");
    assert_eq!(
        promote_payload.get("promoted").and_then(Value::as_bool),
        Some(false)
    );
    let promote_policy_decision_id = promote_payload
        .get("policy_decision_id")
        .and_then(Value::as_str)
        .expect("blocked promote policy decision id")
        .to_string();
    let policy_record = state
        .get_policy_decision(&promote_policy_decision_id)
        .await
        .expect("blocked promote policy decision");
    assert_eq!(
        policy_record.decision,
        tandem_types::PolicyDecisionEffect::Deny
    );
    assert_eq!(policy_record.reason_code, "enterprise_memory_promote_floor");

    let promote_event = next_event_of_type(&mut rx, "memory.promote").await;
    assert_eq!(
        promote_event
            .properties
            .get("status")
            .and_then(Value::as_str),
        Some("blocked")
    );
    assert_eq!(
        promote_event
            .properties
            .get("policyDecisionID")
            .and_then(Value::as_str),
        Some(promote_policy_decision_id.as_str())
    );
}

#[tokio::test]
async fn memory_put_blocks_project_write_denied_by_knowledge_scope() {
    let state = test_state().await;
    let app = app_router(state.clone());

    let capability = json!({
        "run_id": "run-knowledge-scope-write",
        "subject": "agent-user",
        "org_id": "org-1",
        "workspace_id": "ws-1",
        "project_id": "proj-1",
        "memory": {
            "read_tiers": ["session", "project"],
            "write_tiers": ["session", "project"],
            "promote_targets": ["project"],
            "require_review_for_promote": false,
            "allow_auto_use_tiers": ["curated"]
        },
        "expires_at": 9999999999999u64
    });

    let put_req = Request::builder()
        .method("POST")
        .uri("/memory/put")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "run_id": "run-knowledge-scope-write",
                "partition": {
                    "org_id": "org-1",
                    "workspace_id": "ws-1",
                    "project_id": "proj-1",
                    "tier": "project"
                },
                "kind": "fact",
                "content": "project write must carry explicit knowledge scope policy",
                "artifact_refs": ["artifact://run-knowledge-scope-write/output.json"],
                "classification": "internal",
                "metadata": {
                    "knowledge_scope_registry": {
                        "registry_id": "registry-session-only",
                        "resource_ref": {
                            "organization_id": "org-1",
                            "workspace_id": "ws-1",
                            "project_id": "proj-1",
                            "resource_kind": "knowledge_space",
                            "resource_id": "space-session"
                        },
                        "data_class": "confidential",
                        "collection_id": "collection-session",
                        "owner_org_unit_id": "ou-1",
                        "risk_tier": "confidential",
                        "allowed_workflow_phases": ["draft"],
                        "allowed_write_tiers": ["session"],
                        "allowed_promotion_tiers": ["project"],
                        "retention_expires_at_ms": 9999999999999u64,
                        "promotion_requires_approval": true
                    }
                },
                "capability": capability
            })
            .to_string(),
        ))
        .expect("put request");

    let put_resp = app.oneshot(put_req).await.expect("put response");
    assert_eq!(put_resp.status(), StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn memory_put_blocks_source_bound_authority_without_knowledge_scope() {
    let state = test_state().await;
    let app = app_router(state.clone());

    let capability = json!({
        "run_id": "run-source-bound-write",
        "subject": "agent-user",
        "org_id": "org-1",
        "workspace_id": "ws-1",
        "project_id": "proj-1",
        "memory": {
            "read_tiers": ["session", "project"],
            "write_tiers": ["session", "project"],
            "promote_targets": ["project"],
            "require_review_for_promote": false,
            "allow_auto_use_tiers": ["curated"]
        },
        "expires_at": 9999999999999u64
    });

    let put_req = Request::builder()
        .method("POST")
        .uri("/memory/put")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "run_id": "run-source-bound-write",
                "partition": {
                    "org_id": "org-1",
                    "workspace_id": "ws-1",
                    "project_id": "proj-1",
                    "tier": "session"
                },
                "kind": "fact",
                "content": "source-bound write must carry knowledge scope policy",
                "artifact_refs": ["artifact://run-source-bound-write/output.json"],
                "classification": "internal",
                "authority_job_context": {
                    "org_id": "org-1",
                    "workspace_id": "ws-1",
                    "project_id": "proj-1",
                    "actor_id": "agent-user",
                    "run_id": "run-source-bound-write",
                    "task_id": "task-source-bound",
                    "purpose": "write derived source-bound memory",
                    "source_binding_id": "workflow:wf-source-bound",
                    "data_class": "internal",
                    "classification": "internal",
                    "operation": "write",
                    "source_memory_ids": [],
                    "artifact_refs": ["artifact://run-source-bound-write/output.json"],
                    "policy_decision_id": "policy-1",
                    "grant_decision_id": "grant-1"
                },
                "capability": capability
            })
            .to_string(),
        ))
        .expect("put request");

    let put_resp = app.oneshot(put_req).await.expect("put response");
    assert_eq!(put_resp.status(), StatusCode::FORBIDDEN);
}