File size: 23,436 Bytes
7b2dfc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
import XCTest
@testable import DolphinCoreMLTestApp

final class CreateStateToolIntegrationTests: XCTestCase {
  func testContinuityCommandsRouteDeterministically() throws {
    let capture = try XCTUnwrap(
      AgentRequestRouter.plan(for: "Capture decision: Keep tool calls sequential")
        .initialToolCall
    )
    XCTAssertEqual(capture.name, "knowledge_capture")
    XCTAssertEqual(capture.arguments["kind"], .string("decision"))

    XCTAssertEqual(
      AgentRequestRouter.plan(for: "Search knowledge for tool routing")
        .initialToolCall?.name,
      "knowledge_search"
    )
    XCTAssertEqual(
      AgentRequestRouter.plan(for: "Synthesize project context")
        .initialToolCall?.name,
      "project_context"
    )
    XCTAssertEqual(
      AgentRequestRouter.plan(for: "Create a handoff for TestFlight verification")
        .initialToolCall?.name,
      "handoff_create"
    )
    XCTAssertEqual(
      AgentRequestRouter.plan(for: "Analyze code: let value = item!")
        .initialToolCall?.name,
      "code_analyze"
    )
    XCTAssertEqual(
      AgentRequestRouter.plan(for: "Create a handoff for what are we working on")
        .initialToolCall?.name,
      "handoff_create"
    )
    XCTAssertEqual(
      AgentRequestRouter.plan(for: "Analyze code: // what should we do next")
        .initialToolCall?.name,
      "code_analyze"
    )
    XCTAssertEqual(
      AgentRequestRouter.plan(for: "Analyze code: // show project context")
        .initialToolCall?.name,
      "code_analyze"
    )
    for request in [
      "Don’t show project context",
      "Do not show my handoffs",
      "Don't list insights",
      "Don't show tasks",
      "Don't show my calendar today",
      "Don't tell me what is my name",
    ] {
      let plan = AgentRequestRouter.plan(for: request)
      XCTAssertNil(plan.initialToolCall)
      XCTAssertTrue(plan.eligibleToolIDs.isEmpty)
    }

    let taskID = UUID().uuidString
    let negatedCompletion = AgentRequestRouter.plan(
      for: "Do not complete task \(taskID)"
    )
    XCTAssertNil(negatedCompletion.initialToolCall)
    XCTAssertTrue(negatedCompletion.eligibleToolIDs.isEmpty)
  }

  func testKnowledgeCaptureSearchAndGroundedRendering() async throws {
    let registry = AgentToolRegistry()
    let store = ContinuityTestStore(workspace: .empty)
    let context = continuityExecutionContext(store: store)
    let captureCall = AgentToolCall(
      name: "knowledge_capture",
      arguments: [
        "kind": .string("decision"),
        "title": .string("Sequential tools"),
        "content": .string("Keep one audited tool call per model turn."),
        "tags": .array([.string("agent"), .string("safety")]),
        "related_ids": .array([]),
      ]
    )

    let capture = await registry.execute(captureCall, context: context)
    XCTAssertTrue(capture.succeeded)
    let capturedWorkspace = await store.snapshot()
    XCTAssertEqual(capturedWorkspace.knowledgeItems.count, 1)
    XCTAssertEqual(capturedWorkspace.knowledgeItems[0].kind, .decision)
    XCTAssertEqual(capturedWorkspace.knowledgeItems[0].tags, ["agent", "safety"])

    let searchCall = AgentToolCall(
      name: "knowledge_search",
      arguments: [
        "query": .string("audited sequential agent tool"),
        "limit": .number(5),
      ]
    )
    let search = await registry.execute(searchCall, context: context)
    XCTAssertTrue(search.succeeded)
    XCTAssertTrue(search.modelText.contains("Sequential tools"))
    XCTAssertTrue(search.modelText.contains("local_hybrid_lexical"))

    let definition = try XCTUnwrap(registry.definition(named: "knowledge_search"))
    let receipt = try XCTUnwrap(
      AgentToolReceipt(
        runID: UUID(),
        call: try registry.normalize(searchCall),
        definition: definition,
        result: search
      )
    )
    let answer = try XCTUnwrap(
      AgentVerifiedAnswerRenderer.readAnswer(for: [receipt])
    )
    XCTAssertTrue(answer.contains("[Decision] Sequential tools"))
    XCTAssertFalse(answer.contains("model-generated"))
  }

