kind: AdaptiveDialog
beginDialog:
  kind: OnRecognizedIntent
  id: trigger_Y6u2Pf
  intent:
    displayName: Build a Word technical-design draft
    triggerQueries:
      - Create a Word technical design from my notes
      - Build technical documentation
      - Turn requirements into a Word document
      - Draft a technical design document
      - Document this solution
      - Resume my technical documentation draft
      - Retry my Word draft
  actions:
    - kind: SetVariable
      id: set_U2q7Ms
      variable: init:Topic.InitialRequest
      value: =System.Activity.Text
    - kind: SetVariable
      id: set_K8z2Vn
      variable: init:Topic.IsNewGeneration
      value: =false
    - kind: SetVariable
      id: set_pW6k2Rt
      variable: init:Topic.NotesAuthorisedAndRedacted
      value: =false

    - kind: ConditionGroup
      id: condition_S9e4Dx
      conditions:
        - id: branch_C4m8Lq
          condition: =!IsBlank(Global.TdbDraftJson)
          actions:
            - kind: Question
              id: question_H7p2Vc
              variable: init:Topic.ResumeDraft
              prompt: There is a validated draft in this conversation. Resume it for review, refinement or Word creation? Choose No to start a new document.
              entity: BooleanPrebuiltEntity
              alwaysPrompt: true
              interruptionPolicy:
                allowInterruption: false
            - kind: ConditionGroup
              id: condition_L5k9Ua
              conditions:
                - id: branch_N8r3Qd
                  condition: =Topic.ResumeDraft = true
                  actions:
                    - kind: SetVariable
                      id: set_P2f6Jw
                      variable: init:Topic.RawDraft
                      value: =Global.TdbDraftJson
                    - kind: GotoAction
                      id: goto_F8v4Ba
                      actionId: condition_vR6k9Xa

    - kind: SendActivity
      id: send_K3w7Rt
      activity: |-
        I will use a dedicated AI Prompt drafting flow to turn your facts into eighteen narrative fields and five structured tables, then use the fixed Word template TDB-TECHNICAL-DESIGN-002 v0.2. It is a PROPOSED POC STANDARD; every output remains Draft 0.2 for human review. The drafting flow creates no file. Word creation requires your separate confirmation. I do not publish it or change sharing permissions.

        Keep this to one technical design and no more than 12,000 characters of source notes in total. Nothing is silently truncated. Do not include passwords, keys or tokens.

    - kind: Question
      id: question_B7t3Za
      variable: init:Topic.Intake
      prompt: |-
        I have kept your initial request. Add any missing project/service name, purpose, intended audience and technical notes in one reply. Include the document owner if known, and source names/URLs only when real.

        If those details are already in your request, reply "use my request". If a detail is unknown, say so; I will record a confirmation gap rather than invent it. Type "cancel" to stop.
      entity: StringPrebuiltEntity
      alwaysPrompt: true
      interruptionPolicy:
        allowInterruption: false

    - kind: ConditionGroup
      id: condition_Z6c9Dy
      conditions:
        - id: branch_R3w8Fc
          condition: =Lower(Trim(Topic.Intake)) = "cancel"
          actions:
            - kind: SendActivity
              id: send_J5n2Vk
              activity: Stopped. No new Word file was requested. Any previously validated conversation draft is unchanged.
            - kind: EndDialog
              id: end_U9m4Pa

    - kind: SetVariable
      id: set_A6n2Ex
      variable: init:Topic.ProposedEvidence
      value: =Topic.InitialRequest & Char(10) & Char(10) & Topic.Intake

    - kind: ConditionGroup
      id: condition_D9k5Rs
      conditions:
        - id: branch_X3v7Lt
          condition: =Len(Topic.ProposedEvidence) > 12000
          actions:
            - kind: SendActivity
              id: send_Y4q8Ec
              activity: The source notes exceed this POC's 12,000-character intake limit. I have not shortened them or generated a file. Please scope the notes to one design or split the work into documents, then start a new request.
            - kind: EndDialog
              id: end_T2m6Hw

    - kind: Question
      id: question_M7b3Kn
      variable: init:Topic.SafeNotes
      prompt: Confirm that the notes contain no passwords, API keys, private keys, connection tokens or other credentials, and that you are authorised to use these facts for this POC draft.
      entity: BooleanPrebuiltEntity
      alwaysPrompt: true
      interruptionPolicy:
        allowInterruption: false

    - kind: ConditionGroup
      id: condition_V8p4Qa
      conditions:
        - id: branch_F5t9Lu
          condition: =Topic.SafeNotes <> true
          actions:
            - kind: SendActivity
              id: send_H2x6Dj
              activity: No generation or file creation was requested. Remove any credentials and start again with authorised, redacted notes. This action does not delete messages already sent to chat; use your normal incident process if a real secret was exposed.
            - kind: EndDialog
              id: end_Q4e8Mb

    - kind: SetVariable
      id: set_G8y3Pr
      variable: Global.TdbEvidence
      value: =Topic.ProposedEvidence
    - kind: SetVariable
      id: set_nF8r4Yc
      variable: Topic.NotesAuthorisedAndRedacted
      value: =Topic.SafeNotes
    - kind: SetVariable
      id: set_E7c4Wm
      variable: Global.TdbDraftJson
      value: =""
    - kind: SetVariable
      id: set_N2d6Vf
      variable: Global.TdbRevision
      value: =0

    - kind: SetVariable
      id: setRevision_U8j4Ar
      variable: init:Topic.CandidateRevision
      value: =Global.TdbRevision + 1
    - kind: SetVariable
      id: set_F4y9Lr
      variable: Topic.IsNewGeneration
      value: =true
    - kind: ConditionGroup
      id: condition_sJ3p7Vu
      conditions:
        - id: branch_hQ5d8Mf
          condition: =Topic.NotesAuthorisedAndRedacted <> true
          actions:
            - kind: SendActivity
              id: send_tC9w2Kb
              activity: Drafting requires your explicit confirmation that these notes are authorised and redacted. No drafting or Word creation was requested.
            - kind: EndDialog
              id: end_mE4x6Dz
    - kind: SendActivity
      id: send_W6m3Fy
      activity: I am requesting the controlled narratives and tables from the dedicated AI Prompt flow using your source notes as untrusted evidence. Its trusted playbook, UK date and fixed Draft 0.2 govern the draft. Unsupported facts must remain confirmation gaps. This step creates no Word file.

    - kind: InvokeFlowAction
      id: flow_qL7v3Na
      displayName: Draft structured content using the dedicated AI Prompt v0.2
      input:
        binding:
          text: =Global.TdbEvidence
          boolean: =Topic.NotesAuthorisedAndRedacted
      output:
        binding:
          status: Topic.PromptStatus
          contentjson: Topic.PromptContentJson
          prepareddate: Topic.PromptPreparedDate
          draftversion: Topic.PromptDraftVersion
          modelname: Topic.PromptModelName
          finishreason: Topic.PromptFinishReason
          message: Topic.PromptMessage
          requestid: Topic.PromptRequestId
      flowId: 6a4a0ccd-e93f-48eb-934f-7174a620e168

    - kind: SetVariable
      id: set_zH2k9Ws
      variable: Topic.NotesAuthorisedAndRedacted
      value: =false
    - kind: ConditionGroup
      id: condition_aD8m5Jq
      conditions:
        - id: branch_uV4p7Bc
          condition: =Topic.PromptStatus <> "succeeded" || IsBlank(Trim(Topic.PromptContentJson)) || IsBlank(Topic.PromptPreparedDate) || Topic.PromptDraftVersion <> "Draft 0.2" || Topic.PromptFinishReason <> "stop"
          actions:
            - kind: SendActivity
              id: send_fN6r3Yt
              activity: |-
                Draft generation failed or the drafting response could not be verified. No returned draft will be parsed, repaired or sent for Word creation.

                Drafting status: {Topic.PromptStatus}
                Message: {Topic.PromptMessage}
                Model: {Topic.PromptModelName}
                Finish reason: {Topic.PromptFinishReason}
                Request ID: {Topic.PromptRequestId}

                No Word renderer was called. Any previously validated draft remains unchanged. Current source notes remain in this conversation. Resume an existing draft or start a new request with authorised, redacted notes; there is no automatic retry.
            - kind: EndDialog
              id: end_bK9w4Xe
    - kind: SetVariable
      id: set_yP3c8Lu
      variable: Topic.RawDraft
      value: =Topic.PromptContentJson

    # Resume and new generation share validation. The original JSON is never rebuilt.
    - kind: ConditionGroup
      id: condition_vR6k9Xa
      conditions:
        - id: branch_eG2n7Qd
          condition: =IsBlank(Trim(Topic.RawDraft)) || Len(Topic.RawDraft) > 100000
          actions:
            - kind: SendActivity
              id: send_rM8u4Fs
              activity: The draft response must be nonblank JSON within the 100,000-character renderer limit. No file was requested, no content was truncated, and no previously validated draft was overwritten.
            - kind: EndDialog
              id: end_cT5p9Vh

    - kind: ParseValue
      id: parse_Q5r8Vm
      variable: Topic.Draft
      value: =Topic.RawDraft
      errorPolicy: DefaultBlank
      valueType:
        kind: Record
        properties:
          DocumentTitle: String
          ProjectName: String
          DocumentOwner: String
          PreparedDate: String
          DocumentVersion: String
          IntendedAudience: String
          ExecutiveSummary: String
          PurposeAndScope: String
          Requirements: String
          Architecture: String
          InterfacesAndData: String
          SecurityAndCompliance: String
          DeploymentAndRollback: String
          OperationsAndSupport: String
          TestingAndAcceptance: String
          RisksAssumptionsDecisions: String
          SourcesAndReferences: String
          ReviewActions: String
          RequirementRows:
            type:
              kind: Table
              properties:
                RequirementId: String
                RequirementDescription: String
                RequirementPriority: String
                RequirementEvidence: String
          ComponentRows:
            type:
              kind: Table
              properties:
                ComponentName: String
                ComponentDescription: String
                ComponentDependencies: String
          InterfaceRows:
            type:
              kind: Table
              properties:
                InterfaceName: String
                InterfaceSource: String
                InterfaceTarget: String
                InterfaceDescription: String
          TestRows:
            type:
              kind: Table
              properties:
                TestId: String
                TestDescription: String
                TestExpectedResult: String
                TestStatus: String
          RiskRows:
            type:
              kind: Table
              properties:
                RiskId: String
                RiskDescription: String
                RiskMitigation: String
                RiskOwnerStatus: String

    - kind: SetVariable
      id: set_D7q2Nh
      variable: init:Topic.ExactFieldSet
      value: |-
        =IfError(
          CountRows(ColumnNames(ParseJSON(Topic.RawDraft))) = 23 &&
          CountIf(ColumnNames(ParseJSON(Topic.RawDraft)),
            !(Value in ["DocumentTitle", "ProjectName", "DocumentOwner", "PreparedDate", "DocumentVersion", "IntendedAudience", "ExecutiveSummary", "PurposeAndScope", "Requirements", "Architecture", "InterfacesAndData", "SecurityAndCompliance", "DeploymentAndRollback", "OperationsAndSupport", "TestingAndAcceptance", "RisksAssumptionsDecisions", "SourcesAndReferences", "ReviewActions", "RequirementRows", "ComponentRows", "InterfaceRows", "TestRows", "RiskRows"])
          ) = 0,
          false
        )

    - kind: SetVariable
      id: set_B2v7Nd
      variable: init:Topic.Fields
      value: |-
        =Table(
          {Name: "DocumentTitle", Content: Topic.Draft.DocumentTitle, Limit: 180},
          {Name: "ProjectName", Content: Topic.Draft.ProjectName, Limit: 180},
          {Name: "DocumentOwner", Content: Topic.Draft.DocumentOwner, Limit: 180},
          {Name: "PreparedDate", Content: Topic.Draft.PreparedDate, Limit: 40},
          {Name: "DocumentVersion", Content: Topic.Draft.DocumentVersion, Limit: 40},
          {Name: "IntendedAudience", Content: Topic.Draft.IntendedAudience, Limit: 240},
          {Name: "ExecutiveSummary", Content: Topic.Draft.ExecutiveSummary, Limit: 2200},
          {Name: "PurposeAndScope", Content: Topic.Draft.PurposeAndScope, Limit: 3000},
          {Name: "Requirements", Content: Topic.Draft.Requirements, Limit: 2000},
          {Name: "Architecture", Content: Topic.Draft.Architecture, Limit: 3000},
          {Name: "InterfacesAndData", Content: Topic.Draft.InterfacesAndData, Limit: 2200},
          {Name: "SecurityAndCompliance", Content: Topic.Draft.SecurityAndCompliance, Limit: 2200},
          {Name: "DeploymentAndRollback", Content: Topic.Draft.DeploymentAndRollback, Limit: 2200},
          {Name: "OperationsAndSupport", Content: Topic.Draft.OperationsAndSupport, Limit: 2200},
          {Name: "TestingAndAcceptance", Content: Topic.Draft.TestingAndAcceptance, Limit: 1600},
          {Name: "RisksAssumptionsDecisions", Content: Topic.Draft.RisksAssumptionsDecisions, Limit: 1800},
          {Name: "SourcesAndReferences", Content: Topic.Draft.SourcesAndReferences, Limit: 1800},
          {Name: "ReviewActions", Content: Topic.Draft.ReviewActions, Limit: 2200}
        )

    - kind: SetVariable
      id: set_N8g4Ua
      variable: init:Topic.NarrativesAreStrings
      value: |-
        =IfError(
          CountIf(
            Topic.Fields,
            !StartsWith(JSON(Column(ParseJSON(Topic.RawDraft), Name)), Char(34)) ||
            !EndsWith(JSON(Column(ParseJSON(Topic.RawDraft), Name)), Char(34))
          ) = 0,
          false
        )

    - kind: SetVariable
      id: set_P9w4Yb
      variable: init:Topic.InvalidFields
      value: =Filter(Topic.Fields, !IsMatch(Content, "\S", MatchOptions.Contains) || Len(Content) > Limit)

    # Backend strict validation remains authoritative; raw checks also protect resumed
    # content from ParseValue coercion or silent removal of unknown row properties.
    - kind: SetVariable
      id: set_jW4q8Nd
      variable: init:Topic.RowContracts
      value: |-
        =Table(
          {Name: "RequirementRows", Limit: 12, Columns: Table(
            {Name: "RequirementId", Limit: 50},
            {Name: "RequirementDescription", Limit: 700},
            {Name: "RequirementPriority", Limit: 120},
            {Name: "RequirementEvidence", Limit: 350})},
          {Name: "ComponentRows", Limit: 8, Columns: Table(
            {Name: "ComponentName", Limit: 160},
            {Name: "ComponentDescription", Limit: 700},
            {Name: "ComponentDependencies", Limit: 400})},
          {Name: "InterfaceRows", Limit: 8, Columns: Table(
            {Name: "InterfaceName", Limit: 160},
            {Name: "InterfaceSource", Limit: 200},
            {Name: "InterfaceTarget", Limit: 200},
            {Name: "InterfaceDescription", Limit: 700})},
          {Name: "TestRows", Limit: 10, Columns: Table(
            {Name: "TestId", Limit: 50},
            {Name: "TestDescription", Limit: 600},
            {Name: "TestExpectedResult", Limit: 600},
            {Name: "TestStatus", Limit: 180})},
          {Name: "RiskRows", Limit: 8, Columns: Table(
            {Name: "RiskId", Limit: 50},
            {Name: "RiskDescription", Limit: 600},
            {Name: "RiskMitigation", Limit: 600},
            {Name: "RiskOwnerStatus", Limit: 300})}
        )
    - kind: SetVariable
      id: set_hV7m2Br
      variable: init:Topic.InvalidTables
      value: |-
        =Filter(
          Topic.RowContracts As contract,
          IfError(
            With({rawRows: Column(ParseJSON(Topic.RawDraft), contract.Name)},
              !StartsWith(JSON(rawRows), "[") ||
              !EndsWith(JSON(rawRows), "]") ||
              CountRows(Table(rawRows)) < 1 ||
              CountRows(Table(rawRows)) > contract.Limit ||
              CountIf(Table(rawRows) As row,
                CountRows(ColumnNames(row.Value)) <> CountRows(contract.Columns) ||
                CountIf(contract.Columns As col,
                  With({cell: Column(row.Value, col.Name)},
                    !StartsWith(JSON(cell), Char(34)) ||
                    !EndsWith(JSON(cell), Char(34)) ||
                    !IsMatch(Text(cell), "\S", MatchOptions.Contains) ||
                    Len(Text(cell)) > col.Limit
                  )
                ) > 0
              ) > 0
            ),
            true
          )
        )

    - kind: ConditionGroup
      id: condition_K9c3Rs
      conditions:
        - id: branch_E6v2Ta
          condition: =Topic.ExactFieldSet <> true || Topic.NarrativesAreStrings <> true || CountRows(Topic.InvalidFields) > 0 || CountRows(Topic.InvalidTables) > 0 || Topic.Draft.DocumentVersion <> "Draft 0.2"
          actions:
            - kind: SendActivity
              id: send_Q7z3Jf
              activity: |-
                The content is not a complete valid v0.2 draft. It must contain exactly eighteen nonblank string fields and five nonempty typed row arrays within their bounds, with no unknown keys and DocumentVersion exactly Draft 0.2. No Word file was requested, no content was repaired or shortened, and the stored draft was not overwritten.

                Fields needing correction: {Concat(Topic.InvalidFields, Name, ", ")}.
                Tables needing correction: {Concat(Topic.InvalidTables, Name, ", ")}.

                For a legacy eighteen-field draft, start a new request and choose No when offered resume, then confirm the authorised, redacted notes for regeneration. Do not manually repair the model JSON. Otherwise scope or correct the source notes and start again. A previously validated v0.2 draft remains available by saying "resume my technical documentation draft". Current source notes remain in this conversation until Start Over.
            - kind: EndDialog
              id: end_C4k8Hu

    - kind: ConditionGroup
      id: condition_P6b9Tf
      conditions:
        - id: branch_K5q2Ds
          condition: =Topic.IsNewGeneration = true
          actions:
            - kind: ConditionGroup
              id: condition_kP4s9Lg
              conditions:
                - id: branch_wB8n3Ye
                  condition: =Topic.Draft.PreparedDate <> Topic.PromptPreparedDate || Topic.Draft.DocumentVersion <> Topic.PromptDraftVersion
                  actions:
                    - kind: SendActivity
                      id: send_dU6r2Mc
                      activity: |-
                        The draft's control values do not match the drafting flow's trusted UK date and fixed Draft 0.2. I will not repair them or request a Word file. Any previously validated draft remains unchanged.

                        Drafting message: {Topic.PromptMessage}
                        Request ID: {Topic.PromptRequestId}
                    - kind: EndDialog
                      id: end_gF7v5Ka
            - kind: SetVariable
              id: set_E4v8Cy
              variable: Global.TdbRevision
              value: =Topic.CandidateRevision

    # TdbRevision counts accepted conversation generations only, never document versions.
    # Preserve the complete returned string, including every table cell, without reserialization.
    - kind: SetVariable
      id: set_X8d4Pt
      variable: Global.TdbDraftJson
      value: =Topic.RawDraft

    - kind: SendActivity
      id: send_U7q2Mw
      activity: |-
        Draft preview: {Topic.Draft.DocumentTitle}
        Project: {Topic.Draft.ProjectName}
        Owner: {Topic.Draft.DocumentOwner}
        Audience: {Topic.Draft.IntendedAudience}
        Prepared date (UK): {Topic.Draft.PreparedDate}
        Document version: {Topic.Draft.DocumentVersion}
        Template: TDB-TECHNICAL-DESIGN-002 v0.2 — PROPOSED POC STANDARD

        Structured rows: {CountRows(Topic.Draft.RequirementRows)} requirements; {CountRows(Topic.Draft.ComponentRows)} components; {CountRows(Topic.Draft.InterfaceRows)} interfaces; {CountRows(Topic.Draft.TestRows)} tests; {CountRows(Topic.Draft.RiskRows)} risks. Choose review to read every narrative and row before creating a Word draft.

        {Topic.Draft.ExecutiveSummary}

    - kind: SendActivity
      id: send_A3v9Ge
      activity: |-
        Review actions — not an approval:

        {Topic.Draft.ReviewActions}

    - kind: Question
      id: question_D6y2Lf
      variable: init:Topic.NextStep
      prompt: Reply "review" to read all eighteen narratives and every row of the five tables, "refine" to replace the source notes and regenerate, "create" to request an editable Word draft, or "cancel" to stop. Creation requires separate confirmation and does not approve or publish the content.
      entity: StringPrebuiltEntity
      alwaysPrompt: true
      validation: =Lower(Trim(Topic.NextStep)) in ["review", "refine", "create", "cancel"]
      invalidPrompt: Please reply review, refine, create or cancel.
      interruptionPolicy:
        allowInterruption: false

    - kind: ConditionGroup
      id: condition_M4u8Zn
      conditions:
        - id: branch_W3n7Ef
          condition: =Lower(Trim(Topic.NextStep)) = "review"
          actions:
            - kind: Foreach
              id: each_F6c2Vr
              items: =Topic.Fields
              value: Topic.ReviewField
              actions:
                - kind: SendActivity
                  id: send_R8b4Yu
                  activity: |-
                    {Topic.ReviewField.Name}

                    {Topic.ReviewField.Content}
            - kind: Foreach
              id: each_yJ8d3Vp
              items: =Topic.Draft.RequirementRows
              value: Topic.ReviewRequirement
              actions:
                - kind: SendActivity
                  id: send_kR5x9Fb
                  activity: |-
                    Requirements table — {Topic.ReviewRequirement.RequirementId}
                    Requirement / acceptance: {Topic.ReviewRequirement.RequirementDescription}
                    Priority: {Topic.ReviewRequirement.RequirementPriority}
                    Evidence / status: {Topic.ReviewRequirement.RequirementEvidence}
            - kind: Foreach
              id: each_aW2n6Ls
              items: =Topic.Draft.ComponentRows
              value: Topic.ReviewComponent
              actions:
                - kind: SendActivity
                  id: send_cM7u4Qz
                  activity: |-
                    Components table — {Topic.ReviewComponent.ComponentName}
                    Responsibility / description: {Topic.ReviewComponent.ComponentDescription}
                    Dependencies / gaps: {Topic.ReviewComponent.ComponentDependencies}
            - kind: Foreach
              id: each_pD9r5Jv
              items: =Topic.Draft.InterfaceRows
              value: Topic.ReviewInterface
              actions:
                - kind: SendActivity
                  id: send_tG3w8Nh
                  activity: |-
                    Interfaces table — {Topic.ReviewInterface.InterfaceName}
                    Source: {Topic.ReviewInterface.InterfaceSource}
                    Target: {Topic.ReviewInterface.InterfaceTarget}
                    Data / behaviour / gaps: {Topic.ReviewInterface.InterfaceDescription}
            - kind: Foreach
              id: each_vK6c2Yr
              items: =Topic.Draft.TestRows
              value: Topic.ReviewTest
              actions:
                - kind: SendActivity
                  id: send_bE8p4Ua
                  activity: |-
                    Tests table — {Topic.ReviewTest.TestId}
                    Scenario: {Topic.ReviewTest.TestDescription}
                    Expected result: {Topic.ReviewTest.TestExpectedResult}
                    Execution status: {Topic.ReviewTest.TestStatus}
            - kind: Foreach
              id: each_mQ4f7Zc
              items: =Topic.Draft.RiskRows
              value: Topic.ReviewRisk
              actions:
                - kind: SendActivity
                  id: send_xL9d3Pw
                  activity: |-
                    Risks table — {Topic.ReviewRisk.RiskId}
                    Risk / open decision: {Topic.ReviewRisk.RiskDescription}
                    Mitigation / action: {Topic.ReviewRisk.RiskMitigation}
                    Owner / status: {Topic.ReviewRisk.RiskOwnerStatus}
            - kind: GotoAction
              id: goto_N5p9Xh
              actionId: question_D6y2Lf

        - id: branch_H6t2Qa
          condition: =Lower(Trim(Topic.NextStep)) = "refine"
          actions:
            - kind: Question
              id: question_V3s7Lp
              variable: init:Topic.Refinement
              prompt: Supply a corrected, consolidated set of source notes for this design (maximum 12,000 characters). Include project, purpose, audience and any known owner. These replace the previous notes so withdrawn claims cannot linger. Retain facts and real sources you still need; label proposed changes and unknowns. Do not include secrets. Type "cancel" to return to review without changing the notes.
              entity: StringPrebuiltEntity
              alwaysPrompt: true
              validation: =Len(Topic.Refinement) <= 12000 && !IsBlank(Trim(Topic.Refinement))
              invalidPrompt: The replacement notes must be non-empty and at most 12,000 characters. Please scope or split them; I will not truncate content.
              interruptionPolicy:
                allowInterruption: false
            - kind: ConditionGroup
              id: condition_G4w8Cd
              conditions:
                - id: branch_M9n3Pk
                  condition: =Lower(Trim(Topic.Refinement)) = "cancel"
                  actions:
                    - kind: GotoAction
                      id: goto_E2v6Ry
                      actionId: question_D6y2Lf
            - kind: Question
              id: question_T8k3Bx
              variable: init:Topic.SafeRefinement
              prompt: Confirm that the replacement notes contain no credentials and that you are authorised to use them for this POC draft.
              entity: BooleanPrebuiltEntity
              alwaysPrompt: true
              interruptionPolicy:
                allowInterruption: false
            - kind: ConditionGroup
              id: condition_A5u9Jh
              conditions:
                - id: branch_L7e2Qw
                  condition: =Topic.SafeRefinement <> true
                  actions:
                    - kind: SendActivity
                      id: send_C2r8Mv
                      activity: The replacement notes were not accepted for generation. The previous validated draft is unchanged.
                    - kind: GotoAction
                      id: goto_J6x3Pa
                      actionId: question_D6y2Lf
            - kind: SetVariable
              id: set_R4b8Yk
              variable: Global.TdbEvidence
              value: =Topic.Refinement
            - kind: SetVariable
              id: set_eH5t8Cx
              variable: Topic.NotesAuthorisedAndRedacted
              value: =Topic.SafeRefinement
            - kind: GotoAction
              id: goto_Q2n7Vf
              actionId: setRevision_U8j4Ar

        - id: branch_P3f7Dc
          condition: =Lower(Trim(Topic.NextStep)) = "cancel"
          actions:
            - kind: SendActivity
              id: send_N4y8Wq
              activity: Stopped without requesting a Word file. The validated draft remains in this conversation for review or retry. Say "resume my technical documentation draft" to return, or "start over" to clear it.
            - kind: EndDialog
              id: end_B5m9Eu

    - kind: Question
      id: question_X7v3Nk
      variable: init:Topic.ConfirmRender
      prompt: Create a new Word DRAFT using TDB-TECHNICAL-DESIGN-002 v0.2, with these eighteen narratives and five tables, in the configured POC OneDrive folder with existing access only? This is not approval, publishing, or a change to permissions. Human proofreading, factual checks and Word layout review remain required.
      entity: BooleanPrebuiltEntity
      alwaysPrompt: true
      interruptionPolicy:
        allowInterruption: false

    - kind: ConditionGroup
      id: condition_Y2c6Ar
      conditions:
        - id: branch_U8k4Fg
          condition: =Topic.ConfirmRender <> true
          actions:
            - kind: GotoAction
              id: goto_L3p7Wd
              actionId: question_D6y2Lf

    - kind: ConditionGroup
      id: condition_H6e2Vs
      conditions:
        - id: branch_D7n4Qb
          condition: =Len(Global.TdbDraftJson) > 100000
          actions:
            - kind: SendActivity
              id: send_G3p8Xk
              activity: The encoded draft exceeds the renderer's 100,000-character limit. No file was requested and nothing was truncated. Choose refine and scope or split the document. The validated draft text remains in this conversation.
            - kind: GotoAction
              id: goto_W9r2Cf
              actionId: question_D6y2Lf

    - kind: SendActivity
      id: send_S8u3Pe
      activity: I am requesting a new editable Word draft using the pinned template. I will return a link only after the renderer confirms creation and verifies the file metadata.

    - kind: InvokeFlowAction
      id: flow_M6c2Yt
      displayName: Render validated narratives and tables using the pinned v0.2 Word template
      input:
        binding:
          text: TDB-TECHNICAL-DESIGN-002
          text_1: "0.2"
          text_2: =Global.TdbDraftJson
      output:
        binding:
          status: Topic.RenderStatus
          fileurl: Topic.RenderFileUrl
          fileid: Topic.RenderFileId
          filename: Topic.RenderFileName
          templateid: Topic.RenderTemplateId
          templateversion: Topic.RenderTemplateVersion
          warnings: Topic.RenderWarnings
          errorcode: Topic.RenderErrorCode
          message: Topic.RenderMessage
          requestid: Topic.RenderRequestId
      flowId: 0c4d7629-3f32-469b-a0a9-de294bd2a016

    - kind: ConditionGroup
      id: condition_V5x9Qa
      conditions:
        - id: branch_J7d3Nm
          condition: =Topic.RenderStatus = "succeeded" && !IsBlank(Topic.RenderFileUrl) && StartsWith(Topic.RenderFileUrl, "https://") && !IsBlank(Topic.RenderFileId) && !IsBlank(Topic.RenderFileName) && Topic.RenderTemplateId = "TDB-TECHNICAL-DESIGN-002" && Topic.RenderTemplateVersion = "0.2" && IsBlank(Topic.RenderErrorCode)
          actions:
            - kind: SendActivity
              id: send_C4w8Lr
              activity: |-
                Your editable Word DRAFT was created.

                [Open the Word draft]({Topic.RenderFileUrl})

                File: {Topic.RenderFileName}
                File ID: {Topic.RenderFileId}
                Template: {Topic.RenderTemplateId} v{Topic.RenderTemplateVersion} — PROPOSED POC STANDARD
                Prepared date (UK): {Topic.Draft.PreparedDate}
                Request ID: {Topic.RenderRequestId}

                {Topic.RenderWarnings}

                Human review is required: proofread the content, verify facts and sources, resolve proposed assumptions and open questions, and check Word layout. This is not an approved document and has not been published or newly shared.

      elseActions:
        - kind: SendActivity
          id: send_A9v2Kd
          activity: |-
            Word generation failed or the renderer response could not be verified. I cannot confirm a usable file and will not supply a link.

            Renderer status: {Topic.RenderStatus}
            Error code: {Topic.RenderErrorCode}
            Message: {Topic.RenderMessage}
            Request ID: {Topic.RenderRequestId}
            {Topic.RenderWarnings}

            The validated draft text remains in this conversation. Say "resume my technical documentation draft" to review or retry. If the save may have completed before the failure, check the configured Generated Drafts folder before retrying to avoid duplicate drafts.

            If the renderer reports an out-of-date PreparedDate, resume and choose refine, supply consolidated authorised notes and confirm regeneration. The drafting flow will compute a fresh UK date. I do not patch the saved JSON or automatically retry; the new draft needs review and separate file-creation consent again.

    - kind: EndDialog
      id: end_F8m4Ru
