import type { OutputType, TaskType, WorkPackage, WorkPackageDeliverable, WorkPackageOutput, WorkPackageTask, } from "./work-package-types"; type TaskTemplate = { title: string; description: string; type: TaskType; executable?: boolean; }; type RenderContext = { wp: WorkPackage; instruction: string; productIdea?: string; sourceTaskId?: string | null; }; type WorkPackageSpec = { defaultInputFiles: string[]; coreSections: string[]; deliverables?: WorkPackageDeliverable[]; taskTemplates: TaskTemplate[]; askHint: string; outputType: OutputType; renderContent: (ctx: RenderContext) => string; }; function section(title: string, lines: string[]) { return [`## ${title}`, ...lines, ""].join("\n"); } function list(items: string[]) { return items.map((item) => `- ${item}`); } function trimIdea(idea?: string) { return idea?.trim() || "an industrial IoT tightening quality monitoring product"; } function getIdeaSummary(productIdea?: string) { const idea = trimIdea(productIdea); return [ `Product context: ${idea}`, "Assumption: This is a connected industrial device with onboard sensing, local firmware, and dashboard/reporting needs.", ]; } export const WORK_PACKAGE_SPECS: Record = { "wp-crs": { defaultInputFiles: [ "VOC notes", "Customer interviews", "Market feedback", "Safety and legal input", ], coreSections: [ "CRS-User", "CRS-Safety", "CRS-Legal", "CRS-Security", "CRS-Technology", "CRS-Manufacturing", "CRS-Logistics", "CRS-Trade", "CRS-Service", ], taskTemplates: [ { title: "Capture VOC and stakeholder requirements", description: "Translate raw customer and stakeholder input into structured requirement statements.", type: "research", executable: true, }, { title: "Classify requirements by domain", description: "Sort requirements into user, safety, legal, technology, manufacturing, logistics, trade, and service sections.", type: "analysis", }, { title: "Prepare CRS-to-SRS traceability starter", description: "Create initial traceability references for downstream system requirements.", type: "planning", }, ], askHint: "Answer in terms of stakeholder needs, classification, and what the package must feed into SRS.", outputType: "table", renderContent: ({ wp, productIdea }) => [ section("Expected Outputs", list(wp.outputFiles)), section("Customer Requirement List", [ "CRS-001 | Detect tightening anomalies within one work cycle | User | High", "CRS-002 | Provide shift-level trend reporting for supervisors | Trade | Medium", "CRS-003 | Operate on factory Wi-Fi with optional wired fallback | Technology | High", "CRS-004 | Support easy field replacement of the sensing head | Service | Medium", ]), section("User Stories", [ "As a line operator, I want instant feedback on abnormal tightening events so I can stop defects from propagating.", "As a quality engineer, I want traceable event history so I can audit recurring issues by station and shift.", ]), section("Requirement Classification", list(wp.coreSections)), section("CRS-to-SRS Traceability Input", [ "CRS-001 -> sensing accuracy, event detection latency, station identification", "CRS-002 -> data retention, dashboard summaries, export/reporting functions", "CRS-003 -> network interface, retry logic, offline buffering", ]), section("Context", getIdeaSummary(productIdea)), ].join("\n"), }, "wp-final-concept": { defaultInputFiles: ["CRS draft", "User insight notes", "Market positioning notes"], coreSections: [ "User group", "User size", "Insights", "Benefits", "Reasons to believe", "Verbal concept validation", "Product concept visual brief", ], taskTemplates: [ { title: "Synthesize user insight themes", description: "Condense CRS pain points into 3-5 insights.", type: "analysis", executable: true, }, { title: "Draft benefit and RTB matrix", description: "Connect insights to value propositions and proof points.", type: "planning", }, { title: "Create concept visual brief", description: "Describe the intended concept direction for industrial design.", type: "design", }, ], askHint: "Answer in terms of user insight, product value, and how the concept should be validated before detailed design.", outputType: "design_brief", renderContent: ({ wp, productIdea }) => [ section("Expected Outputs", list(wp.outputFiles)), section("Final Product Concept", [ `A compact edge-connected quality monitoring device for ${trimIdea(productIdea)} that detects abnormal torque patterns, explains likely causes, and pushes summaries to supervisors.`, ]), section("Insight-Benefit-RTB Matrix", [ "Insight: Operators only discover faults after downstream inspection.", "Benefit: Immediate anomaly alerting reduces scrap and rework.", "Reason to believe: High-frequency sensing with edge analytics and local alert logic.", "Insight: Quality teams struggle to trace intermittent station issues.", "Benefit: Shift and station dashboards make recurring drift visible.", "Reason to believe: Event tagging, local buffering, and supervisor-ready summaries.", ]), section("Validation of Verbal Concept", [ "Target users: line operator, quality engineer, maintenance lead", "Validation hypothesis: users value rapid anomaly feedback over broad analytics breadth in the first release", "Follow-up: test the concept description with 5 pilot users", ]), section("2D Concept Visual Brief", [ "Rugged small enclosure mounted near tightening station", "Status LED visible from operator position", "Minimal service access points for swap/replacement", ]), section("Context", getIdeaSummary(productIdea)), ].join("\n"), }, "wp-srs": { defaultInputFiles: ["CRS traceability input", "Component assumptions", "Interface assumptions"], coreSections: [ "SRS ID", "Related CRS ID", "System Requirement Statement", "Component / Module", "Specification", "Interface / Dependency", "Verification Method", "Acceptance Criteria", ], taskTemplates: [ { title: "Translate CRS into system requirements", description: "Produce traceable system-level requirements with verification logic.", type: "generation", executable: true, }, { title: "Identify component and interface needs", description: "Map requirements to modules, interfaces, and dependencies.", type: "analysis", }, { title: "Prepare verification inputs", description: "Attach verification method and acceptance criteria for each requirement.", type: "testing", }, ], askHint: "Answer by separating customer need from system realization, and include verification implications.", outputType: "table", renderContent: ({ wp, productIdea }) => [ section("Expected Outputs", list(wp.outputFiles)), section("System Requirements Specification", [ "SRS-001 | CRS-001 | System shall detect abnormal torque signatures within 500 ms of cycle completion | Sensor + Edge Analytics | Event latency <= 500 ms | Sensor bus | Test | 95% of injected anomalies detected", "SRS-002 | CRS-002 | System shall retain event history for 24 hours offline | Firmware + Storage | Buffer >= 24 hours | Local flash | Functional test | No data loss during 24-hour disconnect", "SRS-003 | CRS-003 | System shall publish summary metrics every 60 seconds when connected | Connectivity Module | 60-second summary cadence | Wi-Fi/Ethernet | Integration test | 99% message success in stable network", ]), section("CRS-to-SRS Traceability Matrix", [ "CRS-001 -> SRS-001", "CRS-002 -> SRS-002", "CRS-003 -> SRS-003", ]), section("Component Requirement List", [ "Torque/vibration sensing chain", "MCU or edge compute module", "Local storage", "Connectivity stack", "Supervisor dashboard interface", ]), section("Interface Requirement List", [ "Sensor bus to MCU", "Device-to-dashboard API", "Firmware update/service interface", ]), section("Context", getIdeaSummary(productIdea)), ].join("\n"), }, "wp-safety-of-products": { defaultInputFiles: ["SRS draft", "Hazard assumptions", "Use/misuse scenarios"], coreSections: [ "Moving Elements", "Accessible Parts", "Thermal Hazards", "Material/Substance Hazards", "Ergonomic Hazards", "Environment Hazards", "Life Cycle Hazards", ], taskTemplates: [ { title: "Define intended use and foreseeable misuse", description: "Capture the operational context and common misuse patterns.", type: "analysis", executable: true, }, { title: "Assess safety hazards and risk ratings", description: "Generate the initial hazard list and risk matrix.", type: "risk", }, { title: "Recommend risk reduction measures", description: "Propose mitigations and residual risk acceptance statements.", type: "review", }, ], askHint: "Answer with hazard categories, risk rationale, and mitigation priorities rather than broad product strategy.", outputType: "risk_table", renderContent: ({ wp, productIdea }) => [ section("Expected Outputs", list(wp.outputFiles)), section("Product Safety Risk Assessment", getIdeaSummary(productIdea)), section("Hazard List", [ "HZ-001 | Accessible cable snag during maintenance | Ergonomic / Life Cycle", "HZ-002 | Misread status signal causing continued use after anomaly | Accessible Parts / Use Error", "HZ-003 | Overheating near enclosed industrial cabinet | Thermal Hazards", ]), section("Risk Matrix", [ "HZ-001 | Severity 2 | Likelihood 3 | Initial Risk Medium", "HZ-002 | Severity 4 | Likelihood 2 | Initial Risk Medium", "HZ-003 | Severity 4 | Likelihood 2 | Initial Risk Medium", ]), section("Risk Reduction Measures", [ "Add protected cable routing and service instructions", "Use unambiguous fault-state indication and latched alarm behavior", "Derate thermal design for sealed-cabinet installation and add temperature monitoring", ]), section("Residual Risk Assessment", [ "Residual risk acceptable if service instructions, alarm handling, and thermal safeguards are verified.", ]), ].join("\n"), }, "wp-product-certification": { defaultInputFiles: ["Target markets", "Connectivity assumptions", "Safety assumptions"], coreSections: [ "Applicable standards", "Applicable directives and regulations", "Required documents", "Approval milestones", "Action items", ], taskTemplates: [ { title: "Identify applicable market access categories", description: "Map the product concept to likely regulatory and standards buckets.", type: "compliance", executable: true, }, { title: "Create certification checklist", description: "List required evidence and documentation items.", type: "planning", }, { title: "Define approval milestones", description: "Sequence the certification work into a usable plan.", type: "review", }, ], askHint: "Answer with probable compliance categories, document needs, and planning implications. Never imply legal certainty in MVP.", outputType: "checklist", renderContent: ({ wp, productIdea }) => [ section("Expected Outputs", list(wp.outputFiles)), section("Product Certification Briefing", getIdeaSummary(productIdea)), section("Applicable Standards List", [ "EMC / industrial electronic equipment standards (to be confirmed by product architecture)", "Electrical safety standard family appropriate to supply and enclosure class", "Radio compliance requirements if wireless connectivity is used", ]), section("Certification Checklist", [ "[ ] Confirm target markets and import/export scope", "[ ] Confirm power architecture and safety class", "[ ] Confirm wireless modules and regional radio needs", "[ ] Prepare technical file, declarations, and labeling inputs", ]), section("Product Certification Plan", [ "Gate 1: architecture and market assumptions confirmed", "Gate 2: standards shortlist reviewed with engineering", "Gate 3: evidence package assembled for pre-compliance testing", ]), ].join("\n"), }, "wp-test-management": { defaultInputFiles: ["CRS", "SRS", "Safety assessment", "Certification checklist"], coreSections: [ "Requirement-to-Test Traceability", "Functional tests", "Performance tests", "Reliability validation", "Sample size", "Test time", "Test cost", ], taskTemplates: [ { title: "Generate requirement-to-test matrix", description: "Translate CRS/SRS items into functional and performance verification coverage.", type: "testing", executable: true, }, { title: "Estimate reliability validation scope", description: "Propose sample size, duration, and success-run assumptions.", type: "analysis", }, { title: "Outline test resources and cost", description: "Summarize lab time, fixtures, and staffing assumptions.", type: "planning", }, ], askHint: "Answer with traceability, verification scope, and reliability planning. Keep the focus on test strategy, not product marketing.", outputType: "test_case", renderContent: ({ wp, productIdea }) => [ section("Expected Outputs", list(wp.outputFiles)), section("Test Plan", getIdeaSummary(productIdea)), section("Requirement-to-Test Matrix", [ "SRS-001 -> Functional anomaly injection test -> Acceptance: anomaly detected within 500 ms", "SRS-002 -> Offline endurance test -> Acceptance: 24-hour data buffer preserved", "SRS-003 -> Connectivity summary test -> Acceptance: 99% successful summary uploads", ]), section("Reliability Validation Plan", [ "Sample size assumption: 8 devices for pilot reliability cycle", "Test duration assumption: 2 weeks mixed duty simulation", "Success criterion: no critical data-loss or thermal reset failures", ]), section("Sample Size Calculation", [ "Mock estimate: 8 devices gives useful signal for early reliability screening; increase for confidence before launch.", ]), section("Test Cost Estimate", [ "Fixtures: medium effort", "Lab/line time: 10-15 working days", "Staffing: 1 QA engineer + 1 firmware/EE support", ]), ].join("\n"), }, "wp-decompose-system": { defaultInputFiles: ["Initial engineering concept", "SRS", "Architecture assumptions"], coreSections: [ "System decomposition", "Technology Filter", "Focus Area Analysis", "Technical Complexity Category", "Project Risk Class", ], deliverables: [ { name: "Technology Filter", required: true }, { name: "Focus Area Analysis", required: "if product is complicated-new or complex" }, { name: "Technical Complexity Category", required: true }, { name: "Project Risk Class", required: true }, ], taskTemplates: [ { title: "Break system into modules and interfaces", description: "Define the core subsystems and their boundaries.", type: "design", executable: true, }, { title: "Evaluate technical focus areas", description: "Highlight novelty, risk, and standardization opportunities.", type: "analysis", }, { title: "Assign complexity and project risk class", description: "Estimate technical complexity and pre-development pressure.", type: "risk", }, ], askHint: "Answer with decomposition boundaries, critical interfaces, and technical risk class.", outputType: "table", renderContent: ({ wp, productIdea }) => [ section("Expected Outputs", list(wp.outputFiles)), section("System Decomposition", [ "Subsystem A | Sensing head | Captures torque/vibration signatures", "Subsystem B | Edge controller | Runs detection logic and local buffering", "Subsystem C | Connectivity module | Publishes summaries and receives configuration", "Subsystem D | Service interface | Supports diagnostics, updates, and replacement workflow", ]), section("Technology Filter", [ "Keep custom hardware limited to sensing and ruggedization needs", "Reuse standard compute, storage, and networking modules where possible", ]), section("Focus Area Analysis", [ "Highest novelty: anomaly detection robustness under noisy production conditions", "Highest integration risk: network reliability vs local buffering expectations", ]), section("Technical Complexity Category", [ `Recommended category: complicated-new for ${trimIdea(productIdea)}`, ]), section("Project Risk Class", [ "Mock estimate: medium-high due to sensing robustness, field serviceability, and industrial integration needs", ]), ].join("\n"), }, "wp-industrial-design": { defaultInputFiles: ["Final concept", "SRS", "Safety summary", "Service needs"], coreSections: [ "Industrial design brief", "2D concept design brief", "CMF proposal", "HMI / interaction layout", "Design review checklist", ], taskTemplates: [ { title: "Generate industrial design brief", description: "Translate the concept into visual and ergonomic direction.", type: "design", executable: true, }, { title: "Define CMF and interaction details", description: "Propose materials, finish, indicators, and controls.", type: "design", }, { title: "Create design review checklist", description: "Ensure concept alignment with service, safety, and branding needs.", type: "review", }, ], askHint: "Answer with form, ergonomics, visual cues, and serviceability implications.", outputType: "design_brief", renderContent: ({ wp, productIdea }) => [ section("Expected Outputs", list(wp.outputFiles)), section("Industrial Design Brief", [ `Design a compact, factory-ready enclosure for ${trimIdea(productIdea)} with a clear service split between the sensing head and control module.`, "Visual language: robust, precise, easy to scan from an operator station.", ]), section("2D Concept Design Brief", [ "Front face with clear status signaling", "Protected cable routing and sealed edges", "Simple mounting bracket with fast swap access", ]), section("CMF Proposal", [ "Body: matte charcoal engineering polymer or coated aluminum", "Signal accents: safety amber + fault red only where actionable", "Service touchpoints: lighter neutral for quick identification", ]), section("Design Review Checklist", [ "[ ] Status indicators visible from working position", "[ ] Fasteners and service access compatible with field maintenance", "[ ] Label placement supports certification and traceability needs", ]), ].join("\n"), }, "wp-patent-check": { defaultInputFiles: ["Concept summary", "Architecture summary", "Competitor assumptions"], coreSections: [ "Patent search topics", "FTO risk assumptions", "Patentable invention points", "Design-around questions", "IP review action items", ], taskTemplates: [ { title: "Define patent search topics", description: "List the technical areas that warrant simulated IP review.", type: "research", executable: true, }, { title: "Summarize FTO risk assumptions", description: "Highlight areas where overlap could exist and what to inspect later.", type: "risk", }, { title: "Identify possible invention points", description: "Call out design elements that may be differentiating.", type: "analysis", }, ], askHint: "Answer as a simulated IP planning aid. Never imply legal certainty or a real search.", outputType: "checklist", renderContent: ({ wp, productIdea }) => [ section("Expected Outputs", list(wp.outputFiles)), section("Patent Search Topic List", [ "Edge anomaly detection for tightening / torque quality monitoring", "Sensor fusion or signature analysis for industrial fastening quality", "Service-friendly modular sensing head architectures", ]), section("FTO Risk Assumptions", [ "Assume moderate overlap risk around analytics methods and fixture geometry", "Assume lower risk around dashboard/reporting unless the workflow is unusually specific", ]), section("Patentable Invention Points", [ `Potential novelty for ${trimIdea(productIdea)} may sit in combined sensing + field-service workflow + operator feedback loop.`, ]), section("IP Review Action Items", [ "[ ] Validate analytics-method overlap with later formal search", "[ ] Review service-head replacement architecture for novelty and risk", "[ ] Document unique workflow claims before engineering freezes", ]), ].join("\n"), }, "wp-design-fmea": { defaultInputFiles: ["SRS", "Decomposition", "Safety assessment", "Concept architecture"], coreSections: [ "FMEA ID", "Related CRS ID", "Related SRS ID", "System/Module", "Function", "Potential Failure Mode", "Potential Effect", "Severity", "Cause", "Occurrence", "Prevention Control", "Detection Control", "Detection", "Risk Priority", "Recommended Action", "Residual Risk", "Verification Evidence", ], taskTemplates: [ { title: "Generate Design FMEA table", description: "Assess failure modes, effects, causes, and RPN scores.", type: "risk", executable: true, }, { title: "Identify top-risk actions", description: "Pull out the highest-risk issues that need design changes.", type: "analysis", }, { title: "Map verification follow-up", description: "Tie mitigation actions to verification evidence expectations.", type: "review", }, ], askHint: "Answer with failure-mode thinking, RPN logic, and recommended verification actions.", outputType: "risk_table", renderContent: ({ wp }) => [ section("Expected Outputs", list(wp.outputFiles)), section("Design FMEA Table", [ "FMEA ID | Related SRS ID | Module | Function | Failure Mode | Effect | Severity | Cause | Occurrence | Detection | RPN | Recommended Action", "---|---|---|---|---|---|---:|---|---:|---:|---:|---", "DF-001 | SRS-001 | Sensor Subsystem | Capture torque signature | Loose mounting | False anomaly classification | 4 | Vibration / assembly drift | 3 | 3 | 36 | Add retention feature and torque verification step", "DF-002 | SRS-003 | Connectivity | Publish station summary | Intermittent link | Missing supervisor data | 4 | RF interference | 3 | 2 | 24 | Add retry/backoff and offline queue", "DF-003 | SRS-002 | Power | Maintain stable operation | Brownout reset | Lost buffered event context | 5 | Supply dip | 2 | 3 | 30 | Add supervisor IC and margin analysis", ]), section("High-Risk Failure Mode List", [ "DF-001 | Mechanical stability of sensing head", "DF-003 | Power stability during transient industrial loads", ]), section("Recommended Design Actions", [ "Add retention and assembly verification for sensing-head mounting", "Add supply supervision and transient margin testing for controller power path", "Add queue/retry verification for intermittent connectivity scenarios", ]), section("Residual Risk Summary", [ "Residual risk is acceptable after mechanical retention, supply supervision, and queueing controls are verified.", ]), ].join("\n"), }, "wp-final-engineering-concept": { defaultInputFiles: ["SRS", "Decomposition", "Design FMEA", "Industrial design constraints"], coreSections: [ "Hardware BOM", "Software SBOM", "Feature List", "BOM-to-Feature Mapping", "SBOM-to-Feature Mapping", "Feature-to-SRS Traceability", "Open Engineering Decision List", ], taskTemplates: [ { title: "Draft hardware BOM", description: "List the main hardware building blocks and their roles.", type: "design", executable: true, }, { title: "Draft software SBOM", description: "Identify the key software/runtime components.", type: "generation", }, { title: "Map features to hardware, software, and SRS", description: "Create traceability from implementation elements to planned features.", type: "analysis", }, ], askHint: "Answer with implementation building blocks, feature traceability, and open engineering decisions.", outputType: "bom", renderContent: ({ wp, productIdea }) => [ section("Expected Outputs", list(wp.outputFiles)), section("Hardware BOM", [ "BOM-001 | Sensor head | Sensing | Capture torque/vibration signature | Anomaly detection | SRS-001 | Industrial-grade sensor chain | Buy/custom mix | Medium certification impact | Medium safety impact | Validate mounting robustness | Draft", "BOM-002 | Edge controller | Compute | Run detection logic and manage local data | Event detection + buffering | SRS-001/SRS-002 | MCU or SOM | Buy | Medium certification impact | Low safety impact | Confirm memory margin | Draft", "BOM-003 | Connectivity module | Networking | Publish summaries and receive config | Reporting | SRS-003 | Wi-Fi/Ethernet path | Buy | Medium certification impact | Low safety impact | Confirm factory compatibility | Draft", ]), section("Software SBOM", [ "SBOM-001 | RTOS / Linux runtime | Runtime | Device control | Event detection | SRS-001/SRS-002 | Platform runtime | TBD | License review required | Low data concern | Draft", "SBOM-002 | Analytics service | Application | Signature analysis | Detection feature | SRS-001 | Internal module | v0.x | Internal | Moderate data concern | Draft", "SBOM-003 | Connectivity client | Application | Message transport | Dashboard summaries | SRS-003 | Internal / SDK | v0.x | Review SDK license | Moderate security concern | Draft", ]), section("Feature List", [ `FEAT-001 | Real-time anomaly alerting | Detect abnormal tightening events for ${trimIdea(productIdea)} | Reduce scrap quickly | CRS-001 | SRS-001 | Sensor head + edge controller | Analytics service | High | MVP | Functional test | Draft`, "FEAT-002 | Offline event buffering | Preserve event data during network outages | Maintain traceability | CRS-002 | SRS-002 | Edge controller + storage | Runtime + storage manager | High | MVP | Endurance test | Draft", "FEAT-003 | Shift summary reporting | Share station summaries with supervisors | Improve visibility | CRS-002 | SRS-003 | Connectivity module | Connectivity client | Medium | MVP | Integration test | Draft", ]), section("Traceability Mapping", [ "BOM-001 -> FEAT-001 -> SRS-001", "BOM-002 -> FEAT-001 / FEAT-002 -> SRS-001 / SRS-002", "SBOM-003 -> FEAT-003 -> SRS-003", ]), section("Open Engineering Decision List", [ "Choose compute architecture: MCU-only vs SOM for analytics headroom", "Decide wireless default vs wired-first deployment option", "Confirm serviceable sensing-head connector strategy", ]), ].join("\n"), }, "wp-service-ability-review": { defaultInputFiles: ["Engineering concept", "Service assumptions", "Industrial design review"], coreSections: [ "Quality Gate Questionnaire", "Service Readiness Score", "Go / Conditional Go / No-Go Recommendation", "Open Service Action Items", "Diagnostic Requirement List", "Service Tool Requirement", "Service Training Requirement", ], taskTemplates: [ { title: "Generate service quality gate questionnaire", description: "Check serviceability blockers and major gaps.", type: "review", executable: true, }, { title: "Score service readiness", description: "Estimate readiness and identify open actions.", type: "analysis", }, { title: "Summarize service documentation and tooling needs", description: "List the support material required for field/service teams.", type: "planning", }, ], askHint: "Answer with serviceability gates, open risks, and the likely go/no-go logic.", outputType: "checklist", renderContent: ({ wp, productIdea }) => [ section("Expected Outputs", list(wp.outputFiles)), section("Service Quality Gate Questionnaire", [ "Q-001 | Replaceable Unit | Can the sensing head be replaced without disturbing calibrated alignment? | Answer: Partial | Gate Impact: Major", "Q-002 | Diagnostics | Can service personnel retrieve fault cause without engineering support? | Answer: No | Gate Impact: Blocker", "Q-003 | Training | Is there a concise field replacement workflow? | Answer: Partial | Gate Impact: Major", ]), section("Service Readiness Score", [ "Mock score: 58 / 100", ]), section("Go/Conditional Go/No-Go Recommendation", [ `Recommendation for ${trimIdea(productIdea)}: No-Go until diagnostic access and replacement workflow are closed.`, ]), section("Open Service Action Items", [ "[ ] Add technician-readable diagnostic state reporting", "[ ] Simplify sensing-head replacement alignment process", "[ ] Draft quick-start service training card", ]), ].join("\n"), }, }; function buildTaskId(workPackageId: string, index: number) { return `${workPackageId}-task-${index + 1}`; } export function getWorkPackageSpec(workPackage: WorkPackage) { return WORK_PACKAGE_SPECS[workPackage.id]; } export function createSpecTasks(workPackage: WorkPackage): WorkPackageTask[] { const spec = getWorkPackageSpec(workPackage); if (!spec) return workPackage.tasks; return spec.taskTemplates.map((task, index) => ({ id: buildTaskId(workPackage.id, index), title: task.title, description: task.description, type: task.type, executable: Boolean(task.executable), status: "todo", })); } export function hydrateWorkPackages( workPackages: WorkPackage[], productIdea?: string, ): WorkPackage[] { const idea = productIdea?.trim(); return workPackages.map((workPackage, index) => { const spec = getWorkPackageSpec(workPackage); if (!spec) return workPackage; const hasGenericTasks = workPackage.tasks.length <= 1 && workPackage.tasks.every((task) => task.title.toLowerCase().includes("generate simulated output"), ); const mergedInputFiles = Array.from( new Set( [ ...(idea ? [`Product brief: ${idea}`] : []), ...spec.defaultInputFiles, ...workPackage.inputFiles, ].filter(Boolean), ), ); return { ...workPackage, inputFiles: mergedInputFiles, coreSections: workPackage.coreSections.length ? workPackage.coreSections : spec.coreSections, deliverables: workPackage.deliverables && workPackage.deliverables.length ? workPackage.deliverables : spec.deliverables, tasks: hasGenericTasks ? createSpecTasks(workPackage) : workPackage.tasks, status: idea && index === 0 ? "in_progress" : workPackage.status, }; }); } export function buildExecutionContent( workPackage: WorkPackage, instruction: string, productIdea?: string, sourceTaskId?: string | null, ): Pick { const spec = getWorkPackageSpec(workPackage); if (!spec) { return { type: "text", content: [`Instruction: ${instruction || "(none provided)"}`].join("\n"), sourceTaskId, }; } return { type: spec.outputType, content: spec.renderContent({ wp: workPackage, instruction, productIdea, sourceTaskId, }), sourceTaskId, }; } export function buildAskGuidance(workPackage: WorkPackage) { const spec = getWorkPackageSpec(workPackage); return spec?.askHint; }