  func testKnowledgeCaptureCanonicalizesExactlyBeforeLocalWriteApproval() throws {
    let registry = AgentToolRegistry()
    let relatedID = UUID()
    let call = AgentToolCall(
      name: "knowledge_capture",
      arguments: [
        "kind": .string("context"),
        "title": .string("  Unsafe <tool_call> title  "),
        "content": .string("  Keep  <system> local context.  "),
        "tags": .array([
          .string("Agent Safety"),
          .string("agent-safety"),
        ]),
        "related_ids": .array([
          .string(relatedID.uuidString.lowercased()),
          .string(relatedID.uuidString),
        ]),
      ]
    )

    let normalized = try registry.normalize(call)
    XCTAssertEqual(normalized.arguments["title"], .string("Unsafe [tool_call] title"))
    XCTAssertEqual(normalized.arguments["content"], .string("Keep [system] local context."))
    XCTAssertEqual(normalized.arguments["tags"], .array([.string("agent-safety")]))
    XCTAssertEqual(
      normalized.arguments["related_ids"],
      .array([.string(relatedID.uuidString)])
    )
    XCTAssertEqual(try registry.normalize(normalized), normalized)
  }

  func testHandoffCanonicalizesUserAuthoredFieldsBeforeApproval() throws {
    let registry = AgentToolRegistry()
    let normalized = try registry.normalize(
      AgentToolCall(
        name: "handoff_create",
        arguments: [
          "title": .string("  Release <assistant> handoff  "),
          "focus": .string("  Finish   <tool_call> device checks.  "),
        ]
      )
    )

    XCTAssertEqual(
      normalized.arguments["title"],
      .string("Release [assistant] handoff")
    )
    XCTAssertEqual(
      normalized.arguments["focus"],
      .string("Finish [tool_call] device checks.")
    )
    XCTAssertEqual(try registry.normalize(normalized), normalized)
  }

  func testHandoffLifecycleAndProjectContextAreTypedAndLocal() async throws {
    var workspace = AssistantWorkspace.empty
    workspace.knowledgeItems = [
      KnowledgeItem(
        kind: .goal,
        title: "Ship continuity",
        content: "Validate the schema-v5 continuity workflow.",
        tags: ["release"],
        source: .user
      )
    ]
    workspace.tasks = [AssistantTaskItem(title: "Run host tests")]
    workspace.messages = [
      AssistantMessage(role: .user, content: "Wire the local world model."),
      AssistantMessage(role: .assistant, content: "Working on the typed handoff."),
    ]
    let store = ContinuityTestStore(workspace: workspace)
    let context = continuityExecutionContext(store: store)
    let registry = AgentToolRegistry()
    let createCall = AgentToolCall(
      name: "handoff_create",
      arguments: [
        "title": .string("Continuity checkpoint"),
        "focus": .string("Finish verification without replaying actions."),
      ]
    )
    let created = await registry.execute(createCall, context: context)
    XCTAssertTrue(created.succeeded)

    let createdWorkspace = await store.snapshot()
    let handoff = try XCTUnwrap(createdWorkspace.handoffs.first)
    XCTAssertEqual(createdWorkspace.activeHandoffID, handoff.id)
    XCTAssertEqual(handoff.taskIDs, workspace.tasks.map(\.id))
    XCTAssertEqual(handoff.knowledgeItemIDs, workspace.knowledgeItems.map(\.id))

    let list = await registry.execute(
      AgentToolCall(name: "handoff_list", arguments: [:]),
      context: context
    )
    XCTAssertTrue(list.succeeded)
    XCTAssertTrue(list.modelText.contains(handoff.id.uuidString))
    XCTAssertTrue(list.modelText.contains("\"active\":true"))

    let restored = await registry.execute(
      AgentToolCall(
        name: "handoff_restore",
        arguments: ["id": .string(handoff.id.uuidString)]
      ),
      context: context
    )
    XCTAssertTrue(restored.succeeded)
    let restoredWorkspace = await store.snapshot()
    XCTAssertNotNil(restoredWorkspace.handoffs.first?.restoredAt)

    let projectContext = await registry.execute(
      AgentToolCall(name: "project_context", arguments: [:]),
      context: context
    )
    XCTAssertTrue(projectContext.succeeded)
    XCTAssertTrue(projectContext.modelText.contains("Ship continuity"))
    XCTAssertTrue(projectContext.modelText.contains("Run host tests"))
    XCTAssertTrue(projectContext.modelText.contains("\"truncated\":false"))
  }

