{
  "updatedAt": "2025-12-24T08:53:12.894Z",
  "createdAt": "2025-12-23T09:30:25.763Z",
  "id": "mbX1lCt14Yi75gTE",
  "name": "Continue_Thread",
  "description": null,
  "active": false,
  "isArchived": false,
  "nodes": [
    {
      "parameters": {
        "inputSource": "passthrough"
      },
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "typeVersion": 1.1,
      "position": [
        6656,
        624
      ],
      "id": "cf49146a-7b65-4fe1-8882-9190f8ac80f3",
      "name": "ExecuteWorkflowTrigger"
    },
    {
      "parameters": {
        "jsCode": "// Prepare batch database queries for Execute_Queries sub-workflow\nconst ctx = $json.ctx;\n\nconst db_queries = [\n  {\n    key: 'history',\n    sql: `SELECT timestamp, role, text FROM thread_history \n          WHERE thread_id = $1 AND NOT (role = 'user' AND text = $2) \n          ORDER BY timestamp ASC LIMIT 20`,\n    params: [ctx.event.thread_id, ctx.event.clean_text]\n  },\n  {\n    key: 'north_star',\n    sql: `SELECT value FROM config WHERE key = 'north_star'`\n  },\n  {\n    key: 'activities',\n    sql: `SELECT \n            (data->>'timestamp')::timestamptz as timestamp,\n            data->>'category' as category,\n            data->>'description' as description\n          FROM projections\n          WHERE projection_type = 'activity'\n            AND status IN ('auto_confirmed', 'confirmed')\n          ORDER BY (data->>'timestamp')::timestamptz DESC\n          LIMIT 20`\n  },\n  {\n    key: 'notes',\n    sql: `SELECT \n            (data->>'timestamp')::timestamptz as timestamp,\n            data->>'category' as category,\n            data->>'text' as text\n          FROM projections\n          WHERE projection_type = 'note'\n            AND status IN ('auto_confirmed', 'confirmed')\n          ORDER BY (data->>'timestamp')::timestamptz DESC\n          LIMIT 10`\n  }\n];\n\nreturn {\n  json: {\n    ctx: {\n      ...ctx,\n      db_queries\n    }\n  }\n};",
        "mode": "runOnceForEachItem"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        6880,
        624
      ],
      "id": "prepare-db-queries",
      "name": "PrepareDbQueries"
    },
    {
      "parameters": {
        "workflowId": {
          "__rl": true,
          "value": "CgUAxK0i4YhrZ2Wp",
          "mode": "list",
          "cachedResultName": "Execute_Queries",
          "cachedResultUrl": "/workflow/CgUAxK0i4YhrZ2Wp"
        },
        "workflowInputs": {
          "mappingMode": "defineBelow",
          "value": {
            "ctx": "={{ $json.ctx }}"
          }
        },
        "options": {
          "waitForSubWorkflow": true
        }
      },
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.2,
      "position": [
        7104,
        624
      ],
      "id": "execute-queries-read",
      "name": "ExecuteQueries(read)"
    },
    {
      "parameters": {
        "jsCode": "// Build LLM context from Execute_Queries results\nconst ctx = $json.ctx;\nconst db = ctx.db || {};\n\n// Extract and sort conversation history\nconst history = (db.history?.rows || [])\n  .sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))\n  .map(item => ({\n    role: item.role,\n    text: item.text\n  }));\n\n// Extract north star\nconst northStar = db.north_star?.row?.value || 'Not set';\n\n// Extract activities\nconst activities = (db.activities?.rows || []).map(item => ({\n  timestamp: item.timestamp,\n  category: item.category,\n  description: item.description\n}));\n\n// Extract notes  \nconst notes = (db.notes?.rows || []).map(item => ({\n  timestamp: item.timestamp,\n  category: item.category,\n  text: item.text\n}));\n\nreturn {\n  json: {\n    ctx: {\n      ...ctx,\n      llm: {\n        ...ctx.llm,\n        north_star: northStar,\n        inference_start: Date.now(),\n        history: history,\n        activities: activities,\n        notes: notes\n      }\n    }\n  }\n};",
        "mode": "runOnceForEachItem"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        7328,
        624
      ],
      "id": "66722f6e-f428-4136-bc15-f60097699a36",
      "name": "BuildContext"
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=You are an AI life coach helping the user reflect, plan, and think deeply.\n\n## Context Available\n\n**User's Guiding Principle:** {{ $json.ctx.llm.north_star }}\n\nKeep this in mind when helping them, but don't mention it unless directly relevant to the conversation.\n\n**Recent Activities (Last 20)**\n{{ $json.ctx.llm.activities.map(act => `${DateTime.fromISO(act.timestamp).format(\"yyyy-MM-dd hh:mm\")} - ${act.description}`).join('\\n') }}\n\n**Recent Notes (Last 10)**\n{{ $json.ctx.llm.notes.map(n => `[${n.category}] ${n.text}`).join('\\n') }}\n\n## Instructions\n\n1. **Consider the full context**: conversation history, activities, and notes\n2. **Provide grounded insights**: Reference specific activities or notes when relevant\n3. **Be conversational**: This is an ongoing dialogue, not a new conversation\n4. **Ask clarifying questions**: Help them think deeper when appropriate\n5. **Be concise**: 3-5 sentences, respect their time\n6. **Don't force connections**: Only mention the guiding principle if it's naturally relevant to what they're asking about\n\n## Style\n- Warm and supportive\n- Natural and conversational\n- Focus on what they're asking, not on fitting everything into a grand narrative\n\n## Conversation History\n{{ $json.ctx.llm.history.map(msg => `${msg.role.toUpperCase()}: ${msg.text}`).join('\\n\\n') }}\n\nUSER: {{ $json.ctx.event.clean_text }}\n\nASSISTANT:",
        "needsFallback": true,
        "batching": {}
      },
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.7,
      "position": [
        7552,
        748
      ],
      "id": "4119f733-a0a8-4c97-bcf3-a67ab535c4b5",
      "name": "GenerateResponse"
    },
    {
      "parameters": {
        "model": "xiaomi/mimo-v2-flash:free",
        "options": {
          "temperature": 0.7
        }
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "typeVersion": 1,
      "position": [
        7560,
        972
      ],
      "id": "120ceee9-00cb-4175-8df8-57f862e218fd",
      "name": "MimoV2Flash",
      "credentials": {
        "openRouterApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "model": "nvidia/nemotron-nano-9b-v2:free",
        "options": {
          "temperature": 0.7
        }
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "typeVersion": 1,
      "position": [
        7688,
        972
      ],
      "id": "9c28edb3-a048-474e-8217-915ddee94e23",
      "name": "NemotronNano9b",
      "credentials": {
        "openRouterApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "resource": "message",
        "guildId": {
          "__rl": true,
          "value": "={{ $json.ctx.event.guild_id }}",
          "mode": "id"
        },
        "channelId": {
          "__rl": true,
          "value": "={{ $json.ctx.event.thread_id }}",
          "mode": "id"
        },
        "content": "={{ $json.ctx.llm.completion_text }}",
        "options": {}
      },
      "type": "n8n-nodes-base.discord",
      "typeVersion": 2,
      "position": [
        8352,
        528
      ],
      "id": "742d2510-b9ca-4252-9f4e-4d2c485050a9",
      "name": "PostToThread",
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "credentials": {
        "discordBotApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "react",
        "guildId": {
          "__rl": true,
          "value": "={{ $json.ctx.event.guild_id }}",
          "mode": "id"
        },
        "channelId": {
          "__rl": true,
          "value": "={{ $json.ctx.event.channel_id }}",
          "mode": "id"
        },
        "messageId": "={{ $json.ctx.event.message_id }}",
        "emoji": "=\ud83d\udcad"
      },
      "type": "n8n-nodes-base.discord",
      "typeVersion": 2,
      "position": [
        6880,
        96
      ],
      "id": "3d6f0aee-f86f-437e-aa57-0683b80c2ced",
      "name": "ReactWith\ud83d\udcad",
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "credentials": {
        "discordBotApi": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "method": "DELETE",
        "url": "=https://discord.com/api/v10/channels/{{ $json.ctx.event.channel_id }}/messages/{{ $json.ctx.event.message_id }}/reactions/\ud83d\udd35/@me",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "discordBotApi",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        6880,
        1152
      ],
      "id": "remove-blue-reaction-continue-chat",
      "name": "Remove\ud83d\udd35Reaction",
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "credentials": {
        "discordBotApi": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Prepare write queries for Execute_Queries (trace + projection)\nconst ctx = $json.ctx || {};\nconst response = ctx.llm?.completion_text || '';\nconst inferenceStart = ctx.llm?.inference_start || Date.now();\nconst durationMs = Date.now() - inferenceStart;\n\n// Build filled prompt (reconstructed from template)\nconst promptText = `You are an AI life coach helping the user reflect, plan, and think deeply.\n\n## Context Available\n\n**User's Guiding Principle:** ${ctx.llm?.north_star || '(not set)'}\n\n**Recent Activities (Last 20)**\n${(ctx.llm?.activities || []).map(act => `${act.timestamp} - ${act.description}`).join('\\n')}\n\n**Recent Notes (Last 10)**\n${(ctx.llm?.notes || []).map(n => `[${n.category}] ${n.text}`).join('\\n')}\n\n## Instructions\n...\n\n## Conversation History\n${(ctx.llm?.history || []).map(msg => `${msg.role.toUpperCase()}: ${msg.text}`).join('\\n\\n')}\n\n## Current Message\nThe user just said: \"${ctx.event?.clean_text || ''}\"\n\nRespond to their message now.`;\n\n// Format trace_chain for PostgreSQL uuid[] type\nconst traceChain = ctx.event?.trace_chain || [];\n\n// Build write queries with chaining\nconst db_queries = [\n  {\n    key: 'trace',\n    sql: `INSERT INTO traces (event_id, step_name, data, trace_chain)\n          VALUES (\n            $1::uuid,\n            'thread_response',\n            jsonb_build_object(\n              'input', jsonb_build_object(\n                'text', $2,\n                'thread_id', $3::text,\n                'history_length', $4::integer\n              ),\n              'prompt', $5,\n              'completion', $6,\n              'result', jsonb_build_object(\n                'response_length', $7::integer,\n                'referenced_activities', $8::integer,\n                'referenced_notes', $9::integer\n              ),\n              'model', 'xiaomi/mimo-v2-flash:free',\n              'duration_ms', $10::integer\n            ),\n            $11::uuid[]\n          )\n          RETURNING id, $11::uuid[] || id AS updated_trace_chain`,\n    params: [\n      ctx.event?.event_id,\n      ctx.event?.clean_text || '',\n      ctx.event?.thread_id,\n      (ctx.llm?.history || []).length,\n      promptText,\n      response,\n      response.length,\n      (ctx.llm?.activities || []).length,\n      (ctx.llm?.notes || []).length,\n      durationMs,\n      traceChain\n    ]\n  },\n  {\n    key: 'projection',\n    sql: `INSERT INTO projections (\n            event_id,\n            trace_id,\n            trace_chain,\n            projection_type,\n            status,\n            data,\n            timezone\n          )\n          VALUES (\n            $1::uuid,\n            $2::uuid,\n            $3::uuid[],\n            'thread_response',\n            'auto_confirmed',\n            jsonb_build_object(\n              'thread_id', $4,\n              'response_text', $5,\n              'role', 'assistant',\n              'timestamp', $6::timestamptz\n            ),\n            $7\n          )\n          RETURNING id`,\n    params: [\n      ctx.event?.event_id,\n      '$results.trace.row.id',\n      '$results.trace.row.updated_trace_chain',\n      ctx.event?.thread_id,\n      response,\n      ctx.event?.timestamp,\n      ctx.event?.timezone\n    ]\n  }\n];\n\nreturn {\n  json: {\n    ctx: {\n      ...ctx,\n      db_queries\n    }\n  }\n};",
        "mode": "runOnceForEachItem"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        8352,
        720
      ],
      "id": "prepare-write-queries",
      "name": "PrepareWriteQueries"
    },
    {
      "parameters": {
        "workflowId": {
          "__rl": true,
          "value": "CgUAxK0i4YhrZ2Wp",
          "mode": "list",
          "cachedResultName": "Execute_Queries",
          "cachedResultUrl": "/workflow/CgUAxK0i4YhrZ2Wp"
        },
        "workflowInputs": {
          "mappingMode": "defineBelow",
          "value": {
            "ctx": "={{ $json.ctx }}"
          }
        },
        "options": {
          "waitForSubWorkflow": true
        }
      },
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.2,
      "position": [
        8576,
        720
      ],
      "id": "execute-queries-write",
      "name": "ExecuteQueries(write)"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "llm-completion",
              "name": "ctx.llm.completion_text",
              "value": "={{ $json.text }}",
              "type": "string"
            }
          ]
        },
        "options": {
          "includeOtherFields": true
        }
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        7904,
        748
      ],
      "id": "set-llm-completion",
      "name": "SetLlmCompletion"
    },
    {
      "parameters": {
        "mode": "combine",
        "combineBy": "combineByPosition",
        "options": {}
      },
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3,
      "position": [
        8128,
        624
      ],
      "id": "merge-llm-result",
      "name": "MergeLlmResult"
    }
  ],
  "connections": {
    "ExecuteWorkflowTrigger": {
      "main": [
        [
          {
            "node": "PrepareDbQueries",
            "type": "main",
            "index": 0
          },
          {
            "node": "ReactWith\ud83d\udcad",
            "type": "main",
            "index": 0
          },
          {
            "node": "Remove\ud83d\udd35Reaction",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "PrepareDbQueries": {
      "main": [
        [
          {
            "node": "ExecuteQueries(read)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "ExecuteQueries(read)": {
      "main": [
        [
          {
            "node": "BuildContext",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "BuildContext": {
      "main": [
        [
          {
            "node": "GenerateResponse",
            "type": "main",
            "index": 0
          },
          {
            "node": "MergeLlmResult",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GenerateResponse": {
      "main": [
        [
          {
            "node": "SetLlmCompletion",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "MimoV2Flash": {
      "ai_languageModel": [
        [
          {
            "node": "GenerateResponse",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "NemotronNano9b": {
      "ai_languageModel": [
        [
          {
            "node": "GenerateResponse",
            "type": "ai_languageModel",
            "index": 1
          }
        ]
      ]
    },
    "PostToThread": {
      "main": [
        []
      ]
    },
    "PrepareWriteQueries": {
      "main": [
        [
          {
            "node": "ExecuteQueries(write)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "ExecuteQueries(write)": {
      "main": [
        []
      ]
    },
    "SetLlmCompletion": {
      "main": [
        [
          {
            "node": "MergeLlmResult",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "MergeLlmResult": {
      "main": [
        [
          {
            "node": "PrepareWriteQueries",
            "type": "main",
            "index": 0
          },
          {
            "node": "PostToThread",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "callerPolicy": "workflowsFromSameOwner",
    "errorWorkflow": "NOJ7FqVhVLqw0n8D",
    "availableInMCP": false,
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": null,
  "versionId": "afa8d3be-2df8-4506-baab-4f177983c46a",
  "activeVersionId": null,
  "versionCounter": 185,
  "triggerCount": 0,
  "shared": [
    {
      "updatedAt": "2025-12-23T09:30:25.763Z",
      "createdAt": "2025-12-23T09:30:25.763Z",
      "role": "workflow:owner",
      "workflowId": "mbX1lCt14Yi75gTE",
      "projectId": "erM3nntdLL53noWi",
      "project": {
        "updatedAt": "2025-12-23T09:23:39.658Z",
        "createdAt": "2025-12-23T09:16:56.460Z",
        "id": "erM3nntdLL53noWi",
        "name": "Chris Irineo <chriskevini@gmail.com>",
        "type": "personal",
        "icon": null,
        "description": null,
        "projectRelations": [
          {
            "updatedAt": "2025-12-23T09:16:56.460Z",
            "createdAt": "2025-12-23T09:16:56.460Z",
            "userId": "2a851a2d-b7e5-4b3c-aefb-6eaaa79e0659",
            "projectId": "erM3nntdLL53noWi",
            "user": {
              "updatedAt": "2025-12-24T08:40:46.063Z",
              "createdAt": "2025-12-23T09:16:54.881Z",
              "id": "2a851a2d-b7e5-4b3c-aefb-6eaaa79e0659",
              "email": "chriskevini@gmail.com",
              "firstName": "Chris",
              "lastName": "Irineo",
              "personalizationAnswers": {
                "version": "v4",
                "personalization_survey_submitted_at": "2025-12-23T09:23:43.723Z",
                "personalization_survey_n8n_version": "1.123.5"
              },
              "settings": {
                "userActivated": true,
                "firstSuccessfulWorkflowId": "CgUAxK0i4YhrZ2Wp",
                "userActivatedAt": 1766487000077,
                "easyAIWorkflowOnboarded": true
              },
              "disabled": false,
              "mfaEnabled": false,
              "lastActiveAt": "2025-12-24",
              "isPending": false
            }
          }
        ]
      }
    }
  ],
  "tags": [],
  "activeVersion": null
}