Public Access
7728b6b4ac
Universal: Pre-Release / Build Pre-Release (${{ inputs.stability || github.ref_name }}) (push) Successful in 12s
Universal: PR Check / Branch Policy (pull_request) Successful in 1s
Universal: PR Check / Validate PR (pull_request) Failing after 7s
Universal: PR Check / Secret Scan (pull_request) Successful in 10s
Platform: mokocli CI / Gate 1: Code Quality (pull_request) Failing after 1m3s
Platform: mokocli CI / Gate 2: Unit Tests (8.1) (pull_request) Has been cancelled
Platform: mokocli CI / Gate 2: Unit Tests (8.2) (pull_request) Has been cancelled
Platform: mokocli CI / Gate 2: Unit Tests (8.3) (pull_request) Has been cancelled
Platform: mokocli CI / Gate 3: Self-Health Check (pull_request) Has been cancelled
Platform: mokocli CI / Gate 4: Governance (pull_request) Has been cancelled
Platform: mokocli CI / Gate 5: Template Integrity (pull_request) Has been cancelled
Platform: mokocli CI / CI Summary (pull_request) Has been cancelled
Universal: PR Check / Build RC Package (pull_request) Has been cancelled
Universal: PR Check / Report Issues (pull_request) Has been cancelled
MokoGitea instance rebrand to MokoGit. Content sweep over 265 files (ordered to avoid
moko-prefix doubling) plus path renames:
- .mokogitea/ -> .mokogit/ (repo + all mcp/servers/*)
- templates/mokogitea/ -> templates/mokogit/
- lib/Enterprise/MokoGiteaAdapter.php -> MokoGitAdapter.php (class MokoGitAdapter)
- mcp/servers/mokogitea_{skill,api} -> mokogit_{skill,api}; skills/mokogitea -> skills/mokogit
- automation/migrate_to_gitea.php -> migrate_to_mokogit.php
- env/secret names GITEA_* -> MOKOGIT_*
Note: ~/.claude/.mcp.json server flipped to @mokoconsulting/mcp-mokogit (publish pending).
1102 lines
38 KiB
PHP
1102 lines
38 KiB
PHP
#!/usr/bin/env php
|
|
<?php
|
|
|
|
/* Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
|
|
*
|
|
* SPDX-License-Identifier: GPL-3.0-or-later
|
|
*
|
|
* FILE INFORMATION
|
|
* DEFGROUP: mokocli.CLI
|
|
* INGROUP: mokocli
|
|
* REPO: https://git.mokoconsulting.tech/MokoConsulting/mokocli
|
|
* PATH: /cli/workflow_sync.php
|
|
* VERSION: 09.39.00
|
|
* BRIEF: Sync workflows from Generic → platform templates → live repos based on manifest.platform,
|
|
* plus a read-only health-check (--phase health) that alerts on repos missing synced workflows.
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/../lib/Enterprise/CliFramework.php';
|
|
|
|
use MokoCli\CliFramework;
|
|
|
|
class WorkflowSyncCli extends CliFramework
|
|
{
|
|
private const PLATFORM_TEMPLATES = [
|
|
'joomla' => 'Template-Joomla',
|
|
'go' => 'Template-Go',
|
|
// Template-MCP was renamed to Template-NPM. Both the 'mcp' platform (declared by
|
|
// the mcp-* repos in metadata) and 'npm'/'node' resolve to it. Pointing 'mcp' at the
|
|
// old name yielded a 301 → null → Generic fallback, which made cleanupOrphanedWorkflows
|
|
// strip every MCP-specific workflow as an "orphan". Keep this in sync with the org.
|
|
'mcp' => 'Template-NPM',
|
|
'npm' => 'Template-NPM',
|
|
'node' => 'Template-NPM',
|
|
'platform' => 'Template-Generic',
|
|
'generic' => 'Template-Generic',
|
|
// Dot-prefixed org repos (.mokogit, .vault, …) sync from Template-Dot. These repos
|
|
// carry no platform in metadata, so getRepoPlatform() maps them to 'dot' by name.
|
|
'dot' => 'Template-Dot',
|
|
// NOTE: 'dolibarr' intentionally omitted — Template-Dolibarr no longer exists and no
|
|
// repo declares platform=dolibarr; it falls through to DEFAULT_TEMPLATE (Generic).
|
|
];
|
|
|
|
private const DEFAULT_TEMPLATE = 'Template-Generic';
|
|
private const GENERIC_TEMPLATE = 'Template-Generic';
|
|
|
|
/**
|
|
* Canonical workflow directory in every repo.
|
|
*
|
|
* NOTE: This moved from '.mokogit/workflows' to '.mokogit/workflows' during the
|
|
* MokoGit → MokoGIT rebrand. The old constant was hardcoded inline in every path,
|
|
* so when the repos migrated the sync silently read/wrote a directory that no longer
|
|
* existed — Phase 1/2 both saw "0 workflows" and did nothing. Keep this in ONE place.
|
|
*/
|
|
private const WORKFLOW_DIR = '.mokogit/workflows';
|
|
|
|
/** Default ntfy endpoint for critical drift alerts (matches notify.yml / gitleaks.yml). */
|
|
private const DEFAULT_NTFY_URL = 'https://ntfy.mokoconsulting.tech';
|
|
private const DEFAULT_NTFY_TOPIC = 'mokogit-ops';
|
|
|
|
/**
|
|
* Workflows to exclude per platform during sync.
|
|
* Key = platform name (matching PLATFORM_TEMPLATES keys), Value = array of workflow filenames to skip.
|
|
*/
|
|
private const PLATFORM_EXCLUDES = [
|
|
'joomla' => ['deploy-manual.yml'],
|
|
// Dot-repos (.mokogit, .vault, …) are config/data repos: no build, no versioned
|
|
// releases, no deploy. Curate Template-Dot down to governance/security/hygiene only by
|
|
// excluding the build, versioning, release-pipeline, and deploy workflows. Applied in
|
|
// both Phase 1 (Generic → Template-Dot) and Phase 2 (Template-Dot → dot-repos).
|
|
'dot' => [
|
|
// build/test
|
|
'ci-generic.yml',
|
|
// versioning
|
|
'auto-bump.yml',
|
|
'version-set.yml',
|
|
// release pipeline
|
|
'auto-release.yml',
|
|
'pre-release.yml',
|
|
'rc-revert.yml',
|
|
'cascade-dev.yml',
|
|
// deploy (never in Generic, excluded defensively)
|
|
'deploy-dev.yml',
|
|
'deploy-prod.yml',
|
|
'deploy-rc.yml',
|
|
],
|
|
];
|
|
|
|
private int $updated = 0;
|
|
private int $created = 0;
|
|
private int $skipped = 0;
|
|
private int $errors = 0;
|
|
|
|
protected function configure(): void
|
|
{
|
|
$this->setDescription('Sync workflows from Generic → platform templates → live repos based on manifest.platform');
|
|
$this->addArgument('--mokogit-url', 'MokoGit URL (default: https://git.mokoconsulting.tech)', 'https://git.mokoconsulting.tech');
|
|
$this->addArgument('--token', 'MokoGit API token', '');
|
|
$this->addArgument('--org', 'Target organization', '');
|
|
$this->addArgument('--branch', 'Target branch (default: main)', 'main');
|
|
$this->addArgument('--phase', 'Phase to run: all, templates, repos, health (default: all)', 'all');
|
|
$this->addArgument('--platform-filter', 'Only sync repos matching this platform', '');
|
|
$this->addArgument('--repo-filter', 'Only sync/check these repos (comma-separated names)', '');
|
|
|
|
// Health-check (--phase health) options — all read-only unless an alert flag is set.
|
|
$this->addArgument('--alert-ntfy', 'On drift, send a critical ntfy push notification', false);
|
|
$this->addArgument('--ntfy-url', 'ntfy server URL', self::DEFAULT_NTFY_URL);
|
|
$this->addArgument('--ntfy-topic', 'ntfy topic', self::DEFAULT_NTFY_TOPIC);
|
|
$this->addArgument('--alert-issue', 'On drift, open/update a MokoGit issue on each affected repo', false);
|
|
}
|
|
|
|
protected function run(): int
|
|
{
|
|
$mokogitUrl = rtrim($this->getArgument('--mokogit-url'), '/');
|
|
$token = $this->getArgument('--token');
|
|
$org = $this->getArgument('--org');
|
|
$branch = $this->getArgument('--branch');
|
|
$phase = $this->getArgument('--phase');
|
|
$platformFilter = $this->getArgument('--platform-filter');
|
|
|
|
if ($token === '') {
|
|
$this->log('ERROR', '--token is required.');
|
|
return 1;
|
|
}
|
|
|
|
if ($org === '') {
|
|
$this->log('ERROR', '--org is required.');
|
|
return 1;
|
|
}
|
|
|
|
if (!in_array($phase, ['all', 'templates', 'repos', 'health'], true)) {
|
|
$this->log('ERROR', "--phase must be one of: all, templates, repos, health (got: {$phase})");
|
|
return 1;
|
|
}
|
|
|
|
// Health-check is a standalone, read-only phase — it never syncs.
|
|
if ($phase === 'health') {
|
|
return $this->runHealthCheck($mokogitUrl, $token, $org, $branch, $platformFilter);
|
|
}
|
|
|
|
$this->log('INFO', "Workflow Sync — org: {$org}, branch: {$branch}, phase: {$phase}");
|
|
|
|
if ($platformFilter !== '') {
|
|
$this->log('INFO', "Platform filter: {$platformFilter}");
|
|
}
|
|
|
|
if ($this->dryRun) {
|
|
$this->log('INFO', '[DRY RUN] No changes will be made.');
|
|
}
|
|
|
|
echo "\n";
|
|
|
|
// Phase 1: Sync Generic → Platform Templates
|
|
if ($phase === 'all' || $phase === 'templates') {
|
|
$result = $this->syncGenericToTemplates($mokogitUrl, $token, $org, $branch, $platformFilter);
|
|
|
|
if ($result !== 0) {
|
|
return $result;
|
|
}
|
|
}
|
|
|
|
// Phase 2: Sync Platform Templates → Live Repos
|
|
if ($phase === 'all' || $phase === 'repos') {
|
|
$result = $this->syncTemplatesToRepos($mokogitUrl, $token, $org, $branch, $platformFilter);
|
|
|
|
if ($result !== 0) {
|
|
return $result;
|
|
}
|
|
}
|
|
|
|
echo "\n";
|
|
$this->log('INFO', "Done: {$this->created} created, {$this->updated} updated, "
|
|
. "{$this->skipped} skipped, {$this->errors} error(s).");
|
|
|
|
return $this->errors > 0 ? 1 : 0;
|
|
}
|
|
|
|
/**
|
|
* Phase 1: Push all Generic workflows to each platform template repo.
|
|
* Skips platform-specific overrides (files that exist in the platform template but NOT in Generic).
|
|
*/
|
|
private function syncGenericToTemplates(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $org,
|
|
string $branch,
|
|
string $platformFilter
|
|
): int {
|
|
$this->log('INFO', '=== Phase 1: Sync Generic → Platform Templates ===');
|
|
echo "\n";
|
|
|
|
// Get all workflow files from Template-Generic
|
|
$genericWorkflows = $this->listWorkflows($mokogitUrl, $token, $org, self::GENERIC_TEMPLATE, $branch);
|
|
|
|
if ($genericWorkflows === null) {
|
|
$this->log('ERROR', 'Could not list workflows from ' . self::GENERIC_TEMPLATE);
|
|
return 1;
|
|
}
|
|
|
|
if (count($genericWorkflows) === 0) {
|
|
$this->log('WARN', 'No workflows found in ' . self::GENERIC_TEMPLATE);
|
|
return 0;
|
|
}
|
|
|
|
$this->log('INFO', 'Found ' . count($genericWorkflows) . ' workflow(s) in ' . self::GENERIC_TEMPLATE);
|
|
echo "\n";
|
|
|
|
// Get unique platform templates (exclude Generic itself)
|
|
$platformTemplates = array_unique(array_filter(
|
|
array_values(self::PLATFORM_TEMPLATES),
|
|
fn(string $t) => $t !== self::GENERIC_TEMPLATE
|
|
));
|
|
|
|
// If platform-filter is set, only sync to the matching template
|
|
if ($platformFilter !== '') {
|
|
$targetTemplate = self::PLATFORM_TEMPLATES[$platformFilter] ?? null;
|
|
|
|
if ($targetTemplate === null || $targetTemplate === self::GENERIC_TEMPLATE) {
|
|
$this->log('INFO', "Platform filter '{$platformFilter}' does not map to a non-generic template, skipping Phase 1.");
|
|
return 0;
|
|
}
|
|
|
|
$platformTemplates = [$targetTemplate];
|
|
}
|
|
|
|
fprintf(STDERR, "%-45s | %s\n", 'Template / File', 'Status');
|
|
fprintf(STDERR, "%s\n", str_repeat('-', 70));
|
|
|
|
foreach ($platformTemplates as $templateRepo) {
|
|
foreach ($genericWorkflows as $workflow) {
|
|
$filename = $workflow['name'];
|
|
// Skip platform-excluded workflows
|
|
$templatePlatform = array_search($templateRepo, self::PLATFORM_TEMPLATES, true);
|
|
if ($templatePlatform !== false && in_array($filename, self::PLATFORM_EXCLUDES[$templatePlatform] ?? [], true)) {
|
|
fprintf(STDERR, "%-45s | %s\n", "{$templateRepo}/{$filename}", 'EXCLUDED (platform)');
|
|
$this->skipped++;
|
|
continue;
|
|
}
|
|
$destPath = self::WORKFLOW_DIR . '/' . $filename;
|
|
$label = "{$templateRepo}/{$filename}";
|
|
|
|
// Get file content from Generic
|
|
$sourceContent = $this->getFileContent(
|
|
$mokogitUrl, $token, $org,
|
|
self::GENERIC_TEMPLATE, $destPath, $branch
|
|
);
|
|
|
|
if ($sourceContent === null) {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, 'ERROR (read source)');
|
|
$this->errors++;
|
|
continue;
|
|
}
|
|
|
|
$commitMsg = "chore: sync {$filename} from " . self::GENERIC_TEMPLATE . " [skip ci]";
|
|
|
|
$this->pushFile(
|
|
$mokogitUrl, $token, $org, $templateRepo,
|
|
$destPath, $sourceContent, $branch, $commitMsg, $label
|
|
);
|
|
}
|
|
}
|
|
|
|
echo "\n";
|
|
return 0;
|
|
}
|
|
|
|
/**
|
|
* Phase 2: Sync platform template workflows to live repos based on manifest.platform.
|
|
*/
|
|
private function syncTemplatesToRepos(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $org,
|
|
string $branch,
|
|
string $platformFilter
|
|
): int {
|
|
$this->log('INFO', '=== Phase 2: Sync Platform Templates → Live Repos ===');
|
|
echo "\n";
|
|
|
|
$repoFilter = $this->parseRepoFilter();
|
|
|
|
if ($repoFilter !== []) {
|
|
$this->log('INFO', 'Repo filter: ' . implode(', ', $repoFilter));
|
|
}
|
|
|
|
$repos = $this->fetchOrgRepos($mokogitUrl, $token, $org);
|
|
|
|
if ($repos === null) {
|
|
return 1;
|
|
}
|
|
|
|
$this->log('INFO', 'Found ' . count($repos) . " repo(s) in \"{$org}\".");
|
|
echo "\n";
|
|
|
|
fprintf(STDERR, "%-45s | %s\n", 'Repo / File', 'Status');
|
|
fprintf(STDERR, "%s\n", str_repeat('-', 70));
|
|
|
|
// Cache template workflows to avoid repeated API calls
|
|
$templateWorkflowCache = [];
|
|
|
|
foreach ($repos as $repoFullName) {
|
|
[, $repoName] = explode('/', $repoFullName, 2);
|
|
|
|
// Skip template repos
|
|
if (str_starts_with($repoName, 'Template-')) {
|
|
continue;
|
|
}
|
|
|
|
// Apply repo filter
|
|
if ($repoFilter !== [] && !in_array($repoName, $repoFilter, true)) {
|
|
continue;
|
|
}
|
|
|
|
// Read manifest.platform
|
|
$platform = $this->getRepoPlatform($mokogitUrl, $token, $org, $repoName, $branch);
|
|
|
|
// Apply platform filter
|
|
if ($platformFilter !== '' && $platform !== $platformFilter) {
|
|
continue;
|
|
}
|
|
|
|
// Resolve template
|
|
$templateRepo = self::PLATFORM_TEMPLATES[$platform] ?? self::DEFAULT_TEMPLATE;
|
|
|
|
// Get workflows from the template (cached)
|
|
if (!isset($templateWorkflowCache[$templateRepo])) {
|
|
$templateWorkflowCache[$templateRepo] =
|
|
$this->listWorkflows($mokogitUrl, $token, $org, $templateRepo, $branch);
|
|
}
|
|
|
|
$workflows = $templateWorkflowCache[$templateRepo];
|
|
|
|
// SAFETY: if the mapped template can't be listed (renamed/missing repo — e.g. a stale
|
|
// PLATFORM_TEMPLATES entry or a not-yet-created template), do NOT fall back to Generic.
|
|
// Falling back would treat Generic's set as authoritative and make
|
|
// cleanupOrphanedWorkflows() strip this repo's platform-specific workflows. Skip the
|
|
// repo and warn so the miss is visible instead of silently destructive.
|
|
if ($workflows === null) {
|
|
$this->log('WARN', "Template '{$templateRepo}' for platform '{$platform}' is unreachable"
|
|
. " — skipping {$repoName} (no sync, no cleanup).");
|
|
continue;
|
|
}
|
|
|
|
if (count($workflows) === 0) {
|
|
continue;
|
|
}
|
|
|
|
$templateFilenames = [];
|
|
|
|
foreach ($workflows as $workflow) {
|
|
$filename = $workflow['name'];
|
|
$templateFilenames[] = $filename;
|
|
$label = "{$repoFullName}/{$filename}";
|
|
// Skip platform-excluded workflows
|
|
if (in_array($filename, self::PLATFORM_EXCLUDES[$platform] ?? [], true)) {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, 'EXCLUDED (platform)');
|
|
$this->skipped++;
|
|
continue;
|
|
}
|
|
$destPath = self::WORKFLOW_DIR . '/' . $filename;
|
|
|
|
// Get source content from template
|
|
$sourceContent = $this->getFileContent(
|
|
$mokogitUrl, $token, $org,
|
|
$templateRepo, $destPath, $branch
|
|
);
|
|
|
|
if ($sourceContent === null) {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, 'ERROR (read source)');
|
|
$this->errors++;
|
|
continue;
|
|
}
|
|
|
|
$commitMsg = "chore: sync {$filename} from {$templateRepo} [skip ci]";
|
|
|
|
$this->pushFile(
|
|
$mokogitUrl, $token, $org, $repoName,
|
|
$destPath, $sourceContent, $branch, $commitMsg, $label
|
|
);
|
|
}
|
|
|
|
// Cleanup: delete workflows not in the template and not in custom/
|
|
$this->cleanupOrphanedWorkflows(
|
|
$mokogitUrl, $token, $org, $repoName, $branch,
|
|
$templateFilenames, $repoFullName
|
|
);
|
|
}
|
|
|
|
echo "\n";
|
|
return 0;
|
|
}
|
|
|
|
private const CUSTOM_PREFIX = 'custom/';
|
|
|
|
/**
|
|
* Parse --repo-filter into a list of repo names (empty ⇒ no filter, process all).
|
|
*
|
|
* @return string[]
|
|
*/
|
|
private function parseRepoFilter(): array
|
|
{
|
|
$raw = (string) $this->getArgument('--repo-filter');
|
|
|
|
return array_values(array_filter(array_map('trim', explode(',', $raw)), fn($n) => $n !== ''));
|
|
}
|
|
|
|
/**
|
|
* Delete workflows in a repo that are not in the template and not under custom/.
|
|
*/
|
|
private function cleanupOrphanedWorkflows(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $org,
|
|
string $repoName,
|
|
string $branch,
|
|
array $templateFilenames,
|
|
string $repoFullName
|
|
): void {
|
|
$repoWorkflows = $this->listWorkflows($mokogitUrl, $token, $org, $repoName, $branch);
|
|
|
|
if ($repoWorkflows === null) {
|
|
return;
|
|
}
|
|
|
|
foreach ($repoWorkflows as $item) {
|
|
$name = $item['name'] ?? '';
|
|
$type = $item['type'] ?? 'file';
|
|
|
|
// Skip directories (like custom/)
|
|
if ($type !== 'file') {
|
|
continue;
|
|
}
|
|
|
|
// Skip files that exist in the template
|
|
if (in_array($name, $templateFilenames, true)) {
|
|
continue;
|
|
}
|
|
|
|
// This file is not in the template — delete it
|
|
$destPath = self::WORKFLOW_DIR . '/' . $name;
|
|
$label = "{$repoFullName}/{$name}";
|
|
|
|
$this->deleteFile(
|
|
$mokogitUrl, $token, $org, $repoName,
|
|
$destPath, $branch,
|
|
"chore: remove orphaned workflow {$name} [skip ci]",
|
|
$label
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Delete a file from a repo via the MokoGit API.
|
|
*/
|
|
private function deleteFile(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $org,
|
|
string $repoName,
|
|
string $filePath,
|
|
string $branch,
|
|
string $commitMsg,
|
|
string $label
|
|
): void {
|
|
$existing = $this->apiRequest(
|
|
$mokogitUrl, $token, 'GET',
|
|
"/api/v1/repos/{$org}/{$repoName}/contents/{$filePath}?ref={$branch}"
|
|
);
|
|
|
|
if ($existing['code'] !== 200) {
|
|
return;
|
|
}
|
|
|
|
$data = json_decode($existing['body'], true);
|
|
$sha = $data['sha'] ?? '';
|
|
|
|
if ($this->dryRun) {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, 'WOULD DELETE');
|
|
return;
|
|
}
|
|
|
|
$payload = json_encode([
|
|
'sha' => $sha,
|
|
'message' => $commitMsg,
|
|
'branch' => $branch,
|
|
]);
|
|
|
|
$response = $this->apiRequest(
|
|
$mokogitUrl, $token, 'DELETE',
|
|
"/api/v1/repos/{$org}/{$repoName}/contents/{$filePath}",
|
|
$payload
|
|
);
|
|
|
|
if ($response['code'] === 200) {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, 'DELETED (orphaned)');
|
|
} else {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, "DELETE ERROR (HTTP {$response['code']})");
|
|
$this->errors++;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Push a file to a repo — create or update, skip if identical.
|
|
*/
|
|
private function pushFile(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $org,
|
|
string $repoName,
|
|
string $destPath,
|
|
string $localContent,
|
|
string $branch,
|
|
string $commitMsg,
|
|
string $label
|
|
): void {
|
|
$existing = $this->apiRequest(
|
|
$mokogitUrl,
|
|
$token,
|
|
'GET',
|
|
"/api/v1/repos/{$org}/{$repoName}/contents/"
|
|
. "{$destPath}?ref={$branch}"
|
|
);
|
|
|
|
$encodedContent = base64_encode($localContent);
|
|
|
|
if ($existing['code'] === 200) {
|
|
$data = json_decode($existing['body'], true);
|
|
$remoteSha = $data['sha'] ?? '';
|
|
$remoteContent = base64_decode($data['content'] ?? '');
|
|
|
|
if ($remoteContent === $localContent) {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, 'IDENTICAL (skipped)');
|
|
$this->skipped++;
|
|
return;
|
|
}
|
|
|
|
if ($this->dryRun) {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, 'WOULD UPDATE');
|
|
$this->updated++;
|
|
return;
|
|
}
|
|
|
|
$payload = json_encode([
|
|
'content' => $encodedContent,
|
|
'sha' => $remoteSha,
|
|
'message' => $commitMsg,
|
|
'branch' => $branch,
|
|
]);
|
|
|
|
$response = $this->apiRequest(
|
|
$mokogitUrl,
|
|
$token,
|
|
'PUT',
|
|
"/api/v1/repos/{$org}/{$repoName}/contents/" . $destPath,
|
|
$payload
|
|
);
|
|
|
|
if ($response['code'] === 200) {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, 'UPDATED');
|
|
$this->updated++;
|
|
} else {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, "ERROR (HTTP {$response['code']})");
|
|
$this->errors++;
|
|
}
|
|
} elseif ($existing['code'] === 404) {
|
|
if ($this->dryRun) {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, 'WOULD CREATE');
|
|
$this->created++;
|
|
return;
|
|
}
|
|
|
|
$payload = json_encode([
|
|
'content' => $encodedContent,
|
|
'message' => $commitMsg,
|
|
'branch' => $branch,
|
|
]);
|
|
|
|
$response = $this->apiRequest(
|
|
$mokogitUrl,
|
|
$token,
|
|
'POST',
|
|
"/api/v1/repos/{$org}/{$repoName}/contents/" . $destPath,
|
|
$payload
|
|
);
|
|
|
|
if ($response['code'] === 201) {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, 'CREATED');
|
|
$this->created++;
|
|
} else {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, "ERROR (HTTP {$response['code']})");
|
|
$this->errors++;
|
|
}
|
|
} else {
|
|
fprintf(STDERR, "%-45s | %s\n", $label, "ERROR (HTTP {$existing['code']})");
|
|
$this->errors++;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* List workflow files in a repo's .mokogit/workflows/ directory.
|
|
*/
|
|
private function listWorkflows(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $org,
|
|
string $repoName,
|
|
string $branch
|
|
): ?array {
|
|
$response = $this->apiRequest(
|
|
$mokogitUrl,
|
|
$token,
|
|
'GET',
|
|
"/api/v1/repos/{$org}/{$repoName}/contents/" . self::WORKFLOW_DIR . "?ref={$branch}"
|
|
);
|
|
|
|
if ($response['code'] !== 200) {
|
|
return null;
|
|
}
|
|
|
|
$data = json_decode($response['body'], true);
|
|
|
|
if (!is_array($data)) {
|
|
return null;
|
|
}
|
|
|
|
// Filter to only files (not directories)
|
|
return array_values(array_filter($data, fn($item) => ($item['type'] ?? '') === 'file'));
|
|
}
|
|
|
|
/**
|
|
* Get file content from a repo as a raw string.
|
|
*/
|
|
private function getFileContent(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $org,
|
|
string $repoName,
|
|
string $filePath,
|
|
string $branch
|
|
): ?string {
|
|
$response = $this->apiRequest(
|
|
$mokogitUrl,
|
|
$token,
|
|
'GET',
|
|
"/api/v1/repos/{$org}/{$repoName}/contents/{$filePath}?ref={$branch}"
|
|
);
|
|
|
|
if ($response['code'] !== 200) {
|
|
return null;
|
|
}
|
|
|
|
$data = json_decode($response['body'], true);
|
|
|
|
if (!is_array($data) || !isset($data['content'])) {
|
|
return null;
|
|
}
|
|
|
|
return base64_decode($data['content']);
|
|
}
|
|
|
|
/**
|
|
* Read a repo's platform from the MokoGit metadata API.
|
|
* Returns 'generic' if metadata is missing or has no platform field.
|
|
* (Replaces the retired .mokogit/manifest.xml lookup — platform now lives
|
|
* in the repo Metadata endpoint: GET /api/v1/repos/{owner}/{repo}/metadata.)
|
|
*/
|
|
private function getRepoPlatform(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $org,
|
|
string $repoName,
|
|
string $branch
|
|
): string {
|
|
// Dot-prefixed org repos (.mokogit, .vault, …) sync from Template-Dot regardless of
|
|
// metadata (they carry no platform field). Name is authoritative for these.
|
|
if (str_starts_with($repoName, '.')) {
|
|
return 'dot';
|
|
}
|
|
|
|
$response = $this->apiRequest(
|
|
$mokogitUrl,
|
|
$token,
|
|
'GET',
|
|
"/api/v1/repos/{$org}/{$repoName}/metadata"
|
|
);
|
|
|
|
if ($response['code'] !== 200) {
|
|
return 'generic';
|
|
}
|
|
|
|
$data = json_decode($response['body'], true);
|
|
|
|
if (!is_array($data) || empty($data['platform'])) {
|
|
return 'generic';
|
|
}
|
|
|
|
return strtolower(trim((string) $data['platform']));
|
|
}
|
|
|
|
/**
|
|
* Fetch all non-archived repos in an org (paginated).
|
|
*/
|
|
private function fetchOrgRepos(string $mokogitUrl, string $token, string $org): ?array
|
|
{
|
|
$this->log('INFO', "Fetching repos from org: {$org}");
|
|
|
|
$page = 1;
|
|
$repos = [];
|
|
|
|
while (true) {
|
|
$response = $this->apiRequest(
|
|
$mokogitUrl,
|
|
$token,
|
|
'GET',
|
|
"/api/v1/orgs/{$org}/repos?"
|
|
. "limit=50&page={$page}"
|
|
);
|
|
|
|
if ($response['code'] < 200 || $response['code'] >= 300) {
|
|
if ($page === 1) {
|
|
$this->log('ERROR', "Could not fetch repos "
|
|
. "(HTTP {$response['code']}).");
|
|
return null;
|
|
}
|
|
|
|
break;
|
|
}
|
|
|
|
$data = json_decode($response['body'], true);
|
|
|
|
if (!is_array($data) || count($data) === 0) {
|
|
break;
|
|
}
|
|
|
|
foreach ($data as $repo) {
|
|
if (!empty($repo['archived'])) {
|
|
continue;
|
|
}
|
|
|
|
$fullName = $repo['full_name'] ?? '';
|
|
|
|
if ($fullName !== '') {
|
|
$repos[] = $fullName;
|
|
}
|
|
}
|
|
|
|
$page++;
|
|
}
|
|
|
|
return $repos;
|
|
}
|
|
|
|
// =========================================================================
|
|
// Phase: health — read-only drift detection + alerting
|
|
// =========================================================================
|
|
|
|
private const HEALTH_ISSUE_MARKER = '[workflow-health]';
|
|
|
|
/**
|
|
* Health-check phase: verify every live repo still has the synced workflows its
|
|
* platform template provides, and (optionally) alert on drift.
|
|
*
|
|
* This closes the exact gap that caused the original outage: the sync treated an
|
|
* empty/missing workflow directory as "nothing to do" and moved on silently. Here
|
|
* we assert the canonical set is present and fail loudly (non-zero exit) when it
|
|
* is not — so a scheduled MokoGit Action, an ntfy push, and/or a MokoGit issue surface
|
|
* the problem instead of it rotting undetected.
|
|
*/
|
|
private function runHealthCheck(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $org,
|
|
string $branch,
|
|
string $platformFilter
|
|
): int {
|
|
$alertNtfy = (bool) $this->getArgument('--alert-ntfy');
|
|
$alertIssue = (bool) $this->getArgument('--alert-issue');
|
|
$ntfyUrl = rtrim((string) $this->getArgument('--ntfy-url'), '/');
|
|
$ntfyTopic = (string) $this->getArgument('--ntfy-topic');
|
|
|
|
$this->log('INFO', "Workflow Health-Check — org: {$org}, branch: {$branch}");
|
|
|
|
if ($platformFilter !== '') {
|
|
$this->log('INFO', "Platform filter: {$platformFilter}");
|
|
}
|
|
|
|
$repoFilter = $this->parseRepoFilter();
|
|
|
|
if ($repoFilter !== []) {
|
|
$this->log('INFO', 'Repo filter: ' . implode(', ', $repoFilter));
|
|
}
|
|
|
|
echo "\n";
|
|
|
|
$repos = $this->fetchOrgRepos($mokogitUrl, $token, $org);
|
|
|
|
if ($repos === null) {
|
|
return self::EXIT_FAILURE;
|
|
}
|
|
|
|
$this->log('INFO', 'Scanning ' . count($repos) . " repo(s) in \"{$org}\".");
|
|
echo "\n";
|
|
|
|
$templateCache = [];
|
|
$unhealthy = [];
|
|
$checked = 0;
|
|
|
|
foreach ($repos as $repoFullName) {
|
|
[, $repoName] = explode('/', $repoFullName, 2);
|
|
|
|
if (str_starts_with($repoName, 'Template-')) {
|
|
continue;
|
|
}
|
|
|
|
$platform = $this->getRepoPlatform($mokogitUrl, $token, $org, $repoName, $branch);
|
|
|
|
if ($platformFilter !== '' && $platform !== $platformFilter) {
|
|
continue;
|
|
}
|
|
|
|
if ($repoFilter !== [] && !in_array($repoName, $repoFilter, true)) {
|
|
continue;
|
|
}
|
|
|
|
// A repo that has no such branch is simply out of scope for this run
|
|
// (e.g. single-branch repos have no 'dev'), not unhealthy.
|
|
if (!$this->branchExists($mokogitUrl, $token, $org, $repoName, $branch)) {
|
|
continue;
|
|
}
|
|
|
|
$templateRepo = self::PLATFORM_TEMPLATES[$platform] ?? self::DEFAULT_TEMPLATE;
|
|
|
|
// Expected set = the template's workflows (cached), minus platform excludes.
|
|
// Do NOT fall back to Generic when the mapped template is unreachable — that would
|
|
// silently assess against the wrong baseline. Record null (missing) distinctly.
|
|
if (!array_key_exists($templateRepo, $templateCache)) {
|
|
$tpl = $this->listWorkflows($mokogitUrl, $token, $org, $templateRepo, $branch);
|
|
$templateCache[$templateRepo] = $tpl === null
|
|
? null
|
|
: array_map(fn($w) => $w['name'], $tpl);
|
|
}
|
|
|
|
if ($templateCache[$templateRepo] === null) {
|
|
$this->log('WARN', "Template '{$templateRepo}' for platform '{$platform}' is unreachable"
|
|
. " — cannot assess {$repoName}.");
|
|
continue;
|
|
}
|
|
|
|
$expected = array_values(array_diff(
|
|
$templateCache[$templateRepo],
|
|
self::PLATFORM_EXCLUDES[$platform] ?? []
|
|
));
|
|
|
|
// Template itself is empty — we can't assert anything meaningful.
|
|
if (count($expected) === 0) {
|
|
continue;
|
|
}
|
|
|
|
$repoList = $this->listWorkflows($mokogitUrl, $token, $org, $repoName, $branch);
|
|
$actual = array_map(fn($w) => $w['name'], $repoList ?? []);
|
|
|
|
$missing = $this->evaluateRepoHealth($expected, $actual);
|
|
$checked++;
|
|
|
|
if (count($missing) > 0) {
|
|
$unhealthy[$repoName] = [
|
|
'full' => $repoFullName,
|
|
'platform' => $platform,
|
|
'expected' => count($expected),
|
|
'present' => count(array_intersect($expected, $actual)),
|
|
'missing' => $missing,
|
|
];
|
|
}
|
|
}
|
|
|
|
echo "\n";
|
|
|
|
if (count($unhealthy) === 0) {
|
|
$this->success("All {$checked} in-scope repo(s) have their synced workflows on '{$branch}'.");
|
|
return self::EXIT_SUCCESS;
|
|
}
|
|
|
|
$rows = [];
|
|
|
|
foreach ($unhealthy as $repo => $info) {
|
|
$rows[] = [
|
|
$repo,
|
|
$info['platform'],
|
|
"{$info['present']}/{$info['expected']}",
|
|
(string) count($info['missing']),
|
|
];
|
|
}
|
|
|
|
$this->log('ERROR', count($unhealthy) . " of {$checked} repo(s) are MISSING synced workflows on '{$branch}':");
|
|
$this->table(['Repo', 'Platform', 'Present', 'Missing'], $rows);
|
|
|
|
if ($alertNtfy) {
|
|
$this->sendNtfyAlert($ntfyUrl, $ntfyTopic, $org, $branch, $unhealthy);
|
|
}
|
|
|
|
if ($alertIssue) {
|
|
foreach ($unhealthy as $repo => $info) {
|
|
$this->openHealthIssue($mokogitUrl, $token, $org, $repo, $branch, $info);
|
|
}
|
|
}
|
|
|
|
return self::EXIT_FAILURE;
|
|
}
|
|
|
|
/**
|
|
* Health verdict policy — given the workflows a repo SHOULD have (its platform
|
|
* template's set, minus platform excludes) and the workflows it ACTUALLY has,
|
|
* return the filenames that are missing. Non-empty result ⇒ repo is unhealthy.
|
|
*
|
|
* Default policy: every expected workflow must be present by exact filename.
|
|
* Extra files (repo-specific custom/ workflows, in-flight RC workflows) are
|
|
* ignored — we assert the canonical set is PRESENT, never that nothing else exists.
|
|
*
|
|
* @param string[] $expected Canonical workflow filenames the repo should carry.
|
|
* @param string[] $actual Workflow filenames currently in the repo.
|
|
* @return string[] Missing filenames (empty ⇒ healthy).
|
|
*/
|
|
private function evaluateRepoHealth(array $expected, array $actual): array
|
|
{
|
|
return array_values(array_diff($expected, $actual));
|
|
}
|
|
|
|
/**
|
|
* Return true when the given branch exists in the repo.
|
|
*/
|
|
private function branchExists(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $org,
|
|
string $repoName,
|
|
string $branch
|
|
): bool {
|
|
$response = $this->apiRequest(
|
|
$mokogitUrl, $token, 'GET',
|
|
"/api/v1/repos/{$org}/{$repoName}/branches/{$branch}"
|
|
);
|
|
|
|
return $response['code'] === 200;
|
|
}
|
|
|
|
/**
|
|
* Send a critical ntfy push notification about drift.
|
|
* Matches the org convention in .mokogit/workflows/notify.yml (Title/Priority/Tags headers).
|
|
*/
|
|
private function sendNtfyAlert(
|
|
string $ntfyUrl,
|
|
string $topic,
|
|
string $org,
|
|
string $branch,
|
|
array $unhealthy
|
|
): void {
|
|
if ($ntfyUrl === '' || $topic === '') {
|
|
$this->warn('ntfy alert requested but --ntfy-url/--ntfy-topic is empty; skipping.');
|
|
return;
|
|
}
|
|
|
|
$count = count($unhealthy);
|
|
$names = implode(', ', array_keys($unhealthy));
|
|
$title = "Workflow drift: {$count} repo(s) missing workflows";
|
|
$body = "Org {$org} ({$branch}): {$count} repo(s) missing synced " . self::WORKFLOW_DIR . "/.\n{$names}";
|
|
|
|
if ($this->dryRun) {
|
|
$this->log('INFO', "[DRY RUN] Would send critical ntfy to {$ntfyUrl}/{$topic}: {$title}");
|
|
return;
|
|
}
|
|
|
|
$ch = curl_init("{$ntfyUrl}/{$topic}");
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_POST, true);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
"Title: {$title}",
|
|
'Priority: urgent',
|
|
'Tags: rotating_light,warning',
|
|
]);
|
|
curl_exec($ch);
|
|
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
curl_close($ch);
|
|
|
|
if ($code >= 200 && $code < 300) {
|
|
$this->success("Sent critical ntfy alert to {$ntfyUrl}/{$topic}.");
|
|
} else {
|
|
$this->warn("ntfy alert failed (HTTP {$code}).");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Open a MokoGit issue on an affected repo describing the missing workflows.
|
|
* Idempotent: skips if an open issue carrying the marker already exists.
|
|
*/
|
|
private function openHealthIssue(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $org,
|
|
string $repoName,
|
|
string $branch,
|
|
array $info
|
|
): void {
|
|
// Idempotency — don't stack duplicate issues on repeated runs.
|
|
$existing = $this->apiRequest(
|
|
$mokogitUrl, $token, 'GET',
|
|
"/api/v1/repos/{$org}/{$repoName}/issues?state=open&type=issues&limit=50"
|
|
);
|
|
|
|
if ($existing['code'] === 200) {
|
|
$issues = json_decode($existing['body'], true) ?: [];
|
|
|
|
foreach ($issues as $iss) {
|
|
if (str_contains((string) ($iss['title'] ?? ''), self::HEALTH_ISSUE_MARKER)) {
|
|
$this->log('INFO', "{$repoName}: health issue already open (#{$iss['number']}), skipping.");
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
$missingList = implode("\n", array_map(fn($f) => "- `{$f}`", $info['missing']));
|
|
$title = self::HEALTH_ISSUE_MARKER . " Missing synced workflows on {$branch}";
|
|
$body = 'Automated health-check found this repository is missing '
|
|
. count($info['missing']) . " workflow(s) that its platform template "
|
|
. "(`{$info['platform']}`) provides in `" . self::WORKFLOW_DIR . "/` on `{$branch}`:\n\n"
|
|
. $missingList
|
|
. "\n\nRestore with:\n\n```\nphp bin/moko workflow:sync --org {$org} --branch {$branch} --token \$TOKEN\n```"
|
|
. "\n\n<sub>Filed by workflow_sync.php --phase health.</sub>";
|
|
|
|
if ($this->dryRun) {
|
|
$this->log('INFO', "[DRY RUN] Would open health issue on {$org}/{$repoName}.");
|
|
return;
|
|
}
|
|
|
|
$payload = json_encode(['title' => $title, 'body' => $body]);
|
|
|
|
$resp = $this->apiRequest(
|
|
$mokogitUrl, $token, 'POST',
|
|
"/api/v1/repos/{$org}/{$repoName}/issues",
|
|
$payload
|
|
);
|
|
|
|
if ($resp['code'] === 201) {
|
|
$data = json_decode($resp['body'], true);
|
|
$this->success("Opened health issue {$org}/{$repoName}#" . ($data['number'] ?? '?') . '.');
|
|
} else {
|
|
$this->warn("Failed to open issue on {$org}/{$repoName} (HTTP {$resp['code']}).");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Make an HTTP request to the MokoGit API.
|
|
*/
|
|
private function apiRequest(
|
|
string $mokogitUrl,
|
|
string $token,
|
|
string $method,
|
|
string $endpoint,
|
|
?string $body = null
|
|
): array {
|
|
$url = $mokogitUrl . $endpoint;
|
|
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, $url);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Content-Type: application/json',
|
|
'Accept: application/json',
|
|
"Authorization: token {$token}",
|
|
]);
|
|
|
|
if ($body !== null) {
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
|
|
}
|
|
|
|
$responseBody = curl_exec($ch);
|
|
$httpCode = (int) curl_getinfo(
|
|
$ch,
|
|
CURLINFO_HTTP_CODE
|
|
);
|
|
|
|
if (curl_errno($ch)) {
|
|
$error = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
return [
|
|
'code' => 0,
|
|
'body' => "cURL error: {$error}",
|
|
];
|
|
}
|
|
|
|
curl_close($ch);
|
|
|
|
return ['code' => $httpCode, 'body' => $responseBody];
|
|
}
|
|
}
|
|
|
|
$app = new WorkflowSyncCli();
|
|
exit($app->execute());
|