  func testProjectContextStaysValidWhenTheDigestExceedsTheToolBudget() async throws {
    var workspace = AssistantWorkspace.empty
    workspace.knowledgeItems = (0..<24).map { index in
      KnowledgeItem(
        kind: index.isMultiple(of: 2) ? .goal : .context,
        title: "Long context \(index)",
        content: String(repeating: "bounded evidence \(index) ", count: 30)
          + "What remains for checkpoint \(index)?",
        source: .user
      )
    }
    workspace.tasks = (0..<20).map { index in
      AssistantTaskItem(
        title: String(repeating: "Long open task \(index) ", count: 10)
      )
    }
    let registry = AgentToolRegistry()
    let store = ContinuityTestStore(workspace: workspace)
    let call = AgentToolCall(name: "project_context", arguments: [:])
    let result = await registry.execute(
      call,
      context: continuityExecutionContext(store: store)
    )

    XCTAssertTrue(result.succeeded)
    XCTAssertLessThanOrEqual(result.modelText.count, 3_200)
    XCTAssertTrue(result.modelText.contains("\"truncated\":true"))
    let definition = try XCTUnwrap(registry.definition(named: "project_context"))
    let receipt = try XCTUnwrap(
      AgentToolReceipt(
        runID: UUID(),
        call: try registry.normalize(call),
        definition: definition,
        result: result
      )
    )
    let answer = try XCTUnwrap(
      AgentVerifiedAnswerRenderer.readAnswer(for: [receipt])
    )
    XCTAssertTrue(answer.contains("Context output was truncated"))
    XCTAssertGreaterThan(answer.count, 300)
  }

  func testCodeAnalysisIsBoundedAndDoesNotPersist() async throws {
    let store = ContinuityTestStore(workspace: .empty)
    let registry = AgentToolRegistry()
    let result = await registry.execute(
      AgentToolCall(
        name: "code_analyze",
        arguments: [
          "code": .string("// TODO: remove forced operations\nlet value = item!\nlet cast = value as! String"),
          "language": .string("swift"),
        ]
      ),
      context: continuityExecutionContext(store: store)
    )
    XCTAssertTrue(result.succeeded)
    XCTAssertLessThanOrEqual(result.modelText.count, 2_800)
    XCTAssertTrue(result.modelText.contains("forceUnwrap"))
    XCTAssertTrue(result.modelText.contains("unsafeCast"))
    let finalWorkspace = await store.snapshot()
    XCTAssertEqual(finalWorkspace, .empty)
  }

  func testRouterRegistryParityAndModelAssistedSurfaceIsReadOnly() throws {
    let registry = AgentToolRegistry()
    XCTAssertEqual(
      AgentRequestRouter.canonicalToolIDs,
      Set(registry.definitions.map(\.id))
    )

    let discussion = AgentRequestRouter.plan(
      for: "Let’s discuss memory, tasks, knowledge, and handoffs"
    )
    XCTAssertEqual(discussion.mode, .modelAssistedRead)
    XCTAssertFalse(discussion.eligibleToolIDs.isEmpty)
    for id in discussion.eligibleToolIDs {
      let definition = try XCTUnwrap(registry.definition(named: id))
      XCTAssertNotEqual(definition.risk, .localWrite, id)
      XCTAssertNotEqual(definition.risk, .networkRead, id)
    }

    let knowledgeID = UUID()
    XCTAssertEqual(
      AgentRequestRouter.plan(
        for: "Show knowledge details \(knowledgeID.uuidString)"
      ).initialToolCall?.name,
      "knowledge_get"
    )
    XCTAssertEqual(
      AgentRequestRouter.plan(for: "Review project state")
        .initialToolCall?.name,
      "project_review"
    )
    XCTAssertEqual(
      AgentRequestRouter.plan(for: "Reopen task \(knowledgeID.uuidString)")
        .initialToolCall?.name,
      "task_reopen"
    )
    XCTAssertEqual(
      AgentRequestRouter.plan(
        for: "Deactivate handoff \(knowledgeID.uuidString)"
      ).initialToolCall?.name,
      "handoff_deactivate"
    )
    XCTAssertNil(
      AgentRequestRouter.plan(
        for: "Do not reopen task \(knowledgeID.uuidString)"
      ).initialToolCall
    )
  }

