Skip to content

symfonic.agent.fastapi.router

router

FastAPI router factory for agent endpoints.

Provides create_agent_router() which wraps a SymfonicAgent in /chat and /stream HTTP endpoints.

create_agent_router

create_agent_router(
    agent: SymfonicAgent, prefix: str = "/api/v1"
) -> APIRouter

Create a FastAPI router wrapping a SymfonicAgent.

Endpoints

POST {prefix}/chat -- synchronous chat, returns AgentResponse JSON POST {prefix}/stream -- SSE streaming, yields StreamChunk events

Parameters:

Name Type Description Default
agent SymfonicAgent

The SymfonicAgent instance to expose.

required
prefix str

URL prefix for the router (default /api/v1).

'/api/v1'

Returns:

Type Description
APIRouter

Configured APIRouter.

Raises:

Type Description
RuntimeError

If a production environment is detected (via SYMFONIC_ENV, APP_ENV, ENVIRONMENT, or NODE_ENV set to production/prod) but no tenant-auth verifier is registered via :func:set_tenant_auth_verifier. Set ALLOW_INSECURE_PROD=true to bypass (NOT recommended — logs a CRITICAL warning).

Source code in src/symfonic/agent/fastapi/router.py
 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
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
def create_agent_router(
    agent: SymfonicAgent,
    prefix: str = "/api/v1",
) -> APIRouter:
    """Create a FastAPI router wrapping a SymfonicAgent.

    Endpoints:
        POST {prefix}/chat  -- synchronous chat, returns AgentResponse JSON
        POST {prefix}/stream -- SSE streaming, yields StreamChunk events

    Args:
        agent: The SymfonicAgent instance to expose.
        prefix: URL prefix for the router (default ``/api/v1``).

    Returns:
        Configured APIRouter.

    Raises:
        RuntimeError: If a production environment is detected (via
            ``SYMFONIC_ENV``, ``APP_ENV``, ``ENVIRONMENT``, or ``NODE_ENV``
            set to ``production``/``prod``) but no tenant-auth verifier is
            registered via :func:`set_tenant_auth_verifier`.  Set
            ``ALLOW_INSECURE_PROD=true`` to bypass (NOT recommended —
            logs a CRITICAL warning).
    """
    # Fail-fast in production when auth verifier isn't wired.  The previous
    # dev-mode fallback (one-shot WARN then trust X-Tenant-ID blindly) was
    # a critical tenant-isolation bug waiting for the next deployer to
    # forget ``register_tenant_auth_verifier()``.
    _check_production_auth_gate()

    router = APIRouter(prefix=prefix, tags=["agent"])

    @router.post("/chat", response_model=AgentResponse)
    async def chat(
        request: AgentRequest,
        raw_request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
        _budget: None = Depends(check_budget_before_llm),  # noqa: B008
    ) -> AgentResponse:
        """Execute the agent and return the full response."""
        try:
            return await agent.run(
                query=request.query,
                attachments=request.attachments,
                scope=scope,
                is_admin=bool(getattr(raw_request.state, "is_admin", False)),
                session_id=request.session_id,
            )
        except SecurityScopeError as exc:
            raise HTTPException(
                status_code=403,
                detail="Access denied: missing or invalid tenant scope",
            ) from exc
        except ScopeValidationError as exc:
            raise HTTPException(status_code=400, detail=str(exc)) from exc
        except SymfonicAgentError as exc:
            # Budget breaker (defence-in-depth at the agent layer) surfaces
            # as a typed SymfonicAgentError with "Budget exceeded:" prefix.
            # Translate to 429 so clients treat it like the dep-layer 429.
            msg = str(exc)
            if msg.startswith("Budget exceeded:"):
                raise HTTPException(
                    status_code=429, detail=msg,
                    headers={"Retry-After": "3600"},
                ) from exc
            # v7.1.3 (Item 10.1): map code -> HTTP status (bad_request->400,
            # failed_dependency->424, ...). Unknown codes fall back to 500.
            status_code = _status_from_agent_error(exc)
            detail = str(exc) if status_code != 500 else "Agent execution failed"
            raise HTTPException(status_code=status_code, detail=detail) from exc
        except Exception as exc:
            raise HTTPException(status_code=500, detail="Internal server error") from exc

    @router.post("/stream")
    async def stream(
        request: AgentRequest,
        raw_request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
        _budget: None = Depends(check_budget_before_llm),  # noqa: B008
    ) -> Any:
        """Stream agent execution as Server-Sent Events."""
        from sse_starlette.sse import EventSourceResponse

        is_admin = bool(getattr(raw_request.state, "is_admin", False))

        async def event_generator() -> Any:
            try:
                async for chunk in agent.stream(
                    query=request.query,
                    attachments=request.attachments,
                    scope=scope,
                    is_admin=is_admin,
                    session_id=request.session_id,
                ):
                    yield {
                        "event": chunk.event_type,
                        "data": chunk.model_dump_json(),
                    }
            except SecurityScopeError:
                yield {
                    "event": "error",
                    "data": '{"detail": "Access denied: missing or invalid tenant scope"}',
                }
            except ScopeValidationError as exc:
                yield {
                    "event": "error",
                    "data": json.dumps({"detail": str(exc)}),
                }
            except SymfonicAgentError as exc:
                msg = str(exc)
                if msg.startswith("Budget exceeded:"):
                    yield {
                        "event": "error",
                        "data": json.dumps({"detail": msg, "status": 429}),
                    }
                else:
                    # v7.1.3 (Item 10.1): same status mapping as /chat so
                    # SSE clients see consistent error semantics.
                    status_code = _status_from_agent_error(exc)
                    detail = (
                        str(exc) if status_code != 500 else "Agent execution failed"
                    )
                    yield {
                        "event": "error",
                        "data": json.dumps(
                            {"detail": detail, "status": status_code},
                        ),
                    }
            except Exception:
                logger.exception("Stream event generator failed")
                yield {
                    "event": "error",
                    "data": '{"detail": "Internal server error"}',
                }

        return EventSourceResponse(event_generator())

    @router.post("/stream/typed")
    async def stream_typed(
        request: AgentRequest,
        raw_request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
        _budget: None = Depends(check_budget_before_llm),  # noqa: B008
    ) -> Any:
        """Stream agent execution as typed Server-Sent Events.

        Each SSE event's ``event`` field is the StreamEvent class name
        (e.g. ``TextDeltaEvent``, ``ToolCallStartEvent``).  The ``data``
        field is the JSON-serialized event payload.
        """
        from sse_starlette.sse import EventSourceResponse

        from symfonic.core.streaming.transpiler import _event_to_dict

        is_admin = bool(getattr(raw_request.state, "is_admin", False))

        async def typed_event_generator() -> Any:
            try:
                async for stream_event in agent.stream_typed(
                    query=request.query,
                    attachments=request.attachments,
                    scope=scope,
                    is_admin=is_admin,
                    session_id=request.session_id,
                ):
                    event_name = type(stream_event).__name__
                    yield {
                        "event": event_name,
                        # default=str is a defense-in-depth fallback for any
                        # type _make_json_safe might miss (e.g. nested
                        # langchain objects).
                        "data": json.dumps(
                            _event_to_dict(stream_event), default=str,
                        ),
                    }
            except SecurityScopeError:
                yield {
                    "event": "error",
                    "data": '{"detail": "Access denied: missing or invalid tenant scope"}',
                }
            except ScopeValidationError as exc:
                yield {
                    "event": "error",
                    "data": json.dumps({"detail": str(exc)}),
                }
            except SymfonicAgentError as exc:
                msg = str(exc)
                if msg.startswith("Budget exceeded:"):
                    yield {
                        "event": "error",
                        "data": json.dumps({"detail": msg, "status": 429}),
                    }
                else:
                    # v7.1.3 (Item 10.1): consistent code -> status mapping.
                    status_code = _status_from_agent_error(exc)
                    detail = (
                        str(exc) if status_code != 500 else "Agent execution failed"
                    )
                    yield {
                        "event": "error",
                        "data": json.dumps(
                            {"detail": detail, "status": status_code},
                        ),
                    }
            except Exception:
                logger.exception("Typed stream event generator failed")
                yield {
                    "event": "error",
                    "data": '{"detail": "Internal server error"}',
                }

        return EventSourceResponse(typed_event_generator())

    @router.post("/resume/{pause_token}")
    async def resume(
        pause_token: str,
        raw_request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> Any:
        """Resume a paused agent execution.

        Dispatches on the token's ``name`` claim:

        * ``name == "ask_user"`` -> :meth:`SymfonicAgent.resume` with an
          ``AskUserResponse`` body (existing public API; URL unchanged).
        * other registered names -> :meth:`SymfonicAgent.resume_interrupt`
          with a body validated against the registered ``response_schema``
          (Roadmap Item 9, behind ``experimental_interrupt=True``).

        Returns a typed Server-Sent Events stream as the run continues.
        """
        from sse_starlette.sse import EventSourceResponse

        from symfonic.agent.middleware.pause_token import PauseToken
        from symfonic.core.streaming.transpiler import _event_to_dict

        # Stateless preview decode (HMAC + expiry only) to discover the
        # registered interrupt name. Roadmap Item 9 dispatches generic
        # interrupts here; ask_user stays on the historical path so the
        # existing /resume contract -- including the public test suite
        # that monkeypatches ``agent.resume`` -- is unchanged.
        #
        # If preview decode fails for any reason (malformed token,
        # expired, etc.), we DEFAULT TO ASK_USER. This keeps the
        # historical behaviour where ``agent.resume`` raises a typed
        # error during its own decode pass; that error code maps to
        # the right HTTP status via ``_status_from_agent_error``.
        # The token is still rejected by ``agent.resume``; we just do
        # not pre-empt the rejection here.
        token_name = "ask_user"
        try:
            preview_claims = PauseToken.decode(pause_token, agent._config)
            token_name = (
                getattr(preview_claims, "name", "ask_user") or "ask_user"
            )
        except Exception:
            # Fall through with the default ask_user assumption; the
            # downstream engine call will re-decode and raise the same
            # typed error the historical contract returned.
            pass

        registration = agent._registered_interrupts.get(token_name)
        is_ask_user = (
            (registration is None)
            or (registration.built_in and token_name == "ask_user")
        )

        # Parse + validate the body against the right schema. For the
        # ask_user case we keep the existing AskUserResponse contract;
        # for generic interrupts we look up the registered response
        # schema and validate against it.
        try:
            raw_body = await raw_request.json()
        except Exception as exc:
            return EventSourceResponse(
                _single_error_event(f"Invalid JSON body: {exc}", 400),
            )

        try:
            if is_ask_user:
                response_obj: Any = AskUserResponse.model_validate(raw_body)
            else:
                if registration is None:
                    return EventSourceResponse(
                        _single_error_event(
                            f"Token references unknown interrupt "
                            f"{token_name!r}",
                            400,
                        ),
                    )
                response_obj = registration.response_schema.model_validate(
                    raw_body,
                )
        except Exception as exc:
            return EventSourceResponse(
                _single_error_event(f"Invalid resume payload: {exc}", 400),
            )

        async def resume_generator() -> Any:
            try:
                if is_ask_user:
                    iterator = agent.resume(
                        pause_token=pause_token,
                        response=response_obj,
                        scope=scope,
                    )
                else:
                    iterator = agent.resume_interrupt(
                        pause_token=pause_token,
                        response=response_obj,
                        scope=scope,
                    )
                async for stream_event in iterator:
                    event_name = type(stream_event).__name__
                    yield {
                        "event": event_name,
                        "data": json.dumps(
                            _event_to_dict(stream_event), default=str,
                        ),
                    }
            except SecurityScopeError:
                yield {
                    "event": "error",
                    "data": '{"detail": "Access denied: missing or invalid tenant scope"}',
                }
            except ScopeValidationError as exc:
                yield {
                    "event": "error",
                    "data": json.dumps({"detail": str(exc)}),
                }
            except SymfonicAgentError as exc:
                # v7.1.3 (Item 10.1): use the centralised mapping so
                # ``bad_request`` and ``failed_dependency`` now surface as
                # 400 / 424 (previously bad_request fell through to the
                # default 400 by coincidence; failed_dependency leaked
                # the request_hash-mismatch / MemorySaver-restart path
                # as a generic 400). Unknown codes still default to 400
                # here -- /resume is more restrictive than /chat because
                # an unrecognised error during a token redemption is
                # almost certainly a client-side payload bug.
                status_code = _status_from_agent_error(exc)
                if status_code == 500:
                    # Preserve the historical /resume default of 400 for
                    # unmapped codes; only known generic-error codes get 500.
                    status_code = 400

                yield {
                    "event": "error",
                    "data": json.dumps({"detail": str(exc), "status": status_code}),
                }
            except Exception:
                logger.exception("Resume event generator failed")
                yield {
                    "event": "error",
                    "data": '{"detail": "Internal server error"}',
                }

        return EventSourceResponse(resume_generator())

    @router.get("/chats")
    async def list_chats(
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> list[dict[str, Any]]:
        """List active chat sessions for the current tenant."""
        try:
            return agent._session_manager.list_sessions(scope.tenant_id)
        except SecurityScopeError as exc:
            raise HTTPException(
                status_code=403,
                detail="Access denied: missing or invalid tenant scope",
            ) from exc
        except ScopeValidationError as exc:
            raise HTTPException(status_code=400, detail=str(exc)) from exc

    @router.get("/memories/status", response_model=list[MemoryBlockStatus])
    async def memory_status(
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> list[MemoryBlockStatus]:
        """Return the status of known memory blocks for the current tenant."""
        try:
            discovery = DiscoveryService(agent._orchestrator)
            required = agent._config.domain.required_labels or None
            blocks = await discovery.scan_status(
                scope.to_memory_scope(),
                required_labels=required,
            )
            return [
                MemoryBlockStatus(
                    label=b.label,
                    exists=b.exists,
                    entry_count=b.entry_count,
                    last_updated=b.last_updated,
                    importance=b.importance,
                    layer=b.layer.value,
                    enabled=b.layer.value in agent._config.enabled_layers,
                    is_required=b.is_required,
                )
                for b in blocks
            ]
        except SecurityScopeError as exc:
            raise HTTPException(
                status_code=403,
                detail="Access denied: missing or invalid tenant scope",
            ) from exc
        except ScopeValidationError as exc:
            raise HTTPException(status_code=400, detail=str(exc)) from exc
        except Exception as exc:
            raise HTTPException(status_code=500, detail="Internal server error") from exc

    # ------------------------------------------------------------------
    # Memory CRUD
    # ------------------------------------------------------------------

    @router.get("/memories")
    async def list_memories(
        layer: str | None = None,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> list[dict[str, Any]]:
        """List memory nodes for the tenant, grouped by label prefix.

        Query params:
            layer: Optional memory layer filter (semantic, episodic,
                   procedural, prospective, working). When omitted, all
                   available layers are merged.
        """
        memory_scope = scope.to_memory_scope()

        # Determine which layers to query.
        if layer is not None:
            try:
                target_layer = MemoryLayer(layer)
            except ValueError:
                raise HTTPException(  # noqa: B904
                    status_code=400,
                    detail=f"unknown layer: {layer!r}",
                )
            target_layers = [target_layer]
        else:
            target_layers = list(MemoryLayer)

        all_nodes: list[Any] = []
        result: list[dict[str, Any]] = []
        for ml in target_layers:
            store = agent._orchestrator.get_layer(ml)
            if store is None:
                continue

            # EpisodicLayer is vector-backed (no _graph); enumerate via its
            # public list_events() API and emit result dicts directly.
            if ml == MemoryLayer.EPISODIC:
                try:
                    entries = await store.list_events(memory_scope)  # type: ignore[union-attr]
                    for entry in entries:
                        content = entry.content or ""
                        label = content[:80] if content else "episodic-event"
                        md = entry.metadata or {}
                        group = (
                            str(md.get("group", ""))
                            or str(md.get("action_type", ""))
                            or "episodic"
                        )
                        created_at_str = (
                            entry.created_at.isoformat()
                            if entry.created_at
                            else None
                        )
                        result.append({
                            "id": str(entry.id) if entry.id else "",
                            "label": label,
                            "group": group,
                            "layer": ml.value,
                            "properties": md,
                            "importance": entry.importance,
                            "created_at": created_at_str,
                            "updated_at": None,
                        })
                except Exception:
                    logger.debug("Failed to query episodic layer", exc_info=True)
                continue

            graph = getattr(store, "_graph", None)
            if graph is None:
                continue
            try:
                nodes = await graph.query_nodes(  # type: ignore[union-attr]
                    memory_scope, layer=ml,
                )
                all_nodes.extend((ml, n) for n in nodes)
            except Exception:
                logger.debug("Failed to query layer %s", ml, exc_info=True)

        for ml, node in all_nodes:
            label = str(node.label)
            # Prefer explicit metadata group/type, fall back to label prefix.
            props = node.properties or {}
            if ml == MemoryLayer.PROCEDURAL:
                # Procedural nodes carry description-length labels (e.g.
                # "Standard app deployment workflow triggered by ..."), so
                # the default split-on-":" logic would leak prose into the
                # group column.  Use a stable, short group derived from the
                # skill id or a constant fallback.
                group = (
                    str(props.get("group", ""))
                    or str(props.get("id", ""))
                    or "procedure"
                )
            else:
                group = (
                    str(props.get("group", ""))
                    or str(props.get("type", ""))
                    or (label.split(":")[0].strip() if ":" in label else label)
                )
            result.append({
                "id": str(node.id),
                "label": label,
                "group": group,
                "layer": ml.value,
                "properties": node.properties,
                "importance": node.importance,
                "created_at": str(node.created_at) if node.created_at else None,
                "updated_at": str(node.updated_at) if node.updated_at else None,
            })
        return result

    @router.get("/memories/{node_id}")
    async def get_memory(
        node_id: str,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> dict[str, Any]:
        """Return the full details of a single semantic memory node."""
        semantic = agent._orchestrator.get_layer(MemoryLayer.SEMANTIC)
        if semantic is None:
            raise HTTPException(404, "Semantic layer not available")
        memory_scope = scope.to_memory_scope()
        node = await semantic._graph.get_node(  # type: ignore[union-attr]
            memory_scope, NodeId(node_id),
        )
        if node is None:
            raise HTTPException(404, f"Node {node_id} not found")
        return {
            "id": str(node.id),
            "label": str(node.label),
            "layer": node.layer.value,
            "properties": node.properties,
            "importance": node.importance,
            "access_count": node.access_count,
            "created_at": str(node.created_at) if node.created_at else None,
            "updated_at": str(node.updated_at) if node.updated_at else None,
        }

    @router.patch("/memories/{node_id}")
    async def update_memory(
        node_id: str,
        request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> dict[str, Any]:
        """Update a memory node's content or properties."""
        body = await request.json()
        semantic = agent._orchestrator.get_layer(MemoryLayer.SEMANTIC)
        if semantic is None:
            raise HTTPException(404, "Semantic layer not available")
        memory_scope = scope.to_memory_scope()

        updates: dict[str, object] = {}
        if "content" in body:
            updates["label"] = body["content"]
        if "properties" in body:
            updates["properties"] = body["properties"]
        if "importance" in body:
            updates["importance"] = body["importance"]

        # Audit trail
        props = updates.get("properties", {})
        if isinstance(props, dict):
            props["_last_edited_by"] = "user_manual_edit"
            updates["properties"] = props

        try:
            node = await semantic._graph.update_node(  # type: ignore[union-attr]
                memory_scope, NodeId(node_id), updates,
            )
            _emit_router_audit(
                request, scope,
                action="update_memory",
                resource_type="memory_node",
                resource_id=node_id,
                metadata={"fields": sorted(updates.keys())},
            )
            return {
                "id": str(node.id),
                "label": node.label,
                "properties": node.properties,
            }
        except KeyError as exc:
            raise HTTPException(404, f"Node {node_id} not found") from exc

    @router.delete("/memories/{node_id}")
    async def delete_memory(
        node_id: str,
        request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> dict[str, str]:
        """Delete a memory node and cascade-delete its edges."""
        semantic = agent._orchestrator.get_layer(MemoryLayer.SEMANTIC)
        if semantic is None:
            raise HTTPException(404, "Semantic layer not available")
        memory_scope = scope.to_memory_scope()
        # Verify node exists before deleting (backends silently ignore missing)
        existing = await semantic._graph.get_node(  # type: ignore[union-attr]
            memory_scope, NodeId(node_id),
        )
        if existing is None:
            raise HTTPException(404, f"Node {node_id} not found")
        await semantic._graph.delete_node(  # type: ignore[union-attr]
            memory_scope, NodeId(node_id),
        )
        _emit_router_audit(
            request, scope,
            action="delete_memory",
            resource_type="memory_node",
            resource_id=node_id,
            metadata={"label": str(existing.label)},
        )
        return {"deleted": node_id}

    # ------------------------------------------------------------------
    # Procedural CRUD (Workflows)
    # ------------------------------------------------------------------

    @router.get("/procedures")
    async def list_procedures(
        status: str | None = None,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> list[dict[str, Any]]:
        """List procedural nodes (learned workflows/skills).

        By default only approved (active) skills are returned.
        Use ``?status=draft`` or ``?status=rejected`` to filter, or
        ``?status=all`` to return everything.
        """
        procedural = agent._orchestrator.get_layer(MemoryLayer.PROCEDURAL)
        if procedural is None:
            return []
        memory_scope = scope.to_memory_scope()
        nodes = await procedural._graph.query_nodes(  # type: ignore[union-attr]
            memory_scope, layer=MemoryLayer.PROCEDURAL,
        )
        result: list[dict[str, Any]] = []
        for node in nodes:
            props = node.properties or {}
            node_status = props.get("status", "approved")
            # Default filter: only approved. With ?status=<val>: match that.
            if status is None:
                if node_status != "approved":
                    continue
            elif status != "all" and node_status != status:
                continue
            result.append({
                "id": str(node.id),
                "label": str(node.label),
                "content": props.get("content", node.label),
                "steps": props.get("steps", []),
                "properties": props,
                "status": node_status,
                "active": props.get("active", True),
                "importance": node.importance,
                "created_at": str(node.created_at) if node.created_at else None,
                "updated_at": str(node.updated_at) if node.updated_at else None,
            })
        return result

    @router.get("/procedures/drafts")
    async def list_draft_procedures(
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> list[dict[str, Any]]:
        """List all draft (pending review) procedural skills."""
        procedural = agent._orchestrator.get_layer(MemoryLayer.PROCEDURAL)
        if procedural is None:
            return []
        memory_scope = scope.to_memory_scope()
        nodes = await procedural._graph.query_nodes(  # type: ignore[union-attr]
            memory_scope, layer=MemoryLayer.PROCEDURAL,
        )
        return [
            {
                "id": str(node.id),
                "label": str(node.label),
                "content": (node.properties or {}).get("content", node.label),
                "steps": (node.properties or {}).get("steps", []),
                "status": "draft",
                "active": False,
                "importance": node.importance,
                "created_at": str(node.created_at) if node.created_at else None,
            }
            for node in nodes
            if (node.properties or {}).get("status") == "draft"
        ]

    @router.post("/procedures/{node_id}/approve")
    async def approve_procedure(
        node_id: str,
        request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> dict[str, Any]:
        """Approve a draft skill -- makes it active."""
        procedural = agent._orchestrator.get_layer(MemoryLayer.PROCEDURAL)
        if procedural is None:
            raise HTTPException(404, "Procedural layer not available")
        memory_scope = scope.to_memory_scope()
        try:
            node = await procedural.approve_skill(
                memory_scope, NodeId(node_id),
            )
        except KeyError as exc:
            raise HTTPException(404, str(exc)) from exc
        _emit_router_audit(
            request, scope,
            action="approve_procedure",
            resource_type="procedure",
            resource_id=node_id,
        )
        props = node.properties or {}
        return {
            "id": str(node.id),
            "label": str(node.label),
            "status": props.get("status", "approved"),
            "active": props.get("active", True),
        }

    @router.post("/procedures/{node_id}/reject")
    async def reject_procedure(
        node_id: str,
        request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> dict[str, Any]:
        """Reject a draft skill -- archives it."""
        procedural = agent._orchestrator.get_layer(MemoryLayer.PROCEDURAL)
        if procedural is None:
            raise HTTPException(404, "Procedural layer not available")
        memory_scope = scope.to_memory_scope()
        try:
            node = await procedural.reject_skill(
                memory_scope, NodeId(node_id),
            )
        except KeyError as exc:
            raise HTTPException(404, str(exc)) from exc
        _emit_router_audit(
            request, scope,
            action="reject_procedure",
            resource_type="procedure",
            resource_id=node_id,
        )
        props = node.properties or {}
        return {
            "id": str(node.id),
            "label": str(node.label),
            "status": props.get("status", "rejected"),
            "active": props.get("active", False),
        }

    @router.get("/procedures/{node_id}")
    async def get_procedure(
        node_id: str,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> dict[str, Any]:
        """Return a single procedural node's full details."""
        procedural = agent._orchestrator.get_layer(MemoryLayer.PROCEDURAL)
        if procedural is None:
            raise HTTPException(404, "Procedural layer not available")
        memory_scope = scope.to_memory_scope()
        node = await procedural._graph.get_node(  # type: ignore[union-attr]
            memory_scope, NodeId(node_id),
        )
        if node is None:
            raise HTTPException(404, f"Node {node_id} not found")
        props = node.properties or {}
        return {
            "id": str(node.id),
            "label": str(node.label),
            "content": props.get("content", node.label),
            "steps": props.get("steps", []),
            "properties": props,
            "active": props.get("active", True),
            "importance": node.importance,
            "created_at": str(node.created_at) if node.created_at else None,
            "updated_at": str(node.updated_at) if node.updated_at else None,
        }

    @router.patch("/procedures/{node_id}")
    async def update_procedure(
        node_id: str,
        request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> dict[str, Any]:
        """Update a procedural node's steps, properties, or active flag."""
        body = await request.json()
        procedural = agent._orchestrator.get_layer(MemoryLayer.PROCEDURAL)
        if procedural is None:
            raise HTTPException(404, "Procedural layer not available")
        memory_scope = scope.to_memory_scope()

        # Fetch existing node to merge properties
        existing = await procedural._graph.get_node(  # type: ignore[union-attr]
            memory_scope, NodeId(node_id),
        )
        if existing is None:
            raise HTTPException(404, f"Node {node_id} not found")

        merged_props: dict[str, object] = dict(existing.properties or {})
        touched_fields: list[str] = []
        if "steps" in body:
            merged_props["steps"] = body["steps"]
            touched_fields.append("steps")
        if "properties" in body:
            merged_props.update(body["properties"])
            touched_fields.append("properties")
        if "active" in body:
            merged_props["active"] = body["active"]
            touched_fields.append("active")

        # Audit trail
        merged_props["_last_edited_by"] = "user_manual_edit"

        try:
            node = await procedural._graph.update_node(  # type: ignore[union-attr]
                memory_scope, NodeId(node_id), {"properties": merged_props},
            )
            _emit_router_audit(
                request, scope,
                action="update_procedure",
                resource_type="procedure",
                resource_id=node_id,
                metadata={"fields": sorted(touched_fields)},
            )
            props = node.properties or {}
            return {
                "id": str(node.id),
                "label": node.label,
                "steps": props.get("steps", []),
                "properties": props,
                "active": props.get("active", True),
            }
        except KeyError as exc:
            raise HTTPException(404, f"Node {node_id} not found") from exc

    @router.delete("/procedures/{node_id}")
    async def delete_procedure(
        node_id: str,
        request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> dict[str, str]:
        """Delete a procedural node and cascade-delete its edges."""
        procedural = agent._orchestrator.get_layer(MemoryLayer.PROCEDURAL)
        if procedural is None:
            raise HTTPException(404, "Procedural layer not available")
        memory_scope = scope.to_memory_scope()
        existing = await procedural._graph.get_node(  # type: ignore[union-attr]
            memory_scope, NodeId(node_id),
        )
        if existing is None:
            raise HTTPException(404, f"Node {node_id} not found")
        await procedural._graph.delete_node(  # type: ignore[union-attr]
            memory_scope, NodeId(node_id),
        )
        _emit_router_audit(
            request, scope,
            action="delete_procedure",
            resource_type="procedure",
            resource_id=node_id,
            metadata={"label": str(existing.label)},
        )
        return {"deleted": node_id}

    @router.post("/procedures/deduplicate")
    async def deduplicate_procedures(
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> dict[str, object]:
        """Merge semantically similar procedural nodes for the current tenant.

        Scans all procedural nodes and greedily merges pairs whose textual
        similarity is >= 0.75 (the default SemanticMerge threshold).  Absorbed
        duplicate nodes are deleted; canonical nodes are updated in-place.

        Returns:
            JSON object with ``merged`` (count of absorbed nodes) and
            ``remaining`` (list of surviving canonical procedure dicts).
        """
        from symfonic.memory.janitor import SemanticMerge

        procedural = agent._orchestrator.get_layer(MemoryLayer.PROCEDURAL)
        if procedural is None:
            raise HTTPException(404, "Procedural layer not available")
        memory_scope = scope.to_memory_scope()
        try:
            janitor = SemanticMerge()
            merged_count, remaining_nodes = await janitor.deduplicate_all(
                memory_scope, procedural._graph  # type: ignore[union-attr]
            )
            remaining = [
                {
                    "id": str(n.id),
                    "label": str(n.label),
                    "content": n.properties.get("content", n.label),
                    "steps": n.properties.get("steps", []),
                    "active": n.properties.get("active", True),
                    "importance": n.importance,
                }
                for n in remaining_nodes
            ]
            return {"merged": merged_count, "remaining": remaining}
        except Exception as exc:
            raise HTTPException(status_code=500, detail="Deduplication failed") from exc

    @router.post("/procedures/{node_id}/toggle")
    async def toggle_procedure(
        node_id: str,
        request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
    ) -> dict[str, Any]:
        """Toggle a procedure's active flag (true <-> false)."""
        procedural = agent._orchestrator.get_layer(MemoryLayer.PROCEDURAL)
        if procedural is None:
            raise HTTPException(404, "Procedural layer not available")
        memory_scope = scope.to_memory_scope()

        existing = await procedural._graph.get_node(  # type: ignore[union-attr]
            memory_scope, NodeId(node_id),
        )
        if existing is None:
            raise HTTPException(404, f"Node {node_id} not found")

        merged_props = dict(existing.properties or {})
        current_active = merged_props.get("active", True)
        merged_props["active"] = not current_active
        merged_props["_last_edited_by"] = "user_toggle"

        node = await procedural._graph.update_node(  # type: ignore[union-attr]
            memory_scope, NodeId(node_id),
            {"properties": merged_props},
        )
        _emit_router_audit(
            request, scope,
            action="update_procedure",
            resource_type="procedure",
            resource_id=node_id,
            metadata={"fields": ["active"], "new_active": not current_active},
        )
        props = node.properties or {}
        return {
            "id": str(node.id),
            "label": node.label,
            "active": props.get("active", True),
            "properties": props,
        }

    # ------------------------------------------------------------------
    # Memory consolidation (Deep Sleep)
    # ------------------------------------------------------------------

    @router.post("/memory/consolidate")
    async def consolidate_memory(
        request: Request,
        scope: FrameworkTenantScope = Depends(get_tenant_scope),  # noqa: B008
        _budget: None = Depends(check_budget_before_llm),  # noqa: B008
    ) -> dict[str, Any]:
        """Trigger manual deep-sleep consolidation for the tenant.

        Replays recent traces, strengthens recurring nodes, prunes
        orphans, generates meta-nodes from clusters, updates SOUL
        schema from user corrections, and writes any pending inferred
        edges to the graph.

        Accepts an optional JSON body::

            {
                "pending_connections": [
                    {"source": "NodeA", "target": "NodeB", "relationship": "ASSOCIATED"}
                ]
            }

        ``pending_connections`` is typically obtained from the
        ``activation_log.pending_connections`` field returned by ``/chat``.
        """
        from symfonic.core.learning.consolidation import SleepConsolidator

        semantic = agent._orchestrator.get_layer(MemoryLayer.SEMANTIC)
        if semantic is None or not hasattr(semantic, "_graph"):
            raise HTTPException(404, "Semantic layer not available")

        # Parse optional body (pending_connections from spreading activation)
        pending_connections: list[dict[str, Any]] | None = None
        try:
            body = await request.json()
            if isinstance(body, dict):
                raw = body.get("pending_connections")
                if isinstance(raw, list):
                    pending_connections = raw
                    logger.info(
                        "Consolidate request received %d pending_connections for tenant=%s",
                        len(pending_connections),
                        scope.tenant_id,
                    )
        except (json.JSONDecodeError, KeyError, TypeError, AttributeError):
            pass  # Body is optional; proceed without pending connections

        memory_scope = scope.to_memory_scope()

        # Pass episodic layer if available (enables Phase 10)
        episodic = agent._orchestrator.get_layer(MemoryLayer.EPISODIC)
        # Pass procedural layer if available (enables Phase 12)
        procedural = agent._orchestrator.get_layer(MemoryLayer.PROCEDURAL)
        consolidator = SleepConsolidator(
            semantic._graph,  # type: ignore[union-attr]
            episodic_layer=episodic,
            procedural_layer=procedural,
            promotion_min_pattern_count=getattr(
                agent._config, "promotion_min_pattern_count", 3,
            ),
            promotion_recency_days=getattr(
                agent._config, "promotion_recency_days", 30,
            ),
            promotion_max_drafts_per_run=getattr(
                agent._config, "promotion_max_drafts_per_run", 5,
            ),
            # v7.4.7 Jarvio Ask 9 PR-A: tool-call fallback opt-in.
            promotion_use_tool_calls_fallback=getattr(
                agent._config, "phase_12_action_type_from_tool_calls", False,
            ),
            # v7.7.2 Jarvio fabrication-promotion ask: default-off
            # filter for assistant-narrated promotion.
            promotion_promote_assistant_content=getattr(
                agent._config, "phase_12_promote_assistant_content", False,
            ),
            # v7.6 Jarvio Ask 9 Option A: LLM-backed Phase 12 extractor.
            # Default-off; wire the agent's bound chat model so the
            # factory can instantiate ``LlmProceduralExtractor``.
            phase_12_use_llm_extractor=getattr(
                agent._config, "phase_12_use_llm_extractor", False,
            ),
            phase_12_llm_model=getattr(
                agent._config, "phase_12_llm_model", "claude-haiku-4-5",
            ),
            phase_12_llm_max_episodes_per_run=getattr(
                agent._config, "phase_12_llm_max_episodes_per_run", 100,
            ),
            phase_12_llm_max_drafts_per_run=getattr(
                agent._config, "phase_12_llm_max_drafts_per_run", 5,
            ),
            chat_model=agent.get_chat_model("consolidation"),
            episodic_summarization_max_entries=getattr(
                agent._config, "episodic_summarization_max_entries", 100,
            ),
            episodic_summarization_batch_size=getattr(
                agent._config, "episodic_summarization_batch_size", 50,
            ),
            phase1_spreading_weight=getattr(
                agent._config, "phase1_spreading_weight", 0.5,
            ),
            synthetic_link_min_co_count=getattr(
                agent._config, "synthetic_link_min_co_count", 2,
            ),
            # v7.2 Roadmap Item 12 -- EntityLinker phase (default-off).
            enable_entity_linker=getattr(
                agent._config, "enable_entity_linker", False,
            ),
            entity_linker_extractor_kind=getattr(
                agent._config, "entity_linker_extractor", "regex",
            ),
            entity_linker_min_mention_count=getattr(
                agent._config, "entity_linker_min_mention_count", 2,
            ),
            entity_linker_max_episodics_per_run=getattr(
                agent._config, "entity_linker_max_episodics_per_run", 200,
            ),
            entity_linker_confidence_threshold=getattr(
                agent._config, "entity_linker_confidence_threshold", 0.5,
            ),
        )
        soul_schema = (
            dict(agent._config.domain.soul_schema)
            if agent._config.domain.soul_schema
            else None
        )
        try:
            report = await consolidator.run(
                memory_scope,
                soul_schema=soul_schema,
                pending_connections=pending_connections,
            )
            return report.to_dict()
        except Exception as exc:
            raise HTTPException(
                status_code=500,
                detail="Consolidation failed",
            ) from exc

    # ------------------------------------------------------------------
    # Memory-create sub-router (v6.1.4 — POST /memories/{layer})
    # ------------------------------------------------------------------
    from symfonic.agent.fastapi.memory_create_router import (
        create_memory_create_router,
    )

    memory_create_router = create_memory_create_router(agent)
    router.include_router(memory_create_router)

    # ------------------------------------------------------------------
    # Graph sub-router (neighborhood, pathfinding, edges, clusters)
    # ------------------------------------------------------------------
    from symfonic.agent.fastapi.graph_router import create_graph_router

    graph_router = create_graph_router(agent)
    router.include_router(graph_router)

    # ------------------------------------------------------------------
    # Graph maintenance sub-router (bulk ops, audit, prune)
    # ------------------------------------------------------------------
    from symfonic.agent.fastapi.graph_maintenance_router import (
        create_graph_maintenance_router,
    )

    maintenance_router = create_graph_maintenance_router(agent)
    router.include_router(maintenance_router)

    # ------------------------------------------------------------------
    # Tenant privacy sub-router (GDPR Art. 17 + Art. 20)
    # ------------------------------------------------------------------
    from symfonic.agent.fastapi.tenant_privacy_router import (
        create_tenant_privacy_router,
    )

    privacy_router = create_tenant_privacy_router(agent)
    router.include_router(privacy_router)

    # ------------------------------------------------------------------
    # Metrics sub-router (token usage / cost dashboard) -- opt-in
    # ------------------------------------------------------------------
    if agent.metrics_collector is not None:
        from symfonic.agent.fastapi.metrics_router import create_metrics_router

        metrics_router = create_metrics_router(agent.metrics_collector, prefix="")
        router.include_router(metrics_router)

    return router