{"record":{"id":"c4063ec7beaee3a5","repo":"linshenkx/prompt-optimizer","slug":"iteration-failed-template-not-found-or-invalid","errorCode":null,"errorMessage":"Iteration failed: Template not found or invalid","messagePattern":"Iteration failed: Template not found or invalid","errorType":"exception","errorClass":"IterationError","httpStatus":null,"severity":"error","filePath":"packages/core/src/services/prompt/service.ts","lineNumber":316,"sourceCode":"\n      // 获取迭代提示词\n      let template;\n      try {\n        template = await this.templateManager.getTemplate(\n          templateId || DEFAULT_TEMPLATES.ITERATE,\n        );\n      } catch (error) {\n        const errorMessage =\n          error instanceof Error ? error.message : String(error);\n        throw new IterationError(\n          originalPrompt,\n          iterateInput,\n          `Iteration failed: ${errorMessage}`,\n        );\n      }\n\n      if (!template?.content) {\n        throw new IterationError(\n          originalPrompt,\n          iterateInput,\n          \"Iteration failed: Template not found or invalid\",\n        );\n      }\n\n      // 🔧 迭代功能必须使用高级模板（message array 格式）以支持变量替换\n      if (typeof template.content === \"string\") {\n        throw new IterationError(\n          originalPrompt,\n          iterateInput,\n          `Iteration requires advanced template (message array format) for variable substitution.\\n` +\n            `Template ID: ${template.id}\\n` +\n            `Current template type: Simple template (string format)\\n` +\n            `Suggestion: Please use message array format template that supports {{lastOptimizedPrompt}} and {{iterateInput}} variables`,\n        );\n      }\n","sourceCodeStart":298,"sourceCodeEnd":334,"githubUrl":"https://github.com/linshenkx/prompt-optimizer/blob/3e677b1d9f7e0493c142c175560531e7ae786dce/packages/core/src/services/prompt/service.ts#L298-L334","documentation":"Thrown when the iteration template was fetched successfully but has no content (template?.content is null/undefined/empty). An iteration cannot proceed without template content to render, so the service aborts with IterationError 'Template not found or invalid'.","triggerScenarios":"An iterate template registered with empty content, a template record whose content field failed to serialize/persist, or a template object shape that doesn't match the expected Template type (content missing rather than empty string).","commonSituations":"Manually created templates saved without content; partial writes to the template store (crash during save); importing templates from another version where the content field was renamed.","solutions":["Load the template and check its content field: templateManager.getTemplate(templateId || DEFAULT_TEMPLATES.ITERATE)","Edit/re-save the template so content is a non-empty message array","If the default template is broken, re-seed built-in templates","Validate imported templates for a non-empty content array before registering them"],"exampleFix":"// before\nawait promptService.iteratePrompt(lastPrompt, input, modelKey, \"broken-tpl\");\n\n// after\nconst tpl = await templateManager.getTemplate(\"broken-tpl\");\nif (!tpl?.content || (Array.isArray(tpl.content) && tpl.content.length === 0)) {\n  await templateManager.updateTemplate(\"broken-tpl\", { content: validMessageArray });\n}\nawait promptService.iteratePrompt(lastPrompt, input, modelKey, \"broken-tpl\");","handlingStrategy":"validation","validationCode":"const tpl = await templateManager.getTemplate(templateId || DEFAULT_TEMPLATES.ITERATE);\nconst hasContent = !!tpl?.content && (!Array.isArray(tpl.content) || tpl.content.length > 0);\nif (!hasContent) throw new Error(\"Iteration template has no content\");","typeGuard":"const hasTemplateContent = (t?: { content?: unknown }): boolean =>\n  !!t?.content && (!Array.isArray(t.content) || (t.content as unknown[]).length > 0);","tryCatchPattern":"try {\n  await promptService.iteratePrompt(last, input, modelKey, templateId);\n} catch (e) {\n  if (e instanceof IterationError && /Template not found or invalid/.test(e.message)) {\n    await repairOrReseedTemplate(templateId);\n  } else throw e;\n}","preventionTips":["Never save templates with empty content; assert content on create/update","Run a startup health check on built-in templates","Validate imported templates before registration"],"tags":["template","validation","empty-content","iteration"],"backgroundTag":"invalid-template-content","analyzedSha":"3e677b1d9f7e0493c142c175560531e7ae786dce","analyzedAt":"2026-08-27T21:29:16.709Z","schemaVersion":2},"datasetVersion":"2026-08-28T00:17:15.603Z"}