  func testNewReadToolsAreBoundedCorrelatedAndGrounded() async throws {
    let now = Date(timeIntervalSince1970: 1_750_000_000)
    let item = KnowledgeItem(
      kind: .decision,
      title: "Release evidence",
      content: String(repeating: "Keep device proof separate from compile proof. ", count: 80),
      tags: ["release", "evidence"],
      source: .user,
      createdAt: now
    )
    let task = AssistantTaskItem(
      title: "Collect release device evidence",
      createdAt: now
    )
    let handoff = KnowledgeEngine().makeHandoff(
      title: "Release checkpoint",
      focus: "Finish device verification without replaying actions.",
      knowledge: [item],
      tasks: [task],
      createdAt: now
    )
    var workspace = AssistantWorkspace.empty
    workspace.knowledgeItems = [item]
    workspace.tasks = [task]
    workspace.handoffs = [handoff]
    workspace.activeHandoffID = handoff.id
    let store = ContinuityTestStore(workspace: workspace)
    let context = continuityExecutionContext(store: store)
    let registry = AgentToolRegistry(
      dateProvider: FixedContinuityDateProvider(date: now)
    )

    let knowledgeCall = AgentToolCall(
      name: "knowledge_get",
      arguments: ["id": .string(item.id.uuidString)]
    )
    let knowledgeResult = await registry.execute(knowledgeCall, context: context)
    XCTAssertTrue(knowledgeResult.succeeded)
    XCTAssertLessThanOrEqual(knowledgeResult.modelText.count, 3_200)
    XCTAssertTrue(knowledgeResult.modelText.contains("content_truncated"))
    let knowledgeDefinition = try XCTUnwrap(
      registry.definition(named: "knowledge_get")
    )
    let knowledgeReceipt = try XCTUnwrap(
      AgentToolReceipt(
        runID: UUID(),
        call: try registry.normalize(knowledgeCall),
        definition: knowledgeDefinition,
        result: knowledgeResult
      )
    )
    XCTAssertTrue(
      try XCTUnwrap(
        AgentVerifiedAnswerRenderer.readAnswer(for: [knowledgeReceipt])
      ).contains("Revision 1")
    )
    let mismatchedReceipt = try XCTUnwrap(
      AgentToolReceipt(
        runID: UUID(),
        call: AgentToolCall(
          name: "knowledge_get",
          arguments: ["id": .string(UUID().uuidString)]
        ),
        definition: knowledgeDefinition,
        result: knowledgeResult
      )
    )
    XCTAssertNil(
      AgentVerifiedAnswerRenderer.readAnswer(for: [mismatchedReceipt])
    )

    let reviewCall = AgentToolCall(
      name: "project_review",
      arguments: ["limit": .number(5)]
    )
    let reviewResult = await registry.execute(reviewCall, context: context)
    XCTAssertTrue(reviewResult.succeeded)
    XCTAssertLessThanOrEqual(reviewResult.modelText.count, 4_000)
    let reviewReceipt = try XCTUnwrap(
      AgentToolReceipt(
        runID: UUID(),
        call: try registry.normalize(reviewCall),
        definition: try XCTUnwrap(registry.definition(named: "project_review")),
        result: reviewResult
      )
    )
    XCTAssertTrue(
      try XCTUnwrap(
        AgentVerifiedAnswerRenderer.readAnswer(for: [reviewReceipt])
      ).contains("Project review")
    )

    let taskCall = AgentToolCall(
      name: "task_search",
      arguments: [
        "query": .string("release device"),
        "include_completed": .bool(false),
        "limit": .number(5),
      ]
    )
    let taskResult = await registry.execute(taskCall, context: context)
    let taskReceipt = try XCTUnwrap(
      AgentToolReceipt(
        runID: UUID(),
        call: try registry.normalize(taskCall),
        definition: try XCTUnwrap(registry.definition(named: "task_search")),
        result: taskResult
      )
    )
    XCTAssertTrue(
      try XCTUnwrap(
        AgentVerifiedAnswerRenderer.readAnswer(for: [taskReceipt])
      ).contains(task.id.uuidString)
    )

    let handoffCall = AgentToolCall(
      name: "handoff_get",
      arguments: ["id": .string(handoff.id.uuidString)]
    )
    let handoffResult = await registry.execute(handoffCall, context: context)
    let handoffReceipt = try XCTUnwrap(
      AgentToolReceipt(
        runID: UUID(),
        call: try registry.normalize(handoffCall),
        definition: try XCTUnwrap(registry.definition(named: "handoff_get")),
        result: handoffResult
      )
    )
    let handoffAnswer = try XCTUnwrap(
      AgentVerifiedAnswerRenderer.readAnswer(for: [handoffReceipt])
    )
    XCTAssertTrue(handoffAnswer.contains("Saved handoff"))
    XCTAssertTrue(handoffAnswer.contains("replayed no prior action"))
  }

