{"record":{"id":"b83083b2cda01d24","repo":"mastra-ai/mastra","slug":"related-work-item-not-found-in-this-project","errorCode":null,"errorMessage":"Related work item not found in this project.","messagePattern":"Related work item not found in this project\\.","errorType":"exception","errorClass":"WorkItemRelationError","httpStatus":404,"severity":"error","filePath":"mastracode/factory/src/storage/domains/work-items/base.ts","lineNumber":598,"sourceCode":"}\n\nfunction priorState(row: WorkItemDbRow): WorkItemPriorState {\n  return { stages: row.stages, sessionRoles: Object.keys(row.sessions) };\n}\n\nexport class WorkItemRelationError extends Error {\n  readonly code = 'invalid_work_item_relation';\n}\n\nexport function validateParentRelation(\n  projectItems: WorkItemRow[],\n  itemId: string | undefined,\n  parentWorkItemId: string | null,\n): void {\n  if (parentWorkItemId === null) return;\n  const byId = new Map(projectItems.map(item => [item.id, item]));\n  const parent = byId.get(parentWorkItemId);\n  if (!parent) throw new WorkItemRelationError('Related work item not found in this project.');\n  if (itemId === parentWorkItemId) throw new WorkItemRelationError('A work item cannot relate to itself.');\n\n  const visited = new Set<string>();\n  let cursor: WorkItemRow | undefined = parent;\n  while (cursor?.parentWorkItemId) {\n    if (cursor.parentWorkItemId === itemId) {\n      throw new WorkItemRelationError('This relationship would create a cycle.');\n    }\n    if (visited.has(cursor.id)) throw new WorkItemRelationError('The related work item chain contains a cycle.');\n    visited.add(cursor.id);\n    cursor = byId.get(cursor.parentWorkItemId);\n  }\n}\n\n/**\n * Diff `oldStages` → `newStages` and return the updated history: exited stages\n * get `exitedAt` + `exitedBy` stamped on their open entry, entered stages get\n * a new entry.","sourceCodeStart":580,"sourceCodeEnd":616,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/mastracode/factory/src/storage/domains/work-items/base.ts#L580-L616","documentation":"validateParentRelation checks that any parent (related) work item passed to create/update actually exists within the same project. If parentWorkItemId does not match any item in the project's item list, WorkItemRelationError is thrown so no dangling cross-project or nonexistent relation is stored.","triggerScenarios":"Calling workItems create/update/#upsert with a parentWorkItemId that references a work item from another project, a deleted item, or a typo'd/nonexistent ID.","commonSituations":"Copy-pasting item IDs across projects, a parent item deleted before the child update is applied, or IDs coming from a different tenant/org context.","solutions":["Fetch the parent item first within the same project and confirm it exists before linking","Verify the parentWorkItemId belongs to the same projectId as the child","Handle WorkItemRelationError in the caller and surface a user-facing 'parent not found' message","Re-query the project's work items if the parent was recently created (stale cache)"],"exampleFix":"// before\nawait workItems.update({ id: childId, parentWorkItemId: 'item-999' });\n// after\nconst parent = await workItems.get({ projectId, id: 'item-999' });\nif (!parent) throw new Error('Parent item not found in this project');\nawait workItems.update({ id: childId, parentWorkItemId: 'item-999' });","handlingStrategy":"validation","validationCode":"const parent = projectItems.find(i => i.id === parentWorkItemId);\nif (!parent) throw new Error(`Parent ${parentWorkItemId} not found in project ${projectId}`);","typeGuard":"null","tryCatchPattern":"try {\n  await workItems.update({ id, parentWorkItemId });\n} catch (e) {\n  if (e instanceof WorkItemRelationError && e.message.includes('not found in this project')) {\n    // surface 'parent not found' to user / pick a valid parent\n  } else throw e;\n}","preventionTips":["Resolve parent IDs through the same project scope they will be linked in","Re-fetch recent items before linking instead of trusting stale IDs","Clean up child links when deleting parent items"],"tags":["storage","work-items","validation"],"backgroundTag":"related-entity-not-found","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}