""" AIPM - Execution Agent (v1.0) Agent 3 (final) of the AI Hyperdox pipeline: Goals & Scope -> Planning -> Execution. DESIGN NOTE - HOW THIS AGENT DIFFERS FROM AGENTS 1 & 2: Goals & Scope and Planning are one-shot document generators: run once, produce a governed artifact, hand it downstream. Execution is inherently RECURRING - a PM runs this weekly/biweekly/per-sprint, and each run should ideally know what happened last time, not just report the current period in isolation. That has one real architectural consequence not present in the other two agents: this agent's most natural input isn't just Planning's handoff - it's also ITS OWN PRIOR OUTPUT (a self-referential handoff chain, "*_execution_snapshot.json"), so trend/variance-over-time doesn't require the user to retype history every period. THREE OPERATING MODES (per explicit design decision - agents should chain when possible but stand alone completely, not degraded, when they don't): 1. FULLY CHAINED - Planning backbone + prior Execution snapshot + this period's status -> full variance vs. baseline AND trend vs. last period. 2. PARTIALLY CHAINED - Planning backbone only (e.g. first run ever) -> variance vs. baseline; no trend yet, nothing to trend against. 3. STANDALONE - no uploads at all, manual status only -> ad hoc status tracking against user-named tasks; variance fields explicitly marked non-computable rather than fabricated. A complete, honest mode, not a crippled one. TWO DISTINCT "MISSING DATA" MARKERS (this is new relative to Agents 1 & 2, and deliberate - conflating these two would make a standalone run look like it has unresolved gaps when it's actually just correctly operating in a lower-input mode): - "UNSPECIFIED - see open questions" = the user COULD have given this info but didn't (vague/missing input) - same meaning as in Agents 1 & 2. - "NOT COMPUTABLE - no baseline provided" = this field is STRUCTURALLY impossible to compute because no upstream baseline/history was uploaded - not a gap the user needs to fill, just an honest description of what standalone mode can and can't do. Only the first marker triggers the validate_unspecified_markers() guardrail below; the second is expected and correct in standalone mode and would create guardrail noise if treated the same way. OPEN DESIGN DECISIONS RESOLVED FOR v1.0: - Self-referential handoff file is named "*_execution_snapshot.json". - Risk register tracking works in ALL modes, not just when a Goals & Scope handoff chains through. Sourced from (in order of preference, all optional): the Goals & Scope handoff's risks (if the full chain exists), the prior Execution snapshot's risk_register_update (carried forward with status changes), and anything the user explicitly mentions as a risk in this period's free-text status/actuals input. No dedicated "Risks" input field was added - would bloat a form meant to be filled out weekly; risks surface through the inputs that already exist. ARCHITECTURE CARRIED FORWARD FROM AGENTS 1 & 2 (same reasoning as documented there): real persona system prompt (not a placeholder), single structured JSON call, session- safe uuid file naming, retry-with-backoff, input truncation guardrails, code-level coverage validation (not just a prompt instruction), any-file-type/count uploads, combined guardrail document, and the extract_text_from_file() bugfix already applied in Goals & Scope v5.0 and Planning v2.1/2.2 (string filepaths have no .name attribute). NOTE ON MIGRATION: the only OpenAI-specific code lives in call_llm() - identical shape to Agents 1 & 2's, so all three can be swapped to Anthropic in the same pass later. """ import json import os import time import uuid from datetime import datetime, timezone from io import BytesIO import docx import gradio as gr from openai import OpenAI from PyPDF2 import PdfReader from reportlab.lib import colors from reportlab.lib.pagesizes import LETTER from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import inch from reportlab.platypus import ( SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, ListFlowable, ListItem, PageBreak, ) try: import openpyxl XLSX_AVAILABLE = True except ImportError: XLSX_AVAILABLE = False # ───────────────────────────────────────────────────────────────────────────── # Config # ───────────────────────────────────────────────────────────────────────────── MODEL = "gpt-4o" TEMPERATURE = 0.3 MAX_TOKENS = 4096 MAX_RETRIES = 3 RETRY_BACKOFF_SECONDS = 2 MAX_FIELD_CHARS = 4000 MAX_UPLOAD_CHARS = 6000 MAX_HANDOFF_CHARS = 6000 RUN_DIR = "/tmp/aipm_runs" os.makedirs(RUN_DIR, exist_ok=True) AGENT_VERSION = "1.0" UNSPECIFIED_MARKER = "UNSPECIFIED - see open questions" NOT_COMPUTABLE_MARKER = "NOT COMPUTABLE - no baseline provided" # ───────────────────────────────────────────────────────────────────────────── # System prompt # ───────────────────────────────────────────────────────────────────────────── SYSTEM_PROMPT = f"""You are AIPM, an AI project-management advisor built from Monte Turner's "Be an AI PM" series (Caveman Productions Media). You are the EXECUTION agent - the third and final agent in a 3-agent pipeline (Goals & Scope -> Planning -> Execution). Where the first two agents produce a plan, your job is to track REALITY against that plan, period over period. Your posture should feel less like a planner and more like an honest operations lead giving a status update: skeptical of vague progress claims, quick to name stagnation, precise about what can and can't actually be measured this period. This agent runs RECURRINGLY (weekly, biweekly, or per sprint) rather than once. Each run may or may not have access to: a Planning agent handoff (the original baseline plan) and/or this agent's own prior-period output (for trend and continuity). Treat whichever of these ARE present as authoritative grounding, and be explicit and honest about what you cannot determine when they are absent - never fabricate a comparison point that doesn't exist. HARD RULES: 1. GROUNDING. Every status, date, or cost figure you state must trace to something provided - the Planning handoff, the prior Execution snapshot, or this period's manual input. Never invent completion percentages, dates, or dollar figures. 2. TWO DISTINCT MISSING-DATA MARKERS - do not conflate them: - Use "{UNSPECIFIED_MARKER}" when the user could have given specific info this period but the input was vague or silent on it. Add a specific open_questions entry explaining exactly what's missing. - Use "{NOT_COMPUTABLE_MARKER}" ONLY for variance/trend fields that are structurally impossible to compute because no Planning baseline and/or no prior Execution snapshot was uploaded. This is NOT an open question - it is an honest, expected description of standalone-mode limits. Do not add an open_questions entry for this marker; do not pretend a baseline exists to avoid using it. 3. CROSS-REFERENCING. If a Planning handoff was provided, status_report rows should reference its real wbs_id values. If no handoff was provided, assign lightweight ad hoc task IDs (T1, T2, ...) to whatever tasks the user names in their status input, and use those consistently across all sections in this response. 4. BE CRITICAL ABOUT STAGNATION. If a prior Execution snapshot shows a task has been "In Progress" or "Blocked" for multiple consecutive periods, say so plainly in its notes field and reflect it in overall_health - do not just log it as a neutral, unchanged status update. Recurring blockers are exactly what this agent exists to surface. 5. RISK REGISTER CONTINUITY. Populate risk_register_update from whichever of these are actually available: risks in a Goals & Scope handoff (if it was chained through Planning's backbone), risk entries carried forward from a prior Execution snapshot (update their status field - Materialized / Mitigated / Closed / Still Open / New), and anything the user explicitly describes as a risk in this period's free-text input. If none of these exist, return an empty array - do not invent risks to fill the section. 6. SPECIFICITY OVER POLISH. A status note like "STORY-2.1 blocked 2 weeks running - waiting on manual review set from client" beats "task is progressing well." 7. OUTPUT FORMAT. Respond with ONLY a single valid JSON object matching the schema in the user message. No prose before or after. No markdown code fences. """ JSON_SCHEMA_INSTRUCTIONS = f"""Return a single JSON object with exactly this shape: {{ "period_summary": {{ "reporting_period_start": str, "reporting_period_end": str, "cadence": str, "overall_health": "Green|Yellow|Red", "headline": str }}, "status_report": {{ "rows": [ {{"wbs_id_or_task": str, "task_name": str, "planned_status": str, "actual_status": "Not Started|In Progress|Blocked|Complete", "pct_complete": number, "notes": str}} ] }}, "variance": {{ "schedule_variance_summary": str, "cost_variance_summary": str, "rows": [ {{"wbs_id_or_task": str, "planned_date": str, "actual_or_forecast_date": str, "days_variance": str, "planned_cost": str, "actual_cost": str, "cost_variance": str}} ] }}, "issues_and_blockers": [ {{"issue": str, "related_wbs_id": str, "raised_date": str, "status": "Open|Resolved", "owner": str, "impact": str}} ], "risk_register_update": [ {{"risk": str, "source": "goals_and_scope|planning|execution", "status": "Materialized|Mitigated|Closed|Still Open|New", "notes": str}} ], "change_log": [ {{"change": str, "reason": str, "impact": str, "date": str}} ], "next_period_actions": [ {{"action": str, "owner": str, "due_date": str, "related_wbs_id": str}} ], "open_questions": [str] }} Rules for this JSON: - If no Planning backbone AND no prior Execution snapshot were provided, every "variance.rows" entry's date/cost fields must use "{NOT_COMPUTABLE_MARKER}" - do not fabricate planned dates or costs that were never given to you. - "status_report.rows" must cover every WBS phase/task from the Planning backbone if one was provided - do not silently drop tasks from the report. - If a prior Execution snapshot was provided, every task that was NOT "Complete" last period must reappear in this period's status_report.rows, even if just to confirm it's still blocked or still in progress. - "risk_register_update" and "issues_and_blockers" should be empty arrays (not invented content) if nothing in the provided inputs supports them. - "open_questions" should be empty if there is genuinely nothing to flag - do not invent a question just to fill the field. """ # ───────────────────────────────────────────────────────────────────────────── # File / JSON extraction # ───────────────────────────────────────────────────────────────────────────── def extract_text_from_file(uploaded_file): # Same bugfix applied in Goals & Scope v5.0 and Planning v2.1: a plain string # filepath has no .name attribute, which previously broke extension detection # for Gradio's file_count="multiple" uploads. if isinstance(uploaded_file, str): name = uploaded_file.lower() path_for_open = uploaded_file else: name = str(getattr(uploaded_file, "name", "uploaded_file")).lower() path_for_open = getattr(uploaded_file, "name", uploaded_file) try: with open(path_for_open, "rb") as f: data = f.read() except Exception: data = b"" text = "" try: if name.endswith(".pdf"): reader = PdfReader(BytesIO(data)) for page in reader.pages: text += page.extract_text() or "" elif name.endswith(".docx"): doc = docx.Document(BytesIO(data)) for p in doc.paragraphs: text += p.text + "\n" elif name.endswith((".txt", ".csv")): text = data.decode("utf-8", errors="ignore") elif name.endswith((".xlsx", ".xls")): if XLSX_AVAILABLE: wb = openpyxl.load_workbook(BytesIO(data), data_only=True) for sheet in wb.worksheets: text += f"\n[Sheet: {sheet.title}]\n" for row in sheet.iter_rows(values_only=True): row_text = "\t".join(str(c) if c is not None else "" for c in row) if row_text.strip(): text += row_text + "\n" else: text = "(openpyxl not installed - cannot read Excel file)" else: text = f"(Unsupported file type: {name})" except Exception as e: text = f"(Error reading {name}: {e})" return text.strip() def extract_json_upload(uploaded_file, expected_type): """Reads an uploaded .json handoff file and validates its handoff_type. Used for both the Planning backbone (expected_type='planning_output') and the prior Execution snapshot (expected_type='execution_output') - same function, two different upstream sources, per this agent's two-input-chain design.""" if uploaded_file is None: return None, None try: path = uploaded_file if isinstance(uploaded_file, str) else getattr(uploaded_file, "name", None) with open(path, "r") as f: raw = f.read() data = json.loads(raw) if data.get("handoff_type") != expected_type: return None, f"\u26a0 Uploaded file doesn't look like a {expected_type} package - ignoring it." return data, None except Exception as e: return None, f"\u26a0 Could not read uploaded JSON file: {e}" def truncate(text, limit): if text is None: return "" text = str(text) if len(text) <= limit: return text return text[:limit] + f"\n...[truncated at {limit} chars]" # ───────────────────────────────────────────────────────────────────────────── # LLM call - only function that needs to change on Anthropic migration # ───────────────────────────────────────────────────────────────────────────── def call_llm(system_msg, user_prompt): api_key = os.getenv("OPENAI_API_KEY") if not api_key: raise ValueError( "OPENAI_API_KEY is not set. Go to Space Settings -> Repository Secrets " "and add OPENAI_API_KEY." ) client = OpenAI(api_key=api_key) last_error = None for attempt in range(1, MAX_RETRIES + 1): try: completion = client.chat.completions.create( model=MODEL, temperature=TEMPERATURE, max_tokens=MAX_TOKENS, response_format={"type": "json_object"}, messages=[ {"role": "system", "content": system_msg}, {"role": "user", "content": user_prompt}, ], ) raw = completion.choices[0].message.content return json.loads(raw) except json.JSONDecodeError as e: last_error = f"Model returned invalid JSON on attempt {attempt}: {e}" except Exception as e: last_error = f"API error on attempt {attempt}: {e}" if attempt < MAX_RETRIES: time.sleep(RETRY_BACKOFF_SECONDS * attempt) raise RuntimeError(f"LLM call failed after {MAX_RETRIES} attempts. Last error: {last_error}") # ───────────────────────────────────────────────────────────────────────────── # Coverage validation - same class of guardrail as Agents 1 & 2, adapted for # Execution's two-source coverage requirement (backbone AND prior snapshot) # ───────────────────────────────────────────────────────────────────────────── def validate_coverage(data, backbone_data, prior_snapshot_data): """Two independent coverage checks, both code-level (not just prompt instructions), mirroring the lesson from Agents 1 & 2: completeness guarantees are more reliable enforced in code than in prose. 1. If a Planning backbone was provided, every WBS phase/task must have a status_report row - nothing silently dropped from this period's report. 2. If a prior Execution snapshot was provided, every task that was NOT Complete last period must reappear this period, even if just to confirm it's still stuck - this is the guardrail against a blocker quietly disappearing from reporting rather than actually being resolved. """ open_qs = data.setdefault("open_questions", []) status_rows = data.get("status_report", {}).get("rows", []) status_refs = {str(r.get("wbs_id_or_task", "")).strip() for r in status_rows} if backbone_data: wbs_items = backbone_data.get("wbs", []) backbone_ids = {str(w.get("wbs_id", "")).strip() for w in wbs_items if w.get("wbs_id")} for wbs_id in backbone_ids: if wbs_id not in status_refs: open_qs.append( f"No status_report entry appears tied to WBS item '{wbs_id}' from " f"the Planning backbone - confirm whether this task should still " f"be tracked." ) if prior_snapshot_data: prior_rows = prior_snapshot_data.get("status_report", {}).get("rows", []) for prow in prior_rows: prior_id = str(prow.get("wbs_id_or_task", "")).strip() prior_status = prow.get("actual_status", "") if prior_id and prior_status != "Complete" and prior_id not in status_refs: open_qs.append( f"'{prior_id}' was not Complete as of the last Execution snapshot " f"(status was '{prior_status}') but does not appear in this " f"period's status_report - confirm it wasn't silently dropped." ) return data def validate_unspecified_markers(data): """Mirrors Planning v2.2's guardrail: if the UNSPECIFIED marker (vague/missing input the user could have supplied) appears anywhere but open_questions came back empty, flag it. Deliberately does NOT scan for the NOT COMPUTABLE marker - that one is an expected, correct description of standalone-mode limits, not a gap, and flagging it would create guardrail noise on every standalone run.""" found = {"flag": False} def scan(obj): if found["flag"]: return if isinstance(obj, dict): for v in obj.values(): scan(v) elif isinstance(obj, list): for v in obj: scan(v) elif isinstance(obj, str) and UNSPECIFIED_MARKER in obj: found["flag"] = True scan(data.get("status_report", {})) scan(data.get("variance", {})) scan(data.get("issues_and_blockers", [])) scan(data.get("risk_register_update", [])) open_qs = data.setdefault("open_questions", []) if found["flag"] and not open_qs: open_qs.append( "One or more fields were marked UNSPECIFIED but no open_questions were " "logged explaining why - review this period's report for unresolved gaps." ) return data # ───────────────────────────────────────────────────────────────────────────── # PDF rendering # ───────────────────────────────────────────────────────────────────────────── def _styles(): styles = getSampleStyleSheet() styles.add(ParagraphStyle("AIPMTitle", parent=styles["Title"], textColor=colors.HexColor("#1a3c6e"), fontSize=18)) styles.add(ParagraphStyle("AIPMH2", parent=styles["Heading2"], textColor=colors.HexColor("#2563eb"), fontSize=13, spaceBefore=10, spaceAfter=6)) styles.add(ParagraphStyle("AIPMCell", parent=styles["Normal"], fontSize=8.5, leading=11)) return styles def _table_from_dicts(rows, columns, styles): """columns: (key, header_label, width_fraction) or (key, header_label, width_fraction, formatter_fn).""" header = [Paragraph(f"{c[1]}", styles["AIPMCell"]) for c in columns] data = [header] for row in rows: cells = [] for col in columns: key = col[0] formatter = col[3] if len(col) > 3 else None raw_val = row.get(key, "") val = formatter(raw_val) if formatter else str(raw_val) cells.append(Paragraph(val, styles["AIPMCell"])) data.append(cells) total_width = 7.0 * inch col_widths = [total_width * c[2] for c in columns] table = Table(data, colWidths=col_widths, repeatRows=1) table.setStyle(TableStyle([ ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1a3c6e")), ("TEXTCOLOR", (0, 0), (-1, 0), colors.white), ("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#cccccc")), ("VALIGN", (0, 0), (-1, -1), "TOP"), ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f4f6fb")]), ])) return table def _bullet_list(items, styles): return ListFlowable( [ListItem(Paragraph(str(i), styles["Normal"])) for i in items] or [ListItem(Paragraph("(none)", styles["Normal"]))], bulletType="bullet", ) def _health_badge(val): colors_map = {"Green": "#16a34a", "Yellow": "#ca8a04", "Red": "#dc2626"} color = colors_map.get(val, "#555555") return f'{val or "Unspecified"}' STATUS_COLUMNS = [ ("wbs_id_or_task", "ID", 0.10), ("task_name", "Task", 0.24), ("planned_status", "Planned", 0.14), ("actual_status", "Actual", 0.13), ("pct_complete", "% Complete", 0.10), ("notes", "Notes", 0.29), ] VARIANCE_COLUMNS = [ ("wbs_id_or_task", "ID", 0.10), ("planned_date", "Planned Date", 0.14), ("actual_or_forecast_date", "Actual/Forecast", 0.15), ("days_variance", "Days Var.", 0.10), ("planned_cost", "Planned Cost", 0.14), ("actual_cost", "Actual Cost", 0.14), ("cost_variance", "Cost Var.", 0.23), ] ISSUES_COLUMNS = [ ("issue", "Issue", 0.30), ("related_wbs_id", "WBS ID", 0.10), ("raised_date", "Raised", 0.13), ("status", "Status", 0.11), ("owner", "Owner", 0.13), ("impact", "Impact", 0.23), ] RISK_COLUMNS = [ ("risk", "Risk", 0.34), ("source", "Source", 0.16), ("status", "Status", 0.15), ("notes", "Notes", 0.35), ] CHANGE_COLUMNS = [ ("change", "Change", 0.32), ("reason", "Reason", 0.28), ("impact", "Impact", 0.24), ("date", "Date", 0.16), ] ACTIONS_COLUMNS = [ ("action", "Action", 0.38), ("owner", "Owner", 0.18), ("due_date", "Due Date", 0.16), ("related_wbs_id", "WBS ID", 0.28), ] def build_all_pdfs(run_dir, project_name, data): styles = _styles() safe_pn = (project_name or "Project").replace(" ", "_") pdfs = {} def new_doc(doc_title): path = os.path.join(run_dir, f"{safe_pn}_{doc_title.replace(' ', '_')}.pdf") doc = SimpleDocTemplate( path, pagesize=LETTER, leftMargin=0.75 * inch, rightMargin=0.75 * inch, topMargin=0.75 * inch, bottomMargin=0.75 * inch, ) story = [ Paragraph(project_name or "Project", styles["AIPMTitle"]), Spacer(1, 6), Paragraph(doc_title, styles["AIPMH2"]), Spacer(1, 10), ] return path, doc, story ps = data.get("period_summary", {}) variance = data.get("variance", {}) def period_summary_block(story): story.append(Paragraph( f"Period: {ps.get('reporting_period_start', '')} \u2013 " f"{ps.get('reporting_period_end', '')}  |  " f"Cadence: {ps.get('cadence', '')}  |  " f"Health: {_health_badge(ps.get('overall_health'))}", styles["Normal"], )) story.append(Spacer(1, 4)) story.append(Paragraph(f"{ps.get('headline', '')}", styles["Normal"])) story.append(Spacer(1, 10)) # Status & Variance Report path, doc, story = new_doc("Status & Variance Report") period_summary_block(story) story.append(Paragraph("Status Report", styles["AIPMH2"])) story.append(_table_from_dicts(data.get("status_report", {}).get("rows", []), STATUS_COLUMNS, styles)) story.append(Spacer(1, 10)) story.append(Paragraph("Variance", styles["AIPMH2"])) story.append(Paragraph(f"Schedule: {variance.get('schedule_variance_summary', '')}", styles["Normal"])) story.append(Paragraph(f"Cost: {variance.get('cost_variance_summary', '')}", styles["Normal"])) story.append(Spacer(1, 6)) story.append(_table_from_dicts(variance.get("rows", []), VARIANCE_COLUMNS, styles)) doc.build(story) pdfs["Status & Variance Report"] = path # Risk & Issues Report path, doc, story = new_doc("Risk & Issues Report") story.append(Paragraph("Issues & Blockers", styles["AIPMH2"])) story.append(_table_from_dicts(data.get("issues_and_blockers", []), ISSUES_COLUMNS, styles)) story.append(Spacer(1, 10)) story.append(Paragraph("Risk Register Update", styles["AIPMH2"])) story.append(_table_from_dicts(data.get("risk_register_update", []), RISK_COLUMNS, styles)) doc.build(story) pdfs["Risk & Issues Report"] = path # Change Log & Next-Period Plan path, doc, story = new_doc("Change Log & Next-Period Plan") story.append(Paragraph("Change Log", styles["AIPMH2"])) story.append(_table_from_dicts(data.get("change_log", []), CHANGE_COLUMNS, styles)) story.append(Spacer(1, 10)) story.append(Paragraph("Next-Period Actions", styles["AIPMH2"])) story.append(_table_from_dicts(data.get("next_period_actions", []), ACTIONS_COLUMNS, styles)) doc.build(story) pdfs["Change Log & Next-Period Plan"] = path # Combined Execution Guardrail Document path, doc, story = new_doc("Execution Guardrail Document (Combined)") period_summary_block(story) story.append(Paragraph("Status Report", styles["AIPMH2"])) story.append(_table_from_dicts(data.get("status_report", {}).get("rows", []), STATUS_COLUMNS, styles)) story.append(PageBreak()) story.append(Paragraph("Variance", styles["AIPMH2"])) story.append(Paragraph(f"Schedule: {variance.get('schedule_variance_summary', '')}", styles["Normal"])) story.append(Paragraph(f"Cost: {variance.get('cost_variance_summary', '')}", styles["Normal"])) story.append(Spacer(1, 6)) story.append(_table_from_dicts(variance.get("rows", []), VARIANCE_COLUMNS, styles)) story.append(PageBreak()) story.append(Paragraph("Issues & Blockers", styles["AIPMH2"])) story.append(_table_from_dicts(data.get("issues_and_blockers", []), ISSUES_COLUMNS, styles)) story.append(Spacer(1, 10)) story.append(Paragraph("Risk Register Update", styles["AIPMH2"])) story.append(_table_from_dicts(data.get("risk_register_update", []), RISK_COLUMNS, styles)) story.append(PageBreak()) story.append(Paragraph("Change Log", styles["AIPMH2"])) story.append(_table_from_dicts(data.get("change_log", []), CHANGE_COLUMNS, styles)) story.append(Spacer(1, 10)) story.append(Paragraph("Next-Period Actions", styles["AIPMH2"])) story.append(_table_from_dicts(data.get("next_period_actions", []), ACTIONS_COLUMNS, styles)) story.append(Spacer(1, 10)) story.append(Paragraph("Open Questions", styles["AIPMH2"])) story.append(_bullet_list(data.get("open_questions", []), styles)) doc.build(story) pdfs["Execution Guardrail Document (Combined)"] = path return pdfs # ───────────────────────────────────────────────────────────────────────────── # Main generation function # ───────────────────────────────────────────────────────────────────────────── def generate_execution_report(project_name, cadence, status_input, actuals_input, supporting_uploads, backbone_upload, prior_snapshot_upload): if not any([project_name, status_input, actuals_input, supporting_uploads, backbone_upload, prior_snapshot_upload]): return ( "\u26a0 Please provide at least this period's status, or upload a " "Planning backbone / prior Execution snapshot.", None, None, None, None, None, ) run_id = uuid.uuid4().hex[:10] run_dir = os.path.join(RUN_DIR, run_id) os.makedirs(run_dir, exist_ok=True) backbone_data, backbone_warning = extract_json_upload(backbone_upload, "planning_output") prior_data, prior_warning = extract_json_upload(prior_snapshot_upload, "execution_output") extra_text = "" if supporting_uploads: for f in supporting_uploads: extracted = extract_text_from_file(f) fname = f if isinstance(f, str) else getattr(f, "name", "uploaded file") fname = os.path.basename(fname) extra_text += f"\n\n[Extracted from {fname}]\n{extracted}" backbone_context = "Not provided - no Planning backbone was uploaded." if backbone_data: backbone_context = truncate(json.dumps({ "project_name": backbone_data.get("project_name"), "wbs": backbone_data.get("wbs"), "timeline": backbone_data.get("timeline"), "resource_allocation": backbone_data.get("resource_allocation"), "cost_plan": backbone_data.get("cost_plan"), }, indent=2), MAX_HANDOFF_CHARS) prior_context = "Not provided - no prior Execution snapshot was uploaded (this may be the first tracked period)." if prior_data: prior_context = truncate(json.dumps({ "period_summary": prior_data.get("period_summary"), "status_report": prior_data.get("status_report"), "risk_register_update": prior_data.get("risk_register_update"), "open_questions": prior_data.get("open_questions"), }, indent=2), MAX_HANDOFF_CHARS) context = f"""Project: {project_name} Reporting Cadence: {cadence} Planning Backbone (from Agent 2, if provided - the baseline plan): {backbone_context} Prior Execution Snapshot (from this agent's own previous run, if provided): {prior_context} This Period's Status (manual input): {truncate(status_input, MAX_FIELD_CHARS) or 'Not provided'} Actuals - dates / completion / spend (manual input): {truncate(actuals_input, MAX_FIELD_CHARS) or 'Not provided'} Uploaded Supporting Documents Content (any type): {truncate(extra_text, MAX_UPLOAD_CHARS) or 'None uploaded'} Date: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')} """ user_prompt = f"{context}\n\n{JSON_SCHEMA_INSTRUCTIONS}" try: data = call_llm(SYSTEM_PROMPT, user_prompt) except Exception as e: return (f"\u26a0 Generation failed: {e}", None, None, None, None, None) data = validate_coverage(data, backbone_data, prior_data) data = validate_unspecified_markers(data) try: pdfs = build_all_pdfs(run_dir, project_name, data) except Exception as e: return (f"\u26a0 Document rendering failed: {e}", None, None, None, None, None) # Self-referential handoff: this run's output becomes NEXT run's "prior snapshot" input. snapshot = { "handoff_type": "execution_output", "handoff_version": "1.0", "source_agent": f"execution_v{AGENT_VERSION}", "upstream_backbone_used": bool(backbone_data), "upstream_prior_snapshot_used": bool(prior_data), "project_name": project_name, "cadence": cadence, "generated_at": datetime.now(timezone.utc).isoformat(), "period_summary": data.get("period_summary", {}), "status_report": data.get("status_report", {}), "variance": data.get("variance", {}), "issues_and_blockers": data.get("issues_and_blockers", []), "risk_register_update": data.get("risk_register_update", []), "change_log": data.get("change_log", []), "next_period_actions": data.get("next_period_actions", []), "open_questions": data.get("open_questions", []), } snapshot_path = os.path.join( run_dir, f"{(project_name or 'project').replace(' ', '_')}_execution_snapshot.json" ) with open(snapshot_path, "w") as f: json.dump(snapshot, f, indent=2) status_lines = [] if backbone_warning: status_lines.append(backbone_warning) if prior_warning: status_lines.append(prior_warning) status_lines.append( f"\u2705 Execution report generated for '{project_name}'" + (" (chained: Planning backbone" + (" + prior snapshot)" if prior_data else ")") if backbone_data else " (standalone mode - no baseline uploaded)") + "." ) status_lines.append( "\U0001f4cc Save the Handoff JSON below and upload it as \"Prior Execution " "Snapshot\" next period to get trend/variance-over-time." ) if data.get("open_questions"): status_lines.append(f"\u26a0 {len(data['open_questions'])} open question(s) flagged - see the combined document.") return ( "\n".join(status_lines), pdfs["Status & Variance Report"], pdfs["Risk & Issues Report"], pdfs["Change Log & Next-Period Plan"], pdfs["Execution Guardrail Document (Combined)"], snapshot_path, ) # ───────────────────────────────────────────────────────────────────────────── # Gradio UI # ───────────────────────────────────────────────────────────────────────────── with gr.Blocks(title="AIPM - Execution Reports") as demo: gr.HTML( "