  func testNewWritesRequireExplicitRoutesAndMutateOnlyTargetState()
    async throws
  {
    let now = Date(timeIntervalSince1970: 1_750_000_000)
    let task = AssistantTaskItem(
      title: "Recheck TestFlight",
      isCompleted: true,
      createdAt: now,
      completedAt: now
    )
    let handoff = SessionHandoff(
      title: "Release checkpoint",
      focus: "Continue release verification",
      summary: "No previous action should replay.",
      createdAt: now
    )
    var workspace = AssistantWorkspace.empty
    workspace.tasks = [task]
    workspace.handoffs = [handoff]
    workspace.activeHandoffID = handoff.id
    let store = ContinuityTestStore(workspace: workspace)
    let context = continuityExecutionContext(store: store)
    let registry = AgentToolRegistry()

    let reopenDefinition = try XCTUnwrap(
      registry.definition(named: "task_reopen")
    )
    XCTAssertEqual(
      AgentPolicy.decision(for: reopenDefinition, settings: AgentSettings()),
      .requireApproval(
        "This action changes saved assistant data on this iPhone."
      )
    )
    let reopened = await registry.execute(
      AgentToolCall(
        name: "task_reopen",
        arguments: ["id": .string(task.id.uuidString)]
      ),
      context: context
    )
    XCTAssertTrue(reopened.succeeded)
    var updated = await store.snapshot()
    XCTAssertFalse(try XCTUnwrap(updated.tasks.first).isCompleted)
    XCTAssertNil(updated.tasks.first?.completedAt)
    let reopenedAgain = await registry.execute(
      AgentToolCall(
        name: "task_reopen",
        arguments: ["id": .string(task.id.uuidString)]
      ),
      context: context
    )
    XCTAssertFalse(reopenedAgain.succeeded)

    let deactivated = await registry.execute(
      AgentToolCall(
        name: "handoff_deactivate",
        arguments: ["id": .string(handoff.id.uuidString)]
      ),
      context: context
    )
    XCTAssertTrue(deactivated.succeeded)
    updated = await store.snapshot()
    XCTAssertNil(updated.activeHandoffID)
    XCTAssertEqual(updated.handoffs, [handoff])
    let deactivatedAgain = await registry.execute(
      AgentToolCall(
        name: "handoff_deactivate",
        arguments: ["id": .string(handoff.id.uuidString)]
      ),
      context: context
    )
    XCTAssertFalse(deactivatedAgain.succeeded)
  }

