This commit is contained in:
eddiesoehnel committed 2026-09-22 07:50:20 -06:00
commit 2bcc107c13
39 files changed
+2643

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
# Scripts
Python requires 3.10+ and the standard library. PowerShell commands target PowerShell 7 on Windows. Run from the repository root. See [implementation](../docs/implementation.md) for parameters.
| Script | Purpose and writes |
|---|---|
| [create_example_workbook.py](create_example_workbook.py) | Creates synthetic local/workflows.xlsx; refuses overwrite |
| [build_automations_calendar.py](build_automations_calendar.py) | Renders output/automations-calendar.html |
| [build_automation_results.py](build_automation_results.py) | Renders output/automations-results.html |
| [refresh_automations_calendar.ps1](refresh_automations_calendar.ps1) | Renders both dashboards; no collection |
| [collect_automation_statuses.ps1](collect_automation_statuses.ps1) | Reads explicitly selected local sources and writes a registry |
| [workflow-run-status.ps1](workflow-run-status.ps1) | Read-only receipt/log adapter sourced by collector |
| [copy-workbook.ps1](copy-workbook.ps1) | Copies explicit workbook path without overwrite |
| [aggregate_updates.py](aggregate_updates.py) | Aggregates explicitly selected local project notes into HTML |
| [audit_repository.py](audit_repository.py) | Read-only structural audit adapted from MIT repository template |
| [check_publication.py](check_publication.py) | Read-only metadata/link/privacy checks of public files |
Normal local demo and tests are reversible file operations. Live collection must be explicitly selected. Publication is separately authorized. No script sends messages or changes schedules.
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env python3
r"""Aggregate UPDATES.md files below an explicitly selected directory into local HTML."""
from __future__ import annotations
import argparse
import html
import os
from datetime import datetime
from pathlib import Path
DEFAULT_OUTPUT = Path(__file__).resolve().parent.parent / "output/updates-aggregate.html"
IGNORED_DIRS = {".git", ".hg", ".svn", ".venv", "node_modules"}
def find_update_files(folder: Path) -> list[Path]:
"""Return the folder's UPDATES.md files in alphabetical path order."""
matches: list[Path] = []
for current_dir, dir_names, file_names in os.walk(folder):
dir_names[:] = sorted(
(name for name in dir_names if name not in IGNORED_DIRS),
key=str.casefold,
)
if "UPDATES.md" in file_names:
matches.append(Path(current_dir) / "UPDATES.md")
return sorted(matches, key=lambda path: str(path).casefold())
def build_html(projects_dir: Path) -> str:
folders = sorted(
(path for path in projects_dir.iterdir() if path.is_dir()),
key=lambda path: path.name.casefold(),
)
sections: list[str] = []
nav_items: list[str] = []
total_files = 0
for index, folder in enumerate(folders):
update_files = find_update_files(folder)
total_files += len(update_files)
anchor = f"folder-{index}"
background_class = " red-background" if index % 2 else ""
nav_items.append(
f'<li><a href="#{anchor}">{html.escape(folder.name)}</a>'
f" ({len(update_files)})</li>"
)
file_blocks: list[str] = []
for update_file in update_files:
relative_path = update_file.relative_to(projects_dir)
content = update_file.read_text(encoding="utf-8-sig", errors="replace")
file_blocks.append(
'<article class="update-file">'
f"<h2>{html.escape(str(relative_path))}</h2>"
f"<pre>{html.escape(content)}</pre>"
"</article>"
)
if not file_blocks:
file_blocks.append('<p class="empty">No UPDATES.md files found.</p>')
sections.append(
f'<section id="{anchor}" class="project-folder{background_class}">'
f"<h1>{html.escape(folder.name)}</h1>"
+ "".join(file_blocks)
+ "</section>"
)
generated = datetime.now().astimezone().strftime("%Y-%m-%d %H:%M %Z")
return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Updates</title>
<style>
:root {{
color-scheme: dark;
--dark: #444444;
--steel: #587b91;
--steel-deep: #456579;
--white: #ffffff;
--cream: #eeeecd;
--jade: #52999a;
--pink: #ff1a51;
--line: #84a2b2;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
}}
* {{ box-sizing: border-box; }}
html {{ scroll-behavior: smooth; }}
body {{ margin: 0; color: var(--white); background: var(--steel); font: 15px/1.5 var(--font, Inter, ui-sans-serif, system-ui, sans-serif); }}
header, main {{ width: min(1400px, 90%); margin: 0 auto; }}
header {{ padding: 20px 0 24px; border-bottom: 1px solid #ffffff55; }}
header h1 {{ display: inline-block; margin: 0 0 18px; padding: 10px 14px; color: var(--white); background: var(--dark); border-left: 5px solid var(--pink); border-radius: 8px; box-shadow: 4px 4px 0 var(--pink); font-size: clamp(1.6rem, 3vw, 2.35rem); letter-spacing: .04em; }}
header p {{ margin: .25rem 0; color: #e4edf0; }}
nav {{ margin-top: 18px; }}
nav ul {{ display: flex; flex-wrap: wrap; gap: 8px; margin: 0; padding: 0; list-style: none; }}
nav li {{ margin: 0; }}
nav a {{ display: inline-block; padding: 7px 10px; color: #1649a5; background: var(--cream); border-radius: 9px; text-decoration: none; font-size: 13px; font-weight: 800; }}
nav a:hover, nav a:focus {{ color: var(--white); background: var(--pink); }}
.project-folder {{ margin: 14px 0; padding: 0; overflow: hidden; background: var(--dark); border: 1px solid #ffffff30; border-radius: 14px; box-shadow: 0 5px 18px #263e4c44; }}
.project-folder.red-background {{ background: var(--dark); }}
.project-folder > h1 {{ margin: 0; padding: 18px 20px; color: var(--white); border-left: 5px solid var(--jade); font-size: 1.35rem; letter-spacing: .04em; }}
.project-folder.red-background > h1 {{ border-left-color: var(--pink); }}
.update-file {{ margin: 0; padding: 16px 20px 20px; border-top: 1px solid #ffffff22; background: var(--steel-deep); }}
.update-file h2 {{ margin: 0 0 12px; color: var(--cream); font-size: .85rem; font-weight: 800; overflow-wrap: anywhere; }}
pre {{ margin: 0; padding: 14px; overflow-x: auto; white-space: pre-wrap; overflow-wrap: anywhere; color: var(--dark); background: #f7fbfc; border-left: 3px solid var(--jade); border-radius: 8px; font: 13px/1.6 ui-monospace, SFMono-Regular, Consolas, monospace; }}
.red-background .update-file pre {{ border-left-color: var(--pink); }}
.empty {{ margin: 0; padding: 18px 20px 20px; color: #e4edf0; font-style: italic; }}
@media (max-width: 700px) {{
header, main {{ width: 92%; }}
header {{ padding-top: 14px; }}
.project-folder > h1, .update-file {{ padding-left: 14px; padding-right: 14px; }}
nav ul {{ gap: 6px; }}
nav a {{ padding: 6px 8px; font-size: 12px; }}
}}
</style>
</head>
<body>
<header>
<h1>Project Updates</h1>
<p>{total_files} UPDATES.md files across {len(folders)} top-level folders.</p>
<p>Generated {html.escape(generated)} from the configured projects directory.</p>
<nav><ul>{"".join(nav_items)}</ul></nav>
</header>
<main>{"".join(sections)}</main>
</body>
</html>
"""
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--projects-dir",
type=Path,
required=True,
help="Explicit directory to scan; its contents will appear in the local output.",
)
parser.add_argument(
"--output",
type=Path,
default=DEFAULT_OUTPUT,
help=f"HTML output file (default: {DEFAULT_OUTPUT})",
)
args = parser.parse_args()
if not args.projects_dir.is_dir():
parser.error(f"Projects directory does not exist: {args.projects_dir}")
output = args.output.resolve()
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(build_html(args.projects_dir.resolve()), encoding="utf-8")
print(f"Wrote {output}")
if __name__ == "__main__":
main()
+370
View File
@@ -0,0 +1,370 @@
#!/usr/bin/env python3
"""Read-only structural audit for an AI-ready repository."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import re
import sys
PROFILES = {
"documentation-guide": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"CITATION.cff",
"docs",
},
"skill-workflow": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"AGENTS.md",
"skills.md",
"skills",
"templates",
"examples",
},
"software-automation": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"CONTRIBUTING.md",
"SECURITY.md",
"AGENTS.md",
"docs",
"scripts",
"tests",
},
"dataset": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"CITATION.cff",
"data",
"schemas",
"docs",
},
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("repository", type=Path, help="Repository root to inspect")
parser.add_argument(
"--profile",
choices=sorted(PROFILES),
required=True,
help="Approved repository profile",
)
parser.add_argument("--json", action="store_true", help="Emit JSON")
return parser.parse_args()
def read_version_from_citation(path: Path) -> str | None:
if not path.is_file():
return None
match = re.search(
r"(?m)^version:\s*[\"']?([^\"'\s#]+)",
path.read_text(encoding="utf-8-sig"),
)
return match.group(1) if match else None
def audit_content_index(root: Path, findings: list[dict[str, str]]) -> None:
path = root / "content-index.json"
if not path.is_file():
return
try:
index = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
findings.append({"level": "error", "message": f"content-index.json is invalid: {exc}"})
return
items = index.get("items")
if not isinstance(items, list):
findings.append(
{"level": "error", "message": "content-index.json items must be an array"}
)
return
content_ids: set[str] = set()
paths: set[str] = set()
for position, item in enumerate(items):
if not isinstance(item, dict):
findings.append(
{
"level": "error",
"message": f"content-index.json item {position + 1} must be an object",
}
)
continue
content_id = item.get("content_id")
declared = item.get("path")
if not content_id:
findings.append(
{
"level": "error",
"message": f"content-index.json item {position + 1} lacks content_id",
}
)
elif content_id in content_ids:
findings.append(
{
"level": "error",
"message": f"Duplicate content_id in content-index.json: {content_id}",
}
)
else:
content_ids.add(content_id)
if not declared:
findings.append(
{
"level": "error",
"message": f"content-index.json item {position + 1} lacks path",
}
)
elif declared in paths:
findings.append(
{
"level": "error",
"message": f"Duplicate path in content-index.json: {declared}",
}
)
else:
paths.add(declared)
declared_path = Path(declared)
if (
declared_path.is_absolute()
or ".." in declared_path.parts
or not (root / declared_path).is_file()
):
findings.append(
{
"level": "error",
"message": f"Indexed content path does not exist or is unsafe: {declared}",
}
)
def audit(root: Path, profile: str) -> dict:
findings: list[dict[str, str]] = []
if not root.is_dir():
return {
"repository": str(root),
"profile": profile,
"passed": False,
"findings": [{"level": "error", "message": "Repository path is not a directory"}],
}
for relative in sorted(PROFILES[profile]):
if not (root / relative).exists():
findings.append({"level": "error", "message": f"Missing required path: {relative}"})
manifest_path = root / "repository.json"
manifest = None
if manifest_path.is_file():
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
findings.append({"level": "error", "message": f"repository.json is invalid: {exc}"})
else:
for key in ("schema_version", "repository_id", "title", "description", "version", "entrypoints"):
if key not in manifest:
findings.append({"level": "error", "message": f"repository.json lacks key: {key}"})
entrypoints = manifest.get("entrypoints", {})
if isinstance(entrypoints, dict):
for audience in ("human", "ai"):
declared = entrypoints.get(audience)
if not declared:
findings.append(
{"level": "error", "message": f"Missing {audience} entrypoint declaration"}
)
elif not (root / declared).exists():
findings.append(
{
"level": "error",
"message": f"Declared {audience} entrypoint does not exist: {declared}",
}
)
else:
findings.append({"level": "error", "message": "entrypoints must be an object"})
variables_path = root / "repository-variables.json"
variables = None
if variables_path.is_file():
try:
variables = json.loads(variables_path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
findings.append(
{"level": "error", "message": f"repository-variables.json is invalid: {exc}"}
)
else:
for key in (
"schema_version",
"repository_profile",
"identity",
"repository",
"rights",
"skill_defaults",
"verified_by",
"verified_at",
):
if key not in variables:
findings.append(
{
"level": "error",
"message": f"repository-variables.json lacks key: {key}",
}
)
if manifest and variables:
identity = variables.get("identity", {})
variable_authors = [
item.get("name")
for item in identity.get("authors", [])
if isinstance(item, dict)
]
manifest_authors = [
item.get("name")
for item in manifest.get("authors", [])
if isinstance(item, dict)
]
comparisons = (
("authors", variable_authors, manifest_authors),
(
"publisher",
identity.get("publisher", {}).get("name"),
manifest.get("publisher", {}).get("name"),
),
(
"maintainer",
identity.get("maintainer", {}).get("name"),
manifest.get("maintenance", {}).get("maintainer"),
),
(
"repository",
variables.get("repository"),
{
key: manifest.get(key)
for key in (
"repository_id",
"name",
"title",
"canonical_url",
"organization",
)
},
),
(
"rights",
variables.get("rights"),
{
key: manifest.get("rights", {}).get(key)
for key in ("license", "license_file")
},
),
)
for label, variable_value, manifest_value in comparisons:
if variable_value != manifest_value:
findings.append(
{
"level": "error",
"message": (
f"{label} differs between repository-variables.json "
"and repository.json"
),
}
)
if variables and variables.get("repository_profile") != profile:
findings.append(
{
"level": "error",
"message": (
"repository_profile differs between repository-variables.json "
f"({variables.get('repository_profile')}) and requested audit ({profile})"
),
}
)
audit_content_index(root, findings)
version_path = root / "VERSION"
version = version_path.read_text(encoding="utf-8-sig").strip() if version_path.is_file() else None
if version and manifest and manifest.get("version") != version:
findings.append(
{
"level": "error",
"message": f"VERSION ({version}) differs from repository.json ({manifest.get('version')})",
}
)
citation_version = read_version_from_citation(root / "CITATION.cff")
if version and citation_version and citation_version != version:
findings.append(
{
"level": "error",
"message": f"VERSION ({version}) differs from CITATION.cff ({citation_version})",
}
)
readme = root / "README.md"
if readme.is_file() and not readme.read_text(encoding="utf-8-sig").strip():
findings.append({"level": "error", "message": "README.md is empty"})
return {
"repository": str(root.resolve()),
"profile": profile,
"passed": not any(item["level"] == "error" for item in findings),
"findings": findings,
}
def emit_markdown(result: dict) -> None:
print(f"# Repository Audit\n\n- Repository: `{result['repository']}`")
print(f"- Profile: `{result['profile']}`")
print(f"- Result: `{'PASS' if result['passed'] else 'FAIL'}`")
print("\n## Findings")
if not result["findings"]:
print("\n- No structural errors found.")
else:
for finding in result["findings"]:
print(f"\n- {finding['level'].upper()}: {finding['message']}")
def main() -> int:
args = parse_args()
result = audit(args.repository, args.profile)
if args.json:
print(json.dumps(result, indent=2))
else:
emit_markdown(result)
return 0 if result["passed"] else 1
if __name__ == "__main__":
sys.exit(main())
+146
View File
@@ -0,0 +1,146 @@
#!/usr/bin/env python3
"""Build a reusable automation-results dashboard from the canonical status registry."""
from __future__ import annotations
import argparse
import copy
import json
import shutil
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from build_automations_calendar import WORKSHEET_NAME, attach_statuses, normalize, read_statuses, read_workflow_rows
ROOT = Path(__file__).resolve().parent.parent
DEFAULT_WORKBOOK = ROOT / "local/workflows.xlsx"
DEFAULT_STATUS = ROOT / "examples/status.example.json"
DEFAULT_OUTPUT = ROOT / "output/automations-results.html"
DEFAULT_TEMPLATE = ROOT / "templates/automations-results.template.html"
def load_raw_status(path: Path) -> tuple[dict, list[dict]]:
if not path.is_file():
return {}, []
payload = json.loads(path.read_text(encoding="utf-8-sig"))
records = payload.get("records", []) if isinstance(payload, dict) else payload
return payload if isinstance(payload, dict) else {}, [item for item in records if isinstance(item, dict)]
def build_view(automations: list[dict], evidence: list[dict]) -> tuple[list[dict], list[dict]]:
managed_keys = set()
managed = []
for automation in automations:
managed_keys.add(normalize(automation["name"]))
managed.append({
"id": automation["id"],
"name": automation["name"],
"machine": automation["machine"],
"project": automation["project"],
"opsSegment": automation["opsSegment"],
"location": automation["location"],
"automationStatus": automation["status"],
"run": automation["run"],
"scope": "managed",
})
collected = []
for index, record in enumerate(evidence, start=1):
names = [record.get("name", ""), *(record.get("aliases") or [])]
linked = any(normalize(str(name)) in managed_keys for name in names if name)
outcome = str(record.get("outcome", "unknown")).casefold()
if outcome not in {"success", "failure", "unknown"}:
outcome = "unknown"
collected.append({
"id": f"evidence-{index}",
"name": str(record.get("name") or "Unnamed result"),
"aliases": record.get("aliases") or [],
"outcome": outcome,
"lastRun": record.get("lastRun") or record.get("last_run"),
"detail": record.get("detail") or record.get("message") or "",
"source": record.get("source") or "unknown",
"linked": linked,
"scope": "evidence",
})
return managed, collected
def build_payload(workbook_path: Path, status_path: Path) -> dict:
base_automations, used_range = read_workflow_rows(workbook_path)
status_meta, evidence = load_raw_status(status_path)
current_automations = copy.deepcopy(base_automations)
attach_statuses(current_automations, read_statuses(status_path))
managed, collected = build_view(current_automations, evidence)
days = []
for snapshot in status_meta.get("history", []) if isinstance(status_meta, dict) else []:
if not isinstance(snapshot, dict) or not snapshot.get("date"):
continue
snapshot_automations = copy.deepcopy(base_automations)
snapshot_records = [item for item in snapshot.get("records", []) if isinstance(item, dict)]
snapshot_statuses = {}
for record in snapshot_records:
names = [record.get("name", ""), *(record.get("aliases") or [])]
for name in names:
if name:
snapshot_statuses[normalize(str(name))] = record
attach_statuses(snapshot_automations, snapshot_statuses)
snapshot_managed, snapshot_collected = build_view(snapshot_automations, snapshot_records)
days.append({
"date": str(snapshot["date"]),
"generatedAt": snapshot.get("generatedAt"),
"managed": snapshot_managed,
"evidence": snapshot_collected,
})
if not days:
days = [{"date": datetime.now().astimezone().date().isoformat(), "generatedAt": status_meta.get("generatedAt"), "managed": managed, "evidence": collected}]
days.sort(key=lambda item: item["date"], reverse=True)
days = days[:3]
return {
"generatedAt": datetime.now(timezone.utc).isoformat(),
"registryGeneratedAt": status_meta.get("generatedAt"),
"registryNote": status_meta.get("note", ""),
"workbook": "configured workbook",
"workbookRange": f"{WORKSHEET_NAME}!{used_range}",
"statusRegistry": "configured status registry",
"managed": managed,
"evidence": collected,
"days": days,
}
def write_dashboard(template_path: Path, output_path: Path, payload: dict) -> None:
template = template_path.read_text(encoding="utf-8")
if "__AUTOMATION_RESULTS_DATA__" not in template:
raise ValueError("Results template is missing __AUTOMATION_RESULTS_DATA__")
data = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
html = template.replace("__AUTOMATION_RESULTS_DATA__", data, 1)
output_path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False, dir=output_path.parent, suffix=".tmp") as handle:
handle.write(html)
temp_path = Path(handle.name)
shutil.move(temp_path, output_path)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--workbook", type=Path, default=DEFAULT_WORKBOOK)
parser.add_argument("--status", type=Path, default=DEFAULT_STATUS)
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
parser.add_argument("--template", type=Path, default=DEFAULT_TEMPLATE)
args = parser.parse_args()
for label, path in (("Workbook", args.workbook), ("Status registry", args.status), ("Template", args.template)):
if not path.is_file():
parser.error(f"{label} not found: {path}")
payload = build_payload(args.workbook, args.status)
write_dashboard(args.template, args.output, payload)
print(f"Updated {args.output.resolve()} with {len(payload['managed'])} managed automations and {len(payload['evidence'])} evidence records")
if __name__ == "__main__":
main()
+237
View File
@@ -0,0 +1,237 @@
#!/usr/bin/env python3
"""Refresh automations-calendar.html from scheduled entries in the workflows tab."""
from __future__ import annotations
import argparse
import html
import json
import re
import shutil
import tempfile
import xml.etree.ElementTree as ET
import zipfile
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DEFAULT_WORKBOOK = ROOT / "local/workflows.xlsx"
DEFAULT_HTML = ROOT / "output/automations-calendar.html"
DEFAULT_STATUS = ROOT / "examples/status.example.json"
DEFAULT_TEMPLATE = ROOT / "templates/automations-calendar.template.html"
DAYS = ("Mon", "Tues", "Wed", "Thu", "Fri", "Sat", "Sun")
NS = {"m": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}
REL_NS = {"r": "http://schemas.openxmlformats.org/package/2006/relationships"}
DOC_REL = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"
def normalize(value: str) -> str:
return re.sub(r"[^a-z0-9]+", "", value.casefold())
def column_index(reference: str) -> int:
letters = re.match(r"[A-Z]+", reference.upper()).group(0)
result = 0
for letter in letters:
result = result * 26 + ord(letter) - 64
return result - 1
def column_letters(index: int) -> str:
result = ""
number = index + 1
while number:
number, remainder = divmod(number - 1, 26)
result = chr(65 + remainder) + result
return result
def shared_strings(archive: zipfile.ZipFile) -> list[str]:
try:
root = ET.fromstring(archive.read("xl/sharedStrings.xml"))
except KeyError:
return []
return ["".join(node.text or "" for node in item.findall(".//m:t", NS)) for item in root.findall("m:si", NS)]
def sheet_path(archive: zipfile.ZipFile, sheet_name: str) -> str:
workbook = ET.fromstring(archive.read("xl/workbook.xml"))
relation_id = None
for sheet in workbook.findall(".//m:sheet", NS):
if sheet.attrib.get("name", "").casefold() == sheet_name.casefold():
relation_id = sheet.attrib[DOC_REL]
break
if not relation_id:
raise ValueError(f"Worksheet not found: {sheet_name}")
rels = ET.fromstring(archive.read("xl/_rels/workbook.xml.rels"))
target = next(rel.attrib["Target"] for rel in rels.findall("r:Relationship", REL_NS) if rel.attrib["Id"] == relation_id)
target = target.lstrip("/")
return target if target.startswith("xl/") else f"xl/{target}"
def cell_value(cell: ET.Element, strings: list[str]):
cell_type = cell.attrib.get("t")
if cell_type == "inlineStr":
return "".join(node.text or "" for node in cell.findall(".//m:t", NS))
value_node = cell.find("m:v", NS)
if value_node is None or value_node.text is None:
return None
raw = value_node.text
if cell_type == "s":
return strings[int(raw)]
if cell_type in {"str", "e"}:
return raw
if cell_type == "b":
return raw == "1"
try:
number = float(raw)
return int(number) if number.is_integer() else number
except ValueError:
return raw
WORKSHEET_NAME = "workflows"
def read_workflow_rows(workbook_path: Path) -> tuple[list[dict], str]:
with zipfile.ZipFile(workbook_path) as archive:
strings = shared_strings(archive)
root = ET.fromstring(archive.read(sheet_path(archive, WORKSHEET_NAME)))
matrix: list[list] = []
for row in root.findall(".//m:sheetData/m:row", NS):
values: list = []
for cell in row.findall("m:c", NS):
index = column_index(cell.attrib["r"])
while len(values) <= index:
values.append(None)
values[index] = cell_value(cell, strings)
matrix.append(values)
if not matrix:
return [], "A1:A1"
headers = [str(value or "").strip() for value in matrix[0]]
header_map = {name.casefold(): index for index, name in enumerate(headers) if name}
if not header_map:
raise ValueError("workflows worksheet has no column headers")
last_header_column = max(header_map.values())
last_data_row = max(
(row_number for row_number, row in enumerate(matrix, start=1) if any(value not in (None, "") for value in row[: last_header_column + 1])),
default=1,
)
used_range = f"A1:{column_letters(last_header_column)}{last_data_row}"
required = ["name", "machine", "project", "ops segment", "mon", "tues", "wed", "thu", "fri", "sat", "sun", "other", "notes"]
missing = [name for name in required if name not in header_map]
if missing:
raise ValueError(f"{WORKSHEET_NAME} tab is missing required columns: {', '.join(missing)}")
records = []
for source_row, row in enumerate(matrix[1:], start=2):
def get(*names: str):
for name in names:
index = header_map.get(name)
if index is not None:
return row[index] if index < len(row) else None
return None
name = str(get("name") or "").strip()
if not name or name.casefold().startswith("do not edit"):
continue
schedule = {}
for day in DAYS:
raw = get(day.casefold())
minutes = None
cadence = ""
if isinstance(raw, (int, float)):
minutes = round((float(raw) % 1) * 24 * 60) % 1440
elif raw is not None and str(raw).strip():
cadence = str(raw).strip()
schedule[day] = {"raw": raw, "minutes": minutes, "cadence": cadence}
if not any(slot["raw"] not in (None, "") for slot in schedule.values()):
continue
records.append({
"id": source_row,
"name": name,
"machine": str(get("machine") or "Unspecified").strip(),
"project": str(get("project") or "Unspecified").strip(),
"location": str(get("operator", "location") or "Unspecified").strip(),
"opsSegment": str(get("ops segment") or "Unsorted").strip(),
"status": str(get("operational", "status") or "Active").strip(),
"other": str(get("other") or "").strip(),
"notes": str(get("notes") or "").strip(),
"schedule": schedule,
})
records.sort(key=lambda item: (item["opsSegment"].casefold(), item["project"].casefold(), item["name"].casefold()))
return records, used_range
def read_statuses(path: Path) -> dict[str, dict]:
if not path.exists():
return {}
payload = json.loads(path.read_text(encoding="utf-8-sig"))
records = payload.get("records", payload) if isinstance(payload, dict) else payload
result = {}
if isinstance(records, dict):
records = [{"name": name, **value} for name, value in records.items()]
for record in records or []:
if isinstance(record, dict) and record.get("name"):
names = [record["name"], *(record.get("aliases") or [])]
for name in names:
result[normalize(str(name))] = record
return result
def attach_statuses(records: list[dict], statuses: dict[str, dict]) -> None:
for item in records:
found = statuses.get(normalize(item["name"]))
if found:
outcome = str(found.get("outcome", "unknown")).casefold()
if outcome not in {"success", "failure", "unknown"}:
outcome = "unknown"
item["run"] = {
"outcome": outcome,
"lastRun": found.get("lastRun") or found.get("last_run"),
"detail": found.get("detail") or found.get("message") or "",
"source": found.get("source") or "status registry",
}
else:
item["run"] = {"outcome": "unknown", "lastRun": None, "detail": "No verifiable run result was collected.", "source": "none"}
def update_html(html_path: Path, records: list[dict], used_range: str, workbook_path: Path, template_path: Path = DEFAULT_TEMPLATE) -> None:
html_path.parent.mkdir(parents=True, exist_ok=True)
document = template_path.read_text(encoding="utf-8")
payload = json.dumps(records, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
document, replacements = re.subn(r" const automations = .*?;\r?\n const days =", lambda _: f" const automations = {payload};\n const days =", document, count=1, flags=re.S)
if replacements != 1:
raise ValueError("Could not locate the embedded automations data block in the HTML template")
generated = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
source_line = f"Source: configured workbook · {WORKSHEET_NAME}!{used_range} · Generated {generated}"
document, replacements = re.subn(r"Source: .*? · (?:cron|workflows)![^<]+", lambda _: html.escape(source_line), document, count=1)
if replacements != 1:
raise ValueError("Could not update the HTML source stamp")
with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False, dir=html_path.parent, suffix=".tmp") as handle:
handle.write(document)
temp_path = Path(handle.name)
shutil.move(temp_path, html_path)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--workbook", type=Path, default=DEFAULT_WORKBOOK)
parser.add_argument("--html", type=Path, default=DEFAULT_HTML)
parser.add_argument("--template", type=Path, default=DEFAULT_TEMPLATE)
parser.add_argument("--status", type=Path, default=DEFAULT_STATUS)
args = parser.parse_args()
if not args.workbook.is_file():
parser.error(f"Workbook not found: {args.workbook}")
if not args.template.is_file():
parser.error(f"HTML template not found: {args.template}")
records, used_range = read_workflow_rows(args.workbook)
attach_statuses(records, read_statuses(args.status))
update_html(args.html, records, used_range, args.workbook.resolve(), args.template)
print(f"Updated {args.html.resolve()} with {len(records)} automations from {WORKSHEET_NAME}!{used_range}")
if __name__ == "__main__":
main()
+87
View File
@@ -0,0 +1,87 @@
"""Read-only checks for metadata consistency, local links and common publication leaks.
This is a heuristic guardrail, not proof of anonymity or absence of secrets.
Ignored runtime data is excluded; independently inspect outputs before sharing.
"""
import ast
import json
import re
import subprocess
from pathlib import Path
from urllib.parse import urlparse, unquote
ROOT=Path(__file__).resolve().parent.parent
EXCLUDE={'.git','local','output','logs','__pycache__','.venv'}
BANNED={'.xlsx','.csv','.jsonl','.sql','.log','.pyc','.pem','.key','.pfx','.zip','.bak'}
def sensitive_findings(text, canonical_host):
findings=[]
checks={
'absolute Windows path':r'\b[A-Za-z]:[\\/]',
'absolute private Unix path':r'/(?:home|mnt|srv|opt)/[\w.-]+',
'private key material':r'-----BEGIN (?:RSA |OPENSSH |EC )?PRIVATE KEY-----',
'literal credential assignment':r"""(?i)\b(?:password|passwd|api[_-]?key|access[_-]?token|secret)\s*[=:]\s*["'][A-Za-z0-9_+/=-]{12,}["']""",
}
for label,pattern in checks.items():
if re.search(pattern,text): findings.append(label)
for email in re.findall(r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}',text):
if email.rsplit('@',1)[1] not in {'example.com','example.org','example.net'}:
findings.append('non-example email')
for address in re.findall(r'(?<![\w.])(?:\d{1,3}\.){3}\d{1,3}(?![\w.])',text):
if all(int(x)<256 for x in address.split('.')): findings.append('IPv4 address')
for url in re.findall(r'https?://[^\s<>"\x27)]+',text):
host=urlparse(url).hostname
if host not in {canonical_host,'schemas.openxmlformats.org','example.com','example.org','example.net'}:
findings.append(f'URL host requires review: {host}')
return sorted(set(findings))
def main():
errors=[]
manifest=json.loads((ROOT/'repository.json').read_text())
variables=json.loads((ROOT/'repository-variables.json').read_text())
host=urlparse(manifest['canonical_url']).hostname
version=(ROOT/'VERSION').read_text().strip()
if manifest['version']!=version: errors.append('manifest version mismatch')
for name in ['README.md','CHANGELOG.md','UPDATES.md']:
if version not in (ROOT/name).read_text(encoding='utf-8'): errors.append(f'{name}: version missing')
if manifest['authors']!=variables['identity']['authors']: errors.append('authors mismatch')
if manifest['rights']!=variables['rights']: errors.append('rights mismatch')
if manifest['canonical_url']!=variables['repository']['canonical_url']: errors.append('canonical URL mismatch')
for name in ['AUTHOR.md','LICENSE']:
for author in manifest['authors']:
if author['name'] not in (ROOT/name).read_text(encoding='utf-8'): errors.append(f'{name}: author missing')
if 'MIT License' not in (ROOT/'LICENSE').read_text(): errors.append('license mismatch')
declared=list(manifest['entrypoints'].values())+[x['path'] for x in manifest['contents']]
declared+=manifest['ai_retrieval']['read_first']+manifest['ai_retrieval']['retrieve_as_needed']
for name in declared:
p=Path(name)
if p.is_absolute() or '..' in p.parts or not (ROOT/p).exists(): errors.append(f'invalid declared path: {name}')
files=[]
for p in sorted(ROOT.rglob('*')):
if not p.is_file() or any(x in EXCLUDE for x in p.relative_to(ROOT).parts): continue
name=p.relative_to(ROOT).as_posix()
files.append(name)
if p.suffix.lower() in BANNED or p.name=='.env': errors.append(f'prohibited artifact: {name}')
try: text=p.read_text(encoding='utf-8-sig')
except UnicodeError:
errors.append(f'non-text file requires review: {name}')
continue
for finding in sensitive_findings(text,host): errors.append(f'{name}: {finding}')
if p.suffix=='.json': json.loads(text)
if p.suffix=='.py': ast.parse(text,filename=name)
if p.suffix=='.md':
for link in re.findall(r'\[[^\]]*\]\(([^)]+)\)',text):
link=link.split('#',1)[0]
if not link or '://' in link or link.startswith('mailto:'): continue
target=(p.parent/unquote(link)).resolve()
if not target.is_relative_to(ROOT.resolve()) or not target.exists(): errors.append(f'{name}: invalid link {link}')
# .gitignore does not protect files that were already tracked.
result=subprocess.run(['git','-c',f'safe.directory={ROOT.as_posix()}','-C',str(ROOT),'ls-files','-z'],capture_output=True,text=True)
if result.returncode: errors.append('git tracked-file scan failed')
for name in filter(None,result.stdout.split('\0')):
p=Path(name)
if any(x in EXCLUDE for x in p.parts) or p.suffix.lower() in BANNED or p.name=='.env': errors.append(f'prohibited tracked file: {name}')
print(json.dumps({'passed':not errors,'files_checked':len(files),'errors':errors},indent=2))
return bool(errors)
if __name__=='__main__': raise SystemExit(main())
+178
View File
@@ -0,0 +1,178 @@
[CmdletBinding()]
param(
[string]$OutputPath = (Join-Path $PSScriptRoot '../output/status.json'),
[string]$OverridesPath,
[string]$AliasesPath,
[string]$CodexAutomationsPath,
[switch]$IncludeScheduledTasks,
[string]$WorkflowRepository,
[string]$WorkflowId,
[string]$SchedulerLogRoot
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'workflow-run-status.ps1')
$records = [System.Collections.Generic.List[object]]::new()
$aliasesByTarget = @{}
if ($AliasesPath -and (Test-Path -LiteralPath $AliasesPath)) {
$aliasPayload = Get-Content -LiteralPath $AliasesPath -Raw | ConvertFrom-Json
foreach ($mapping in @($aliasPayload.mappings)) {
$target = [string]$mapping.target
if (-not [string]::IsNullOrWhiteSpace($target)) {
$aliasesByTarget[$target.ToLowerInvariant()] = @($mapping.aliases)
}
}
}
function Get-CalendarRefreshResult {
param([string]$Text)
# Only the latest run and statements about this refresh are evidence.
# Counts of failed managed jobs describe other automations, not this job.
$headers = [regex]::Matches($Text, '(?m)^- Run time:\s*([^\r\n]+)')
if (-not $headers.Count) { return [pscustomobject]@{ outcome = 'unknown'; lastRun = $null } }
$header = $headers[$headers.Count - 1]
$section = $Text.Substring($header.Index + $header.Length)
$outcome = 'unknown'
foreach ($line in ($section -split '\r?\n')) {
if ($line -notmatch 'refresh_automations_calendar\.ps1|requested refresh|refresh (?:failed|succeeded|completed)|script exited') { continue }
if ($line -match '(?i)\b(failed|blocked|rejected|denied|fatal)\b|exited with code [1-9]') { $outcome = 'failure' }
elseif ($line -match '(?i)\b(successfully|succeeded)\b|completed successfully') { $outcome = 'success' }
}
$timestamp = $null
$parsed = [DateTimeOffset]::MinValue
if ([DateTimeOffset]::TryParse($header.Groups[1].Value.Trim(), [ref]$parsed)) { $timestamp = $parsed.ToString('o') }
return [pscustomobject]@{ outcome = $outcome; lastRun = $timestamp }
}
function Get-ConfiguredAliases {
param([string[]]$Targets)
$found = [System.Collections.Generic.List[string]]::new()
foreach ($target in $Targets) {
if ([string]::IsNullOrWhiteSpace($target)) { continue }
$key = $target.ToLowerInvariant()
if ($aliasesByTarget.ContainsKey($key)) {
foreach ($alias in @($aliasesByTarget[$key])) {
if (-not [string]::IsNullOrWhiteSpace([string]$alias) -and -not $found.Contains([string]$alias)) { $found.Add([string]$alias) }
}
}
}
return @($found)
}
if ($IncludeScheduledTasks) {
try {
foreach ($task in Get-ScheduledTask -ErrorAction Stop) {
try {
$info = Get-ScheduledTaskInfo -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop
$hasRun = $info.LastRunTime -and $info.LastRunTime.Year -gt 2000
$outcome = if (-not $hasRun) { 'unknown' } elseif ($info.LastTaskResult -eq 267009) { 'unknown' } elseif ($info.LastTaskResult -eq 0) { 'success' } else { 'failure' }
$records.Add([pscustomobject]@{
name = $task.TaskName
aliases = @(Get-ConfiguredAliases -Targets @($task.TaskName, "$($task.TaskPath)$($task.TaskName)"))
outcome = $outcome
lastRun = if ($hasRun) { $info.LastRunTime.ToString('o') } else { $null }
detail = if ($hasRun) { "Windows Task Scheduler result: $($info.LastTaskResult). State: $($task.State)." } else { 'Windows Task Scheduler reports no completed run.' }
source = 'windows-task-scheduler'
})
} catch {
$records.Add([pscustomobject]@{ name = $task.TaskName; aliases = @(); outcome = 'unknown'; lastRun = $null; detail = $_.Exception.Message; source = 'windows-task-scheduler' })
}
}
} catch {
Write-Warning "Could not query Windows Task Scheduler: $($_.Exception.Message)"
}
}
if ($CodexAutomationsPath -and (Test-Path -LiteralPath $CodexAutomationsPath)) {
foreach ($folder in Get-ChildItem -LiteralPath $CodexAutomationsPath -Directory) {
$definition = Join-Path $folder.FullName 'automation.toml'
if (-not (Test-Path -LiteralPath $definition)) { continue }
$definitionText = Get-Content -LiteralPath $definition -Raw
$nameMatch = [regex]::Match($definitionText, '(?m)^name\s*=\s*"([^"]+)"')
$name = if ($nameMatch.Success) { $nameMatch.Groups[1].Value } else { $folder.Name }
$memory = Join-Path $folder.FullName 'memory.md'
$outcome = 'unknown'
$lastRun = $null
$detail = 'Codex automation exists, but no verifiable run result was found.'
if (Test-Path -LiteralPath $memory) {
$memoryItem = Get-Item -LiteralPath $memory
$lastRun = $memoryItem.LastWriteTime.ToString('o')
$tail = (Get-Content -LiteralPath $memory -Tail 120) -join "`n"
$failureMatches = [regex]::Matches($tail, '(?i)\b(failed|failure|blocked|fatal|error)\b')
$successMatches = [regex]::Matches($tail, '(?i)\b(success|successful|completed|passed|refreshed|created|updated|wrote)\b')
$lastFailure = if ($failureMatches.Count) { $failureMatches[$failureMatches.Count - 1].Index } else { -1 }
$lastSuccess = if ($successMatches.Count) { $successMatches[$successMatches.Count - 1].Index } else { -1 }
if ($lastSuccess -gt $lastFailure) { $outcome = 'success' }
elseif ($lastFailure -gt $lastSuccess) { $outcome = 'failure' }
$detail = "Best-effort result from the latest Codex automation memory for $($folder.Name); inspect memory.md when investigating."
if ($folder.Name -eq 'automations-calendar-refresh') {
$refreshResult = Get-CalendarRefreshResult -Text (Get-Content -LiteralPath $memory -Raw)
$outcome = $refreshResult.outcome
$lastRun = $refreshResult.lastRun
$detail = "Latest recorded calendar refresh: $outcome. Based on the refresh's own execution statement, excluding outcome counts for other jobs. Evidence: $($folder.Name)/memory.md"
}
}
$statusSource = 'codex-automation-memory'
$configuredAliases = @(Get-ConfiguredAliases -Targets @($name, $folder.Name))
$records.Add([pscustomobject]@{
name = $name
aliases = @(@($folder.Name) + $configuredAliases | Select-Object -Unique)
outcome = $outcome
lastRun = $lastRun
detail = $detail
source = $statusSource
})
}
}
if ($WorkflowRepository -or $WorkflowId -or $SchedulerLogRoot) {
if (-not $WorkflowRepository -or -not $WorkflowId) { throw 'WorkflowRepository and WorkflowId must be specified together.' }
$workflow = Get-WorkflowRunStatus -Repository $WorkflowRepository -WorkflowId $WorkflowId -LogRoot $SchedulerLogRoot
$records.Add([pscustomobject]@{
name = $WorkflowId
aliases = @(Get-ConfiguredAliases -Targets @($WorkflowId))
outcome = if ($workflow) { $workflow.outcome } else { 'unknown' }
lastRun = if ($workflow) { $workflow.time.ToString('o') } else { $null }
detail = if ($workflow) { $workflow.detail } else { 'No verified receipt or scheduler failure was found.' }
source = if ($workflow) { $workflow.source } else { 'none' }
})
}
if ($OverridesPath -and (Test-Path -LiteralPath $OverridesPath)) {
$overridePayload = Get-Content -LiteralPath $OverridesPath -Raw | ConvertFrom-Json
$overrideRecords = if ($overridePayload.records) { $overridePayload.records } else { $overridePayload }
foreach ($override in @($overrideRecords)) { $records.Add($override) }
}
$now = Get-Date
$today = $now.ToString('yyyy-MM-dd')
$target = [System.IO.Path]::GetFullPath($OutputPath)
$priorHistory = @()
if (Test-Path -LiteralPath $target) {
try {
$existingPayload = Get-Content -LiteralPath $target -Raw | ConvertFrom-Json
$priorHistory = @($existingPayload.history)
} catch {
$priorHistory = @()
}
}
$snapshot = [ordered]@{
date = $today
generatedAt = $now.ToUniversalTime().ToString('o')
records = @($records)
}
$history = @($priorHistory | Where-Object { $_.date -ne $today }) + @([pscustomobject]$snapshot)
$history = @($history | Sort-Object date -Descending | Select-Object -First 3)
$payload = [ordered]@{
generatedAt = $now.ToUniversalTime().ToString('o')
note = 'Success and failure are shown only when a local scheduler, Codex memory, or explicit override supplies evidence. Unknown is preserved instead of guessing.'
records = $records
history = $history
}
[System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($target)) | Out-Null
$temp = "$target.tmp"
$payload | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $temp -Encoding utf8
Move-Item -LiteralPath $temp -Destination $target -Force
Write-Output "Wrote $target with $($records.Count) status records."
+11
View File
@@ -0,0 +1,11 @@
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)][string]$Source,
[Parameter(Mandatory)][string]$Destination
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $Source -PathType Leaf)) { throw 'Source workbook is missing.' }
if (Test-Path -LiteralPath $Destination) { throw 'Destination exists; choose a new file path.' }
if ($PSCmdlet.ShouldProcess($Destination, 'Copy workbook')) {
[IO.File]::Copy([IO.Path]::GetFullPath($Source), [IO.Path]::GetFullPath($Destination), $false)
}
+45
View File
@@ -0,0 +1,45 @@
"""Create a synthetic XLSX workflows worksheet using only the standard library."""
import argparse
from pathlib import Path
from xml.sax.saxutils import escape
from zipfile import ZipFile, ZIP_DEFLATED
HEADERS = ['Name','Machine','Project','Ops Segment','Mon','Tues','Wed','Thu','Fri','Sat','Sun','Other','Notes']
ROWS = [
['Demo report','demo-worker','Demo analytics','Marketing',0.375,None,None,None,None,None,None,'','Synthetic report'],
['Demo backup','demo-worker','Demo maintenance','Systems',None,0.5,None,None,None,None,None,'','Synthetic backup'],
['Demo review','demo-worker','Demo planning','Strategy',None,None,'Hourly',None,None,None,None,'','Synthetic review'],
]
def create_workbook(path, rows=None, headers=None):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
matrix = [HEADERS if headers is None else headers] + (ROWS if rows is None else rows)
xml_rows = []
for rownum, row in enumerate(matrix, 1):
cells=[]
for col,value in enumerate(row):
if value is None: continue
ref=f'{chr(65+col)}{rownum}'
if isinstance(value,(int,float)):
cells.append(f'<c r="{ref}"><v>{value}</v></c>')
else:
cells.append(f'<c r="{ref}" t="inlineStr"><is><t>{escape(str(value))}</t></is></c>')
xml_rows.append(f'<row r="{rownum}">{"".join(cells)}</row>')
ns='http://schemas.openxmlformats.org/spreadsheetml/2006/main'
rel='http://schemas.openxmlformats.org/package/2006/relationships'
docrel='http://schemas.openxmlformats.org/officeDocument/2006/relationships'
with ZipFile(path,'w',ZIP_DEFLATED) as z:
z.writestr('[Content_Types].xml','<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>')
z.writestr('_rels/.rels',f'<Relationships xmlns="{rel}"><Relationship Id="rId1" Type="{docrel}/officeDocument" Target="xl/workbook.xml"/></Relationships>')
z.writestr('xl/workbook.xml',f'<workbook xmlns="{ns}" xmlns:r="{docrel}"><sheets><sheet name="workflows" sheetId="1" r:id="rId1"/></sheets></workbook>')
z.writestr('xl/_rels/workbook.xml.rels',f'<Relationships xmlns="{rel}"><Relationship Id="rId1" Type="{docrel}/worksheet" Target="worksheets/sheet1.xml"/></Relationships>')
z.writestr('xl/worksheets/sheet1.xml',f'<worksheet xmlns="{ns}"><sheetData>{"".join(xml_rows)}</sheetData></worksheet>')
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output',type=Path,default=Path(__file__).resolve().parent.parent/'local/workflows.xlsx')
args=parser.parse_args()
if args.output.exists(): parser.error('Output already exists; choose a new path.')
create_workbook(args.output)
print(f'Created synthetic workbook: {args.output}')
+20
View File
@@ -0,0 +1,20 @@
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Workbook,
[string]$Status = (Join-Path $PSScriptRoot '../examples/status.example.json'),
[string]$OutputDirectory = (Join-Path $PSScriptRoot '../output'),
[string]$Python = 'python'
)
$ErrorActionPreference = 'Stop'
# Offline rendering only. Collect real evidence separately with explicit source flags.
$pythonCommand = Get-Command $Python -ErrorAction Stop
$Html = Join-Path $OutputDirectory 'automations-calendar.html'
$Results = Join-Path $OutputDirectory 'automations-results.html'
& $pythonCommand.Source (Join-Path $PSScriptRoot 'build_automations_calendar.py') --workbook $Workbook --html $Html --status $Status
if ($LASTEXITCODE -ne 0) { throw "Calendar generation failed: $LASTEXITCODE" }
& $pythonCommand.Source (Join-Path $PSScriptRoot 'build_automation_results.py') --workbook $Workbook --status $Status --output $Results
if ($LASTEXITCODE -ne 0) { throw "Results generation failed: $LASTEXITCODE" }
foreach ($path in @($Html, $Results)) {
if (-not (Test-Path -LiteralPath $path) -or (Get-Item -LiteralPath $path).Length -eq 0) { throw "Missing or empty dashboard: $path" }
}
Write-Output 'Verified calendar and results dashboard outputs.'
+44
View File
@@ -0,0 +1,44 @@
function Get-WorkflowRunStatus {
param(
[Parameter(Mandatory)][string]$Repository,
[string]$LogRoot,
[Parameter(Mandatory)][string]$WorkflowId
)
$latest = $null
foreach ($file in @(Get-ChildItem -LiteralPath (Join-Path $Repository 'receipts') -Filter '*.json' -File -ErrorAction SilentlyContinue)) {
try {
$r = Get-Content -LiteralPath $file.FullName -Raw | ConvertFrom-Json
if ($r.skill.name -ne $WorkflowId) { continue }
$time = [DateTimeOffset]::Parse($r.finished_at)
$outcome = 'unknown'
if ($r.status -in @('failure','failed','blocked') -or @($r.failures | Where-Object { $null -ne $_ }).Count) { $outcome = 'failure' }
elseif ($r.status -eq 'success' -and $r.validation.deterministic -eq 'pass' -and $r.validation.manual -eq 'pass' -and $r.artifacts.checkpoint_advanced -eq $true) {
$base = [IO.Path]::GetFullPath($Repository).TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar
$report = [IO.Path]::GetFullPath((Join-Path $Repository $r.artifacts.report))
if (-not $report.StartsWith($base, [StringComparison]::OrdinalIgnoreCase)) { throw 'Report path escapes configured repository.' }
if ((Test-Path -LiteralPath $report -PathType Leaf) -and (Get-Item -LiteralPath $report).Length -gt 0) { $outcome = 'success' }
}
if (-not $latest -or $time -gt $latest.time) {
$latest = [pscustomobject]@{ time=$time; outcome=$outcome; detail="Validated workflow receipt: $($file.Name); outcome: $outcome."; source='workflow-run-receipt' }
}
} catch { Write-Warning "Unable to read workflow receipt $($file.Name)." }
}
# Startup failures occur before a task exists, so no workflow receipt can be written.
# Look back two weekly cycles; retain the latest completed run as the baseline.
$day = (Get-Date).Date.AddDays(-15)
while ($LogRoot -and $day -le (Get-Date).Date) {
$folder = Join-Path $LogRoot ($day.ToString('yyyy/MM/dd'))
foreach ($file in @(Get-ChildItem -LiteralPath $folder -Filter '*.log' -File -ErrorAction SilentlyContinue)) {
foreach ($hit in @(Select-String -LiteralPath $file.FullName -Pattern ('Scheduled run failed automationId=' + [regex]::Escape($WorkflowId) + '(?:\s|$)') -ErrorAction SilentlyContinue)) {
$stamp = [regex]::Match($hit.Line, '^\S+')
$time = [DateTimeOffset]::MinValue
if ($stamp.Success -and [DateTimeOffset]::TryParse($stamp.Value, [ref]$time) -and (-not $latest -or $time -gt $latest.time)) {
$message = [regex]::Match($hit.Line, 'errorMessage="([^"]+)"').Groups[1].Value
$latest = [pscustomobject]@{ time=$time; outcome='failure'; detail="Codex scheduler could not start the run: $message. Evidence: $($file.Name):$($hit.LineNumber)."; source='codex-scheduler-log' }
}
}
}
$day = $day.AddDays(1)
}
return $latest
}