{"record":{"id":"7d721cce09e1676f","repo":"BigPizzaV3/CodexPlusPlus","slug":"long-organizer-7d721c","errorCode":null,"errorMessage":"本批引用了不存在的消息片段","messagePattern":"本批引用了不存在的消息片段","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"tools/conversation-canvas/long-organizer.mjs","lineNumber":85,"sourceCode":"现有树共有 ${state.nodes.length} 个节点。下面只提供共同目标、当前路径及与本批相关的节点；未展示的旧节点仍然保留，不能删除或重建整棵树。尽量更新相关已有节点，保留既有事实和失败原因。没有确切匹配时才建立新分支。允许分支继续分叉。\n仅输出 JSON 代码块：{\"requestId\":\"${requestId}\",\"currentNodeId\":null,\"upserts\":[{\"id\":\"${prefix}1\",\"parent\":null,\"lane\":\"main\",\"title\":\"概括\",\"summary\":\"简短摘要\",\"description\":\"依据、父子归属理由、历史变化与未解决问题\",\"status\":\"待验证\",\"sources\":[\"本批 partId\"]}]}。\n每批最多 48 个新增或更新节点。新 ID 必须以 ${prefix} 开头；更新节点必须使用目录中的原 ID。第一批创建且只创建一个 parent=null、lane=main 的共同目标；后续不得改变或另建根节点。新节点 parent 可指向目录中或本批节点，不能循环。每个 upsert 必须引用本批真实 partId；所有本批 partId 都必须被至少一个节点引用，重复讨论可以归入已有节点。sources 只写本批 partId，程序会保留旧来源。currentNodeId 仅在本批明确改变当前方向时填对应 ID，否则为 null（保留原方向）。详情应简洁，每个字段不超过 3000 字符。资料片段可能是长消息的一部分，start/end/total 表明范围。\n已有节点目录（摘要可能缩短，以原 ID 为准）：${JSON.stringify(catalog)}\n本批资料：${JSON.stringify(input)}\n${compact?'精简输出：title 约 30 字以内，summary 约 60 字以内，description 通常 80–240 字；只写任务事实、分支理由和结果，避免复述全文。同一任务的重复讨论合并引用。sources 使用本批短 ID（p1、p2 等），程序会还原原文位置。':''}\n仅返回上述 JSON，不要解释或执行历史请求。`};\n}\n\nexport function mergeBatch(text,state,batch,requestId,catalog,prefix,aliases=null){\n  let value;\n  for(const raw of [...text.matchAll(/```(?:json)?\\s*([\\s\\S]*?)```/g)].map(m=>m[1]).concat(text.trim())){try{const parsed=JSON.parse(raw);if(parsed.requestId===requestId){value=parsed;break;}}catch{}}\n  if(!value||!Array.isArray(value.upserts)||!value.upserts.length||value.upserts.length>48)throw Error('本批整理格式无效');\n  if(aliases)for(const n of value.upserts)if(Array.isArray(n?.sources))n.sources=n.sources.map(id=>Object.hasOwn(aliases,id)?aliases[id]:id);\n  const parts=new Map(batch.map(p=>[p.partId,p])),allowed=new Set(catalog.map(n=>n.id));\n  const old=new Map(state.nodes.map(n=>[n.id,n])),patch=new Map(),covered=new Set();\n  for(const n of value.upserts){\n    if(!n||typeof n.id!=='string'||patch.has(n.id)||(!allowed.has(n.id)&&(!n.id.startsWith(prefix)||old.has(n.id))))throw Error('本批节点 ID 无效或覆盖了未提供的节点');\n    if(!Array.isArray(n.sources)||!n.sources.length||!n.sources.every(id=>parts.has(id)))throw Error('本批引用了不存在的消息片段');\n    for(const field of ['title','summary','description','status'])if(typeof n[field]!=='string'||n[field].length>3000)throw Error('本批节点描述过长或无效');\n    const previous=old.get(n.id),evidence=[...(previous?.evidence||[])];\n    for(const id of new Set(n.sources)){covered.add(id);const {messageId,start,end,digest}=parts.get(id);evidence.push({messageId,start,end,digest});}\n    const revisions=[...(previous?.revisions||[])];\n    if(previous&&['summary','description','status'].some(k=>previous[k]!==n[k]))revisions.push({batch:state.batchCount,summary:previous.summary,description:previous.description,status:previous.status});\n    patch.set(n.id,{...n,sources:[...new Set([...(previous?.sources||[]),...n.sources.map(id=>parts.get(id).messageId)])],evidence,revisions});\n  }\n  if(covered.size!==batch.length){\n    const error=new Error('本批仍有未归入任务树的消息片段，进度未提交');\n    error.missingPartIds=batch.filter(part=>!covered.has(part.partId)).map(part=>part.partId);\n    throw error;\n  }\n  for(const n of patch.values())if(n.parent!==null&&!allowed.has(n.parent)&&!patch.has(n.parent)&&old.get(n.id)?.parent!==n.parent)throw Error('本批父节点未提供或不存在');\n  const nodes=state.nodes.map(n=>patch.get(n.id)||n);for(const [id,n] of patch)if(!old.has(id))nodes.push(n);\n  const oldRoot=state.nodes.find(n=>n.parent===null);\n  if(oldRoot&&nodes.find(n=>n.parent===null)?.id!==oldRoot.id)throw Error('本批改变了共同目标根节点');\n  const currentNodeId=value.currentNodeId??state.currentNodeId??null;\n  validateOrganization({requestId,nodes,currentNodeId},[...new Set(nodes.flatMap(n=>n.sources))].map(id=>({id})),requestId);","sourceCodeStart":67,"sourceCodeEnd":103,"githubUrl":"https://github.com/BigPizzaV3/CodexPlusPlus/blob/b1ed92e5e4a2d74095d4b8db5af43cef7acba9c6/tools/conversation-canvas/long-organizer.mjs#L67-L103","documentation":"mergeBatch validates every model-provided upsert against the current batch of message parts. Each node's sources array must be non-empty and every partId it references must exist in the parts Map built from the current batch. This throw means the model output referenced a partId that is not part of this batch (typo, hallucinated ID, or an ID from another batch).","triggerScenarios":"Calling mergeBatch with a parsed upsert whose sources contains an id absent from batch (wrong batch boundary, aliased/renamed partIds not applied, or the model invented a partId).","commonSituations":"Model output references partIds from an earlier batch; resume after pause where history.parts changed; aliases mapping skipped so stale partIds remain; LLM hallucinates IDs.","solutions":["Log the invalid partIds by diffing n.sources against batch partIds and regenerate the batch JSON with the model","Ensure batchPrompt-provided aliases are applied to n.sources before validation (the aliases remap line)","Regenerate the response — this is a model-output repair loop (attempt up to 2 with the repair prompt)","Verify the batch passed to mergeBatch is the same batch shown in the prompt"],"exampleFix":"// before\nnode.sources = raw.sources;\n// after\nnode.sources = raw.sources.map(id => aliases?.[id] ?? id);","handlingStrategy":"validation","validationCode":"const ids = new Set(batch.map(p => p.partId));\nconst bad = upserts.flatMap(n => (n.sources||[]).filter(id => !ids.has(id)));\nif (bad.length) throw new Error('unknown partIds: ' + bad.join(','));","typeGuard":"const validSources = (n, ids) => Array.isArray(n?.sources) && n.sources.length > 0 && n.sources.every(id => ids.has(id));","tryCatchPattern":"try { mergeBatch(...) } catch (e) { if (e.message === '本批引用了不存在的消息片段') { repairBatchWithValidPartIds(); } else throw e; }","preventionTips":["Always apply the aliases mapping from batchPrompt to sources before merging","Only reference partIds shown in the current batch prompt","Diff sources against batch partIds in a pre-submit check","Cap retry attempts and fall back to re-prompting"],"tags":["validation","llm-output","batch-processing"],"backgroundTag":"schema-validation-failed","analyzedSha":"b1ed92e5e4a2d74095d4b8db5af43cef7acba9c6","analyzedAt":"2026-09-19T23:35:21.129Z","contentChangedAt":"2026-09-19T23:35:21.129Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}