\U0001f4c8 AIPM - Execution Agent

" "

Agent 3 of 3 \u00b7 Goals & Scope \u2192 Planning \u2192 Execution

" ) with gr.Row(): with gr.Column(scale=1): backbone_upload = gr.File( label="\U0001f517 Planning Backbone (optional, .json from Agent 2)", file_count="single", ) prior_snapshot_upload = gr.File( label="\U0001f504 Prior Execution Snapshot (optional, .json from this agent's last run)", file_count="single", ) project_name = gr.Textbox(label="Project Name", placeholder="e.g. Smarter Job Hunt Sprint", lines=1) cadence = gr.Radio( choices=["Weekly", "Biweekly", "Sprint"], value="Weekly", label="\U0001f4c5 Reporting Cadence", ) status_input = gr.Textbox( label="This Period's Status (what got done, what's blocked, what's next)", placeholder="e.g.\nScrape validation fix shipped and tested.\nMatching reweight logic still blocked - manual review set not yet assembled.", lines=6, ) actuals_input = gr.Textbox( label="Actuals - dates / completion / spend (optional, paste directly)", placeholder="e.g.\nSTORY-1.1 completed 2026-07-23 (1 day early)\nAnthropic API spend to date: $12", lines=4, ) uploads = gr.File( label="Upload Supporting Documents (optional, any format)", file_count="multiple", ) submit_btn = gr.Button("\U0001f680 Generate Execution Report", variant="primary") with gr.Column(scale=1): status = gr.Textbox(label="Status", interactive=False, lines=5) pdf_sv = gr.File(label="\U0001f4e5 Status & Variance Report") pdf_ri = gr.File(label="\U0001f4e5 Risk & Issues Report") pdf_cn = gr.File(label="\U0001f4e5 Change Log & Next-Period Plan") pdf_combined = gr.File(label="\U0001f4e5 Execution Guardrail Document (Combined)") snapshot_file = gr.File(label="\U0001f517 Execution Snapshot - re-upload next period (JSON)") submit_btn.click( fn=generate_execution_report, inputs=[project_name, cadence, status_input, actuals_input, uploads, backbone_upload, prior_snapshot_upload], outputs=[status, pdf_sv, pdf_ri, pdf_cn, pdf_combined, snapshot_file], show_progress=True, ) gr.HTML( f"

" f"\u00a9 2026 Caveman Productions Media  \u00b7  AIPM Execution Agent v{AGENT_VERSION} " f" \u00b7  Agent 3 of 3

" ) if __name__ == "__main__": demo.launch(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="gray"))