  func testSchemaFiveRoundTripPreservesContinuityState() async throws {
    let fixedDate = Date(timeIntervalSince1970: 1_700_000_000)
    let item = KnowledgeItem(
      kind: .preference,
      title: "Verification style",
      content: "Keep compile evidence separate from device evidence.",
      tags: ["testing"],
      source: .user,
      createdAt: fixedDate
    )
    let handoff = KnowledgeEngine().makeHandoff(
      title: "Release handoff",
      focus: "Run the remaining device walkthrough.",
      knowledge: [item],
      tasks: [],
      createdAt: fixedDate
    )
    let digest = KnowledgeEngine().synthesizeContext(
      knowledge: [item],
      tasks: [],
      handoff: handoff,
      createdAt: fixedDate
    )
    var workspace = AssistantWorkspace.empty
    workspace.knowledgeItems = [item]
    workspace.knowledgeDigests = [digest]
    workspace.handoffs = [handoff]
    workspace.activeHandoffID = handoff.id

    let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent(
      "dolphin-schema-five-\(UUID().uuidString).json"
    )
    defer { try? FileManager.default.removeItem(at: fileURL) }
    let persistence = try AssistantPersistence(fileURL: fileURL)
    try await persistence.save(workspace)
    let reloaded = try await persistence.load()
    XCTAssertEqual(reloaded, workspace)
  }
}

private actor ContinuityTestStore {
  private var workspace: AssistantWorkspace

  init(workspace: AssistantWorkspace) {
    self.workspace = workspace
  }

  func snapshot() -> AssistantWorkspace { workspace }

  func commit(
    _ mutation: AssistantWorkspaceMutation,
    resultBuilder: AssistantWorkspaceResultBuilder
  ) throws -> AgentToolResult {
    switch mutation {
    case .saveMemory(let item):
      workspace.memories.append(item)
      return try resultBuilder(.memory(item))
    case .captureKnowledge(let item):
      workspace.knowledgeItems.append(item)
      return try resultBuilder(.knowledge(item))
    case .createHandoff(let handoff):
      if let index = workspace.handoffs.firstIndex(where: { $0.id == handoff.id }) {
        workspace.handoffs[index] = handoff
      } else {
        workspace.handoffs.append(handoff)
      }
      workspace.activeHandoffID = handoff.id
      return try resultBuilder(.handoff(handoff))
    case .restoreHandoff(let id, let restoredAt):
      guard let index = workspace.handoffs.firstIndex(where: { $0.id == id }) else {
        throw ContinuityTestError.handoffNotFound
      }
      workspace.handoffs[index].restoredAt = restoredAt
      workspace.activeHandoffID = id
      return try resultBuilder(.handoff(workspace.handoffs[index]))
    case .deactivateHandoff(let id):
      guard workspace.activeHandoffID == id,
        let handoff = workspace.handoffs.first(where: { $0.id == id })
      else { throw ContinuityTestError.handoffNotFound }
      workspace.activeHandoffID = nil
      return try resultBuilder(.handoff(handoff))
    case .addTask(let item):
      workspace.tasks.append(item)
      return try resultBuilder(.task(item))
    case .completeTask(let id, let completedAt):
      guard let index = workspace.tasks.firstIndex(where: { $0.id == id }) else {
        throw ContinuityTestError.taskNotFound
      }
      workspace.tasks[index].isCompleted = true
      workspace.tasks[index].completedAt = completedAt
      return try resultBuilder(.task(workspace.tasks[index]))
    case .reopenTask(let id):
      guard let index = workspace.tasks.firstIndex(where: { $0.id == id }),
        workspace.tasks[index].isCompleted
      else { throw ContinuityTestError.taskNotFound }
      workspace.tasks[index].isCompleted = false
      workspace.tasks[index].completedAt = nil
      return try resultBuilder(.task(workspace.tasks[index]))
    }
  }
}

private enum ContinuityTestError: Error {
  case handoffNotFound
  case taskNotFound
}

private struct FixedContinuityDateProvider: DateProviding {
  let date: Date

  func now() -> Date { date }
}

private func continuityExecutionContext(
  store: ContinuityTestStore
) -> AgentToolExecutionContext {
  AgentToolExecutionContext(
    snapshot: { await store.snapshot() },
    commitLocalWrite: { mutation, _, _, resultBuilder in
      try await store.commit(mutation, resultBuilder: resultBuilder)
    }
  )
}