@temmo/cli 0.0.0-stage → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +16 -0
- package/.codex-plugin/plugin.json +30 -0
- package/.cursor-plugin/plugin.json +22 -0
- package/.mcp.json +18 -0
- package/LICENSE +202 -0
- package/README.md +82 -2
- package/THIRD_PARTY_NOTICES +32 -0
- package/commands/afk.md +17 -0
- package/deploy/build-ui.mjs +65 -0
- package/deploy/claude/README.md +16 -0
- package/deploy/claude/auto-mode.json +31 -0
- package/deploy/postgres/compose.yaml +26 -0
- package/deploy/temmo-runner.service +24 -0
- package/deploy/verify-ui.mjs +15 -0
- package/harness-core/README.md +27 -0
- package/harness-core/bin/harness.mjs +17 -0
- package/harness-core/package.json +10 -0
- package/harness-core/stage.mjs +108 -0
- package/harness-core/stages/commit.md +7 -0
- package/harness-core/stages/pr.md +7 -0
- package/harness-core/stages/push.md +7 -0
- package/hooks/codex-hooks.json +14 -0
- package/hooks/cursor-hooks.json +17 -0
- package/hooks/hooks.json +27 -0
- package/lib/acp/permission.js +72 -0
- package/lib/acp/sessionConfig.js +109 -0
- package/lib/activity.js +244 -0
- package/lib/agent-guard.js +72 -0
- package/lib/agents-route.js +55 -0
- package/lib/agents.js +213 -0
- package/lib/agui.js +255 -0
- package/lib/alerts.js +36 -0
- package/lib/analyze-otlp.js +46 -0
- package/lib/analyze-run-code.js +397 -0
- package/lib/analyze-sources.js +372 -0
- package/lib/approval-card.js +54 -0
- package/lib/approval-cli.js +53 -0
- package/lib/approval-request.js +81 -0
- package/lib/approval-signer.js +48 -0
- package/lib/approvals.js +295 -0
- package/lib/attachment-cache.js +236 -0
- package/lib/attachment.js +63 -0
- package/lib/blocked.js +20 -0
- package/lib/build-review.js +90 -0
- package/lib/builder/cli.js +90 -0
- package/lib/builder/policy.js +176 -0
- package/lib/builder/recover.js +189 -0
- package/lib/builder/run.js +240 -0
- package/lib/builder/settle.js +198 -0
- package/lib/builder/stage.js +240 -0
- package/lib/builder/state.js +73 -0
- package/lib/builder/supervisor.js +289 -0
- package/lib/builder-clean.js +223 -0
- package/lib/builder-code.cjs +67 -0
- package/lib/builder.js +9 -0
- package/lib/bus-postgres.js +281 -0
- package/lib/bus.js +349 -0
- package/lib/catalog/author.js +278 -0
- package/lib/catalog/dot.js +426 -0
- package/lib/catalog/pattern-model.js +193 -0
- package/lib/catalog/patterns.js +324 -0
- package/lib/catalog/projects.js +83 -0
- package/lib/catalog/records.js +2 -0
- package/lib/catalog/roster.js +70 -0
- package/lib/catalog/team-files.js +49 -0
- package/lib/catalog/teams.js +109 -0
- package/lib/claude-socket.js +333 -0
- package/lib/cli.js +741 -0
- package/lib/code-mode.js +45 -0
- package/lib/code-read-policy.yaml +9 -0
- package/lib/code-run.js +461 -0
- package/lib/codex-compact.js +141 -0
- package/lib/compaction.js +21 -0
- package/lib/config.js +424 -0
- package/lib/cursor-trace.js +248 -0
- package/lib/deep-link.js +20 -0
- package/lib/deliver-push.js +120 -0
- package/lib/delivery.js +28 -0
- package/lib/deploy-tree.js +227 -0
- package/lib/durable.js +404 -0
- package/lib/factory-tick.js +32 -0
- package/lib/family.js +63 -0
- package/lib/fetch-origin.js +53 -0
- package/lib/format.js +133 -0
- package/lib/harness-surface-cli.js +153 -0
- package/lib/harness-surface.js +486 -0
- package/lib/harness.js +271 -0
- package/lib/hook.mjs +291 -0
- package/lib/idle.js +40 -0
- package/lib/install-cursor.js +115 -0
- package/lib/install-opencode.js +105 -0
- package/lib/job.js +82 -0
- package/lib/land-cli.js +319 -0
- package/lib/land-member.js +64 -0
- package/lib/land.js +320 -0
- package/lib/lessons.js +223 -0
- package/lib/limit-alert.js +423 -0
- package/lib/limits.js +284 -0
- package/lib/machine-prompt.js +19 -0
- package/lib/merge-sweep.js +149 -0
- package/lib/messaging.js +1002 -0
- package/lib/mission-cli.js +103 -0
- package/lib/mission.js +241 -0
- package/lib/mode.js +215 -0
- package/lib/models.js +114 -0
- package/lib/names.js +86 -0
- package/lib/opencode-api.js +57 -0
- package/lib/opencode-plugin.mjs +313 -0
- package/lib/operator-token.js +78 -0
- package/lib/operator.js +187 -0
- package/lib/pad-activity.js +143 -0
- package/lib/pad-fresh.js +44 -0
- package/lib/pad.js +198 -0
- package/lib/pattern-cli.js +120 -0
- package/lib/pattern-compiler.js +68 -0
- package/lib/pattern-runs.js +795 -0
- package/lib/pattern-stall.js +58 -0
- package/lib/pattern-tick.js +45 -0
- package/lib/pattern-workflow.js +69 -0
- package/lib/pi-extension.mjs +98 -0
- package/lib/pi.js +57 -0
- package/lib/plugin-copy.js +76 -0
- package/lib/pm-review.js +32 -0
- package/lib/pm-workspace.js +87 -0
- package/lib/postgres.js +115 -0
- package/lib/pr-card.js +34 -0
- package/lib/probe.js +295 -0
- package/lib/process.js +67 -0
- package/lib/project-pause.js +23 -0
- package/lib/prune.js +793 -0
- package/lib/questions.js +250 -0
- package/lib/receipts.js +63 -0
- package/lib/reflect.js +962 -0
- package/lib/rename-migration.js +118 -0
- package/lib/run-terminal.js +437 -0
- package/lib/runner-request.js +33 -0
- package/lib/sandbox-app.js +120 -0
- package/lib/sandbox-claims.js +258 -0
- package/lib/sandbox-cli.js +188 -0
- package/lib/sandbox-hosts-cli.js +68 -0
- package/lib/sandbox-hosts.js +94 -0
- package/lib/sandbox-pr.js +102 -0
- package/lib/sandbox-proposal.js +367 -0
- package/lib/sandbox-tools.js +143 -0
- package/lib/sandbox.js +501 -0
- package/lib/schedule-session.js +68 -0
- package/lib/session-activity.js +67 -0
- package/lib/session-events.js +94 -0
- package/lib/sessions/control.js +244 -0
- package/lib/sessions/git-refs.js +265 -0
- package/lib/sessions/launch.js +359 -0
- package/lib/sessions/registry.js +450 -0
- package/lib/sessions/scope.js +111 -0
- package/lib/setup.js +377 -0
- package/lib/signed-approval.js +225 -0
- package/lib/slash.js +167 -0
- package/lib/spawn-cli.js +45 -0
- package/lib/spawn.js +107 -0
- package/lib/start-limit.js +58 -0
- package/lib/state.js +24 -0
- package/lib/stop.js +308 -0
- package/lib/store-read.js +62 -0
- package/lib/store.js +252 -0
- package/lib/subagent-guard.js +240 -0
- package/lib/surfaces/channel-post.js +43 -0
- package/lib/surfaces/instructions.js +15 -0
- package/lib/surfaces/mcp-reload.js +144 -0
- package/lib/surfaces/ops.js +629 -0
- package/lib/surfaces/render-mcp.js +33 -0
- package/lib/surfaces/run-terminal-ops.js +40 -0
- package/lib/surfaces/sandbox-ops.js +36 -0
- package/lib/surfaces/schema.js +7 -0
- package/lib/surfaces/task-view.js +90 -0
- package/lib/surfaces/types.js +4 -0
- package/lib/task-cli.js +274 -0
- package/lib/task-order.js +34 -0
- package/lib/task-order.mjs +2 -0
- package/lib/task-route.js +125 -0
- package/lib/tasks.js +631 -0
- package/lib/team-permission.js +34 -0
- package/lib/team-templates/blitz/team.dot +9 -0
- package/lib/team-templates/factory/team.dot +26 -0
- package/lib/team-templates/feature/team.dot +14 -0
- package/lib/team-templates/fix-and-review/team.dot +12 -0
- package/lib/team-templates/product/team.dot +16 -0
- package/lib/team-templates/release/team.dot +7 -0
- package/lib/team-templates/review/team.dot +6 -0
- package/lib/terminal-draft.js +42 -0
- package/lib/thread-branch.js +82 -0
- package/lib/thread-channel-store.js +181 -0
- package/lib/thread-channels.js +116 -0
- package/lib/thread-listening.js +20 -0
- package/lib/thread-routes.js +91 -0
- package/lib/threads.js +441 -0
- package/lib/tool-api.js +33 -0
- package/lib/transcript.js +98 -0
- package/lib/ui-build-output.js +19 -0
- package/lib/ui-capabilities.js +90 -0
- package/lib/usage.js +182 -0
- package/lib/vendor/mcp-sdk.d.mts +4 -0
- package/lib/vendor/mcp-sdk.mjs +17046 -0
- package/lib/waiter.js +127 -0
- package/lib/workflows.js +546 -0
- package/lib/worktree-setup.js +86 -0
- package/package.json +110 -4
- package/runner/adapters/claude.js +465 -0
- package/runner/adapters/cli-sandbox.js +277 -0
- package/runner/adapters/codex.js +675 -0
- package/runner/adapters/cursor.mjs +937 -0
- package/runner/adapters/fake.js +119 -0
- package/runner/adapters/opencode-sandbox.js +370 -0
- package/runner/adapters/opencode.js +486 -0
- package/runner/adapters/pi-sandbox.js +134 -0
- package/runner/adapters/pi.js +364 -0
- package/runner/client.js +40 -0
- package/runner/contract.js +129 -0
- package/runner/control.js +178 -0
- package/runner/delivery.js +184 -0
- package/runner/factory-tick.mjs +10 -0
- package/runner/lock.js +41 -0
- package/runner/main.mjs +118 -0
- package/runner/pattern-tick.mjs +16 -0
- package/runner/publish.js +113 -0
- package/runner/runner.js +2612 -0
- package/runner/sandbox-run.mjs +239 -0
- package/runner/schedules.js +294 -0
- package/runner/task-wake.js +59 -0
- package/scripts/ai-collab +3 -0
- package/scripts/ai-collab-bus.mjs +4 -0
- package/scripts/ai-collab-code-mcp.mjs +3 -0
- package/scripts/ai-collab-hook +3 -0
- package/scripts/ai-collab-hook.mjs +3 -0
- package/scripts/ai-collab-mcp-tools.mjs +2 -0
- package/scripts/ai-collab-mcp.mjs +3 -0
- package/scripts/ai-collab.mjs +3 -0
- package/scripts/install-cursor.mjs +11 -0
- package/scripts/install-opencode.mjs +10 -0
- package/scripts/temmo +3 -0
- package/scripts/temmo-bus.mjs +151 -0
- package/scripts/temmo-code-mcp.mjs +63 -0
- package/scripts/temmo-hook +3 -0
- package/scripts/temmo-hook.mjs +201 -0
- package/scripts/temmo-mcp-tools.mjs +22 -0
- package/scripts/temmo-mcp.mjs +27 -0
- package/scripts/temmo.mjs +4 -0
- package/skills/antislop/SKILL.md +701 -0
- package/skills/antislop/VERSION +1 -0
- package/skills/antislop-code/SKILL.md +128 -0
- package/skills/antislop-human/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-human/SKILL.md +204 -0
- package/skills/antislop-human/contrast-check.py +168 -0
- package/skills/antislop-human/contrast-mcp.py +125 -0
- package/skills/antislop-human/references/A11Y-PATTERNS.md +249 -0
- package/skills/antislop-human/references/WCAG.md +127 -0
- package/skills/antislop-layoutmobile/SKILL.md +170 -0
- package/skills/antislop-ui/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-ui/SKILL.md +351 -0
- package/skills/antislop-ui/references/CORE-WEB-VITALS.md +181 -0
- package/skills/antislop-ui/references/WEB-BASELINE.md +28 -0
- package/skills/harness-surface/SKILL.md +42 -0
- package/skills/land/SKILL.md +32 -0
- package/skills/memory-file/SKILL.md +39 -0
- package/skills/temmo/SKILL.md +101 -0
- package/skills/temmo/references/role-programs.md +47 -0
- package/skills/ui-sdk/SKILL.md +56 -0
- package/skills/ui-sdk/references/agent-ready.md +136 -0
- package/skills/ui-sdk/references/build-interface.md +187 -0
- package/skills/ui-sdk/references/create-component.md +88 -0
- package/skills/ui-sdk/references/patterns.md +246 -0
- package/skills/ui-sdk/references/styles.md +66 -0
- package/skills/ui-sdk/references/testing.md +172 -0
- package/skills/ui-sdk/references/web-components.md +78 -0
- package/tools/screen-state.mjs +119 -0
- package/tools/smoke-ui.mjs +540 -0
- package/web/app/activity.jsx +251 -0
- package/web/app/agent-mark.tsx +43 -0
- package/web/app/alert-level.jsx +16 -0
- package/web/app/api/[action]/route.js +8 -0
- package/web/app/api/auth/[step]/route.js +12 -0
- package/web/app/api/events/route.js +8 -0
- package/web/app/api/file/[name]/route.js +8 -0
- package/web/app/api/land/route.js +12 -0
- package/web/app/api/lessons/route.js +8 -0
- package/web/app/api/push/key/route.js +8 -0
- package/web/app/api/push/subscribe/route.js +12 -0
- package/web/app/api/push/test/route.js +8 -0
- package/web/app/api/refs/route.js +8 -0
- package/web/app/api/review-diff/route.js +8 -0
- package/web/app/api/schedules/route.js +8 -0
- package/web/app/api/thread-diff/route.js +8 -0
- package/web/app/api/version/route.js +6 -0
- package/web/app/cards.jsx +189 -0
- package/web/app/chat-api.js +82 -0
- package/web/app/chat-composer.jsx +313 -0
- package/web/app/chat-console.jsx +691 -0
- package/web/app/chat-image.tsx +61 -0
- package/web/app/chat-message.jsx +122 -0
- package/web/app/chat-shared.jsx +59 -0
- package/web/app/chat-sidebar.jsx +25 -0
- package/web/app/chat-stream.js +127 -0
- package/web/app/chat.jsx +31 -0
- package/web/app/compactions.jsx +57 -0
- package/web/app/composer-actions.tsx +87 -0
- package/web/app/decisions.jsx +53 -0
- package/web/app/fonts/OFL-hanken-grotesk.txt +93 -0
- package/web/app/fonts/OFL-ibm-plex-mono.txt +93 -0
- package/web/app/fonts/hanken-grotesk-latin-wght-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-500-normal.woff2 +0 -0
- package/web/app/globals.css +199 -0
- package/web/app/home.jsx +246 -0
- package/web/app/icon.svg +1 -0
- package/web/app/land-panel.jsx +63 -0
- package/web/app/land-reviews.jsx +20 -0
- package/web/app/layout.jsx +17 -0
- package/web/app/lessons.tsx +76 -0
- package/web/app/logo.tsx +13 -0
- package/web/app/logos.jsx +16 -0
- package/web/app/manifest.js +8 -0
- package/web/app/mode-menu.tsx +46 -0
- package/web/app/new-session.jsx +275 -0
- package/web/app/notify.jsx +180 -0
- package/web/app/outcomes.tsx +94 -0
- package/web/app/page.jsx +9 -0
- package/web/app/pattern-graph.jsx +75 -0
- package/web/app/patterns-page.jsx +293 -0
- package/web/app/phone-nav.tsx +36 -0
- package/web/app/progress-feed.tsx +33 -0
- package/web/app/providers.tsx +27 -0
- package/web/app/quote.jsx +15 -0
- package/web/app/run-card.tsx +200 -0
- package/web/app/run-requests.tsx +148 -0
- package/web/app/scheduled.jsx +105 -0
- package/web/app/session-panel.tsx +174 -0
- package/web/app/session-toolbar.tsx +180 -0
- package/web/app/shadcn.css +638 -0
- package/web/app/shipped.jsx +49 -0
- package/web/app/subagent-runs.jsx +31 -0
- package/web/app/task-graph.jsx +67 -0
- package/web/app/tasks-strip.tsx +36 -0
- package/web/app/tasks.jsx +375 -0
- package/web/app/team-author.jsx +145 -0
- package/web/app/team-editor.jsx +88 -0
- package/web/app/thread-agents.tsx +32 -0
- package/web/app/thread-place.tsx +9 -0
- package/web/app/thread-sessions.tsx +149 -0
- package/web/app/thread-sidebar.tsx +418 -0
- package/web/app/thread-switcher.tsx +27 -0
- package/web/app/tool-diff.jsx +94 -0
- package/web/components/a2ui/controls.jsx +36 -0
- package/web/components/a2ui/option-picker.jsx +23 -0
- package/web/components/a2ui/script.tsx +121 -0
- package/web/components/a2ui/surface.jsx +81 -0
- package/web/components/chat/thread.jsx +50 -0
- package/web/components/script-text.tsx +42 -0
- package/web/components/ui/avatar.jsx +115 -0
- package/web/components/ui/badge.jsx +47 -0
- package/web/components/ui/button.jsx +63 -0
- package/web/components/ui/chat-container.jsx +52 -0
- package/web/components/ui/choice-list.tsx +72 -0
- package/web/components/ui/code-block.jsx +60 -0
- package/web/components/ui/copy-button.tsx +41 -0
- package/web/components/ui/dropdown-menu.jsx +257 -0
- package/web/components/ui/markdown.jsx +84 -0
- package/web/components/ui/message.jsx +28 -0
- package/web/components/ui/popover.jsx +33 -0
- package/web/components/ui/scroll-button.jsx +34 -0
- package/web/components/ui/select.jsx +189 -0
- package/web/components/ui/sheet.jsx +152 -0
- package/web/components/ui/sonner.jsx +10 -0
- package/web/components/ui/tabs.jsx +88 -0
- package/web/components/ui/textarea.jsx +20 -0
- package/web/components/ui/tooltip.jsx +56 -0
- package/web/components.json +24 -0
- package/web/instrumentation.js +8 -0
- package/web/lib/a2ui-catalog.js +34 -0
- package/web/lib/a2ui-pr.js +76 -0
- package/web/lib/a2ui-run-catalog.js +18 -0
- package/web/lib/a2ui-run.js +93 -0
- package/web/lib/a2ui.js +262 -0
- package/web/lib/activity-rows.js +275 -0
- package/web/lib/agent-detail.js +5 -0
- package/web/lib/alert-level.js +44 -0
- package/web/lib/approval-mode.js +22 -0
- package/web/lib/chat-turns.js +174 -0
- package/web/lib/child-subagents.js +16 -0
- package/web/lib/compaction-view.js +48 -0
- package/web/lib/composer-actions.js +40 -0
- package/web/lib/context-view.js +57 -0
- package/web/lib/fuzzy.js +26 -0
- package/web/lib/highlight.js +44 -0
- package/web/lib/lessons-view.js +23 -0
- package/web/lib/mentions.js +16 -0
- package/web/lib/message-routing.js +105 -0
- package/web/lib/new-session.js +85 -0
- package/web/lib/operator-messages.js +28 -0
- package/web/lib/pattern-graph.js +165 -0
- package/web/lib/pattern-view.js +33 -0
- package/web/lib/pending-summary.js +18 -0
- package/web/lib/permission-modes.js +30 -0
- package/web/lib/project-feed.js +107 -0
- package/web/lib/quote.js +7 -0
- package/web/lib/reply-quote.js +31 -0
- package/web/lib/scheduled.js +79 -0
- package/web/lib/selection.js +110 -0
- package/web/lib/send-confirmation.js +22 -0
- package/web/lib/session-dead.js +10 -0
- package/web/lib/session-state.js +132 -0
- package/web/lib/sidebar.js +15 -0
- package/web/lib/slash-commands.js +164 -0
- package/web/lib/start-default.js +35 -0
- package/web/lib/start-mode.js +35 -0
- package/web/lib/stream-views.js +49 -0
- package/web/lib/subagent-state.js +20 -0
- package/web/lib/task-board.js +54 -0
- package/web/lib/task-graph.js +183 -0
- package/web/lib/task-tags.js +41 -0
- package/web/lib/team-editor.js +10 -0
- package/web/lib/thread-groups.js +86 -0
- package/web/lib/threads.js +28 -0
- package/web/lib/tool-diff.js +273 -0
- package/web/lib/ui-events.js +58 -0
- package/web/lib/utils.js +5 -0
- package/web/lib/view-memory.js +25 -0
- package/web/next.config.mjs +37 -0
- package/web/postcss.config.mjs +1 -0
- package/web/proxy.js +25 -0
- package/web/public/sw.js +39 -0
- package/web/server/auth.js +178 -0
- package/web/server/dispatch.js +293 -0
- package/web/server/history.js +56 -0
- package/web/server/hosted.js +58 -0
- package/web/server/hub.js +126 -0
- package/web/server/instance.js +5 -0
- package/web/server/land-reviews.js +64 -0
- package/web/server/push.js +148 -0
- package/web/server/run-terminal.js +79 -0
- package/web/server/schedules.js +38 -0
- package/web/server/shipped.js +51 -0
- package/web/server/task-board.js +71 -0
- package/web/server/threads.js +209 -0
- package/web/server/ui.js +2937 -0
- package/web/tsconfig.base.json +16 -0
- package/web/tsconfig.json +9 -0
package/lib/limits.js
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
// Usage and plan limits: detects a limit in a harness error or event, and owns the fallback chain a limit starts.
|
|
2
|
+
// Typed sources: sdk.d.ts (Claude SDK 0.3.330). Text patterns are UNVERIFIED: no type or source here names them.
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { autoDefaults, stateDir } from "./config.js";
|
|
6
|
+
import { FALLBACK_MODEL, HARNESSES, modelShape, parseHarnessModel } from "./harness.js";
|
|
7
|
+
import { readJson, withLock, writeJson } from "./store.js";
|
|
8
|
+
// oxlint-disable-next-line quality/no-known-value-widening -- open map keyed by server window names
|
|
9
|
+
export const LIMIT_WINDOW_NAMES = {
|
|
10
|
+
five_hour: "5-hour", seven_day: "weekly", seven_day_opus: "weekly Opus", seven_day_sonnet: "weekly Sonnet",
|
|
11
|
+
seven_day_overage_included: "weekly overage", overage: "overage",
|
|
12
|
+
};
|
|
13
|
+
// UNVERIFIED: limit wording in a harness's error text. A bare HTTP 429 matches none of these.
|
|
14
|
+
const LIMIT_TEXT = /usage limit|plan limit|rate limit|quota/i;
|
|
15
|
+
// Explicit subscription wording. "Rate limit" alone is not enough to call the card a limit.
|
|
16
|
+
const LIMIT_WORDING = /usage limit|plan limit|quota|5[- ]?hour|weekly|7[- ]?day/i;
|
|
17
|
+
const WINDOW_TEXT = [[/5[- ]?hour/i, "five_hour"], [/weekly|7[- ]?day/i, "seven_day"]];
|
|
18
|
+
// Codex error code for a plan limit. UNVERIFIED: the name is not in any type definition in this repo.
|
|
19
|
+
const CODEX_LIMIT_INFO = "usageLimitExceeded";
|
|
20
|
+
const CODEX_LIMIT_INFO_ROLLOUT = "usage_limit_exceeded";
|
|
21
|
+
// SDKRateLimitInfo.resetsAt is an epoch number. Its unit is UNVERIFIED: above 1e12 read as ms, else seconds.
|
|
22
|
+
// The window end is held to at least 5 minutes from now.
|
|
23
|
+
const MIN_WINDOW_MS = 5 * 60_000;
|
|
24
|
+
const MS_THRESHOLD = 1e12;
|
|
25
|
+
// The replacement a limit starts when nobody has named one: Cursor DeepSeek, then the free OpenCode model.
|
|
26
|
+
export const CURSOR_FALLBACK = { harness: "cursor", model: FALLBACK_MODEL };
|
|
27
|
+
export const OPENCODE_FALLBACK = { harness: "opencode", model: "opencode/deepseek-v4.1-flash-free" };
|
|
28
|
+
export const REPLACEMENT_MAX = 4;
|
|
29
|
+
/** "harness:model" when the model is known, else the harness. */
|
|
30
|
+
export const who = (harness, model) => (model ? `${harness}:${model}` : harness);
|
|
31
|
+
function limit(harness, { window = null, resetsAt = null, wording = false, verified, source }) {
|
|
32
|
+
return { harness, window, windowName: window ? LIMIT_WINDOW_NAMES[window] ?? window : null, resetsAt, wording, verified, source };
|
|
33
|
+
}
|
|
34
|
+
// Window named in free text, e.g. "5-hour limit reached"; null when the text names none.
|
|
35
|
+
function windowFromText(text) {
|
|
36
|
+
return WINDOW_TEXT.find(([pattern]) => pattern.test(String(text ?? "")))?.[1] ?? null;
|
|
37
|
+
}
|
|
38
|
+
function resetMs(value, now = Date.now()) {
|
|
39
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
|
|
40
|
+
return null;
|
|
41
|
+
const ms = value > MS_THRESHOLD ? value : value * 1000;
|
|
42
|
+
return Math.max(ms, now + MIN_WINDOW_MS);
|
|
43
|
+
}
|
|
44
|
+
// Overage that is allowed or in use: the request runs on overage credit, so the plan window did not block it (sdk.d.ts:6243-6246).
|
|
45
|
+
// A rejected overage is not on overage, whatever the other flags say: overageEnabled only means the account may buy overage.
|
|
46
|
+
function onOverage(info) {
|
|
47
|
+
if (info.overageStatus === "rejected")
|
|
48
|
+
return false;
|
|
49
|
+
return info.isUsingOverage === true || info.overageInUse === true || info.overageEnabled === true
|
|
50
|
+
|| info.overageStatus === "allowed" || info.overageStatus === "allowed_warning";
|
|
51
|
+
}
|
|
52
|
+
function classifyClaude(event) {
|
|
53
|
+
switch (event?.kind) {
|
|
54
|
+
// sdk.d.ts:6224 SDKRateLimitEvent; status 'rejected' means the limit blocked the request (sdk.d.ts:6238).
|
|
55
|
+
case "rate_limit_event": {
|
|
56
|
+
const info = event.rate_limit_info;
|
|
57
|
+
if (info?.status !== "rejected" || onOverage(info))
|
|
58
|
+
return null;
|
|
59
|
+
return limit("claude", {
|
|
60
|
+
window: LIMIT_WINDOW_NAMES[info.rateLimitType] ? info.rateLimitType : null,
|
|
61
|
+
resetsAt: resetMs(info.resetsAt), wording: true, verified: true, source: "sdk.d.ts:6224 rate_limit_event",
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
// sdk.d.ts:10502 StopFailureHookInput; error 'rate_limit' is in the enum at sdk.d.ts:3995. Also returns for API 429s, not only plan limits.
|
|
65
|
+
case "stop_failure": {
|
|
66
|
+
if (event.error !== "rate_limit")
|
|
67
|
+
return null;
|
|
68
|
+
const details = String(event.error_details ?? "");
|
|
69
|
+
return limit("claude", {
|
|
70
|
+
window: windowFromText(details), wording: LIMIT_WORDING.test(details), verified: true, source: "sdk.d.ts:10502 StopFailure error=rate_limit",
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
// sdk.d.ts:6268 SDKResultError with is_error; the text match is UNVERIFIED.
|
|
74
|
+
case "result_error":
|
|
75
|
+
return LIMIT_TEXT.test(event.text ?? "")
|
|
76
|
+
? limit("claude", { window: windowFromText(event.text), wording: LIMIT_WORDING.test(event.text), verified: false, source: "UNVERIFIED result error text" })
|
|
77
|
+
: null;
|
|
78
|
+
default: return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
|
|
82
|
+
// Codex words the reset as "try again at 1:14 PM" or "try again at Nov 29th, 2026 1:14 PM"; a local time (the CLI prints the user's clock).
|
|
83
|
+
const CODEX_RESET = /try again at (?:([A-Za-z]{3,9})\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(\d{4})\s+)?(\d{1,2}):(\d{2})\s*([AP]M)/i;
|
|
84
|
+
/** The reset time (ms) a Codex limit message names, or null. A bare clock time is the next such time, not a past one. */
|
|
85
|
+
export function codexResetFrom(message, now = Date.now()) {
|
|
86
|
+
const found = CODEX_RESET.exec(String(message ?? ""));
|
|
87
|
+
if (!found)
|
|
88
|
+
return null;
|
|
89
|
+
const [, month, day, year, hourText, minute, meridiem] = found;
|
|
90
|
+
const hour = (Number(hourText) % 12) + (/^p/i.test(meridiem) ? 12 : 0);
|
|
91
|
+
if (Number(hourText) < 1 || Number(hourText) > 12 || Number(minute) > 59)
|
|
92
|
+
return null;
|
|
93
|
+
let at;
|
|
94
|
+
if (year) {
|
|
95
|
+
const index = MONTHS.indexOf(month.slice(0, 3).toLowerCase());
|
|
96
|
+
if (index < 0)
|
|
97
|
+
return null;
|
|
98
|
+
at = new Date(Number(year), index, Number(day), hour, Number(minute));
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
const today = new Date(now);
|
|
102
|
+
at = new Date(today.getFullYear(), today.getMonth(), today.getDate(), hour, Number(minute));
|
|
103
|
+
if (at.getTime() <= now)
|
|
104
|
+
at.setDate(at.getDate() + 1);
|
|
105
|
+
}
|
|
106
|
+
return Number.isFinite(at.getTime()) ? resetMs(at.getTime(), now) : null;
|
|
107
|
+
}
|
|
108
|
+
function classifyCodex(event) {
|
|
109
|
+
if (event?.kind !== "turn_error")
|
|
110
|
+
return null;
|
|
111
|
+
const message = event.message ?? "";
|
|
112
|
+
// UNVERIFIED: the codexErrorInfo code, from Codex's app-server protocol (not in node_modules or docs/).
|
|
113
|
+
// The rollout file records the same code in snake_case (codex_error_info: "usage_limit_exceeded"), measured 2026-11-24.
|
|
114
|
+
if (event.codexErrorInfo === CODEX_LIMIT_INFO || event.codexErrorInfo === CODEX_LIMIT_INFO_ROLLOUT) {
|
|
115
|
+
return limit("codex", { window: windowFromText(message), resetsAt: codexResetFrom(message), wording: true, verified: false, source: "UNVERIFIED codexErrorInfo usageLimitExceeded" });
|
|
116
|
+
}
|
|
117
|
+
return LIMIT_TEXT.test(message)
|
|
118
|
+
? limit("codex", { window: windowFromText(message), resetsAt: codexResetFrom(message), wording: LIMIT_WORDING.test(message), verified: false, source: "UNVERIFIED turn error text" })
|
|
119
|
+
: null;
|
|
120
|
+
}
|
|
121
|
+
function classifyOpenCode(event) {
|
|
122
|
+
if (event?.kind !== "run_error")
|
|
123
|
+
return null;
|
|
124
|
+
// UNVERIFIED: OpenCode's provider error carries an HTTP status; runner/adapters/opencode.ts forwards it in RUN_ERROR metadata.
|
|
125
|
+
if (event.status === 429)
|
|
126
|
+
return limit("opencode", { verified: false, source: "UNVERIFIED HTTP 429 from provider" });
|
|
127
|
+
return LIMIT_TEXT.test(event.message ?? "")
|
|
128
|
+
? limit("opencode", { window: windowFromText(event.message), wording: LIMIT_WORDING.test(event.message), verified: false, source: "UNVERIFIED provider error text" })
|
|
129
|
+
: null;
|
|
130
|
+
}
|
|
131
|
+
// Explicit limit wording a Cursor error may use about the plan's own window (not a bare "rate limited").
|
|
132
|
+
const CURSOR_LIMIT_TEXT = /usage limit|plan limit|monthly quota|quota exhausted|reached your (usage|limit|quota)/i;
|
|
133
|
+
// Structured ACP/error codes that name a usage limit. UNVERIFIED: no local schema names them.
|
|
134
|
+
const CURSOR_LIMIT_CODES = /usage_?limit|rate_?limit|limit_?exceeded|quota|insufficient_quota|429/i;
|
|
135
|
+
// A bare HTTP 429 counts only with limit wording beside it, so an ordinary throttled request does not open a card.
|
|
136
|
+
const HAS_429 = /(^|\D)429(\D|$)/;
|
|
137
|
+
function classifyCursor(event) {
|
|
138
|
+
if (event?.kind !== "run_error")
|
|
139
|
+
return null;
|
|
140
|
+
const message = String(event.message ?? "");
|
|
141
|
+
// The adapter joins the ACP error code, its data and the child's stderr tail into the message, so one text covers them all.
|
|
142
|
+
const structured = [event.code, event.data].filter((value) => value !== undefined)
|
|
143
|
+
.map((value) => (typeof value === "string" ? value : JSON.stringify(value))).join("\n");
|
|
144
|
+
if (structured && CURSOR_LIMIT_CODES.test(structured) && !/^(0|1|2)$/.test(structured.trim())) {
|
|
145
|
+
// A structured code is a limit on its own: the code says the plan blocked the request, not that a request was throttled.
|
|
146
|
+
return limit("cursor", { window: windowFromText(`${message}\n${structured}`), wording: true, verified: false, source: "UNVERIFIED ACP error code" });
|
|
147
|
+
}
|
|
148
|
+
if (CURSOR_LIMIT_TEXT.test(message)) {
|
|
149
|
+
return limit("cursor", { window: windowFromText(message), wording: LIMIT_WORDING.test(message), verified: false, source: "UNVERIFIED ACP error text" });
|
|
150
|
+
}
|
|
151
|
+
// "You've reached your usage limit" and "429" combined with limit wording: LIMIT_TEXT already covers the first; a 429 with
|
|
152
|
+
// explicit limit wording is a limit even when neither of the patterns above matched only because of formatting.
|
|
153
|
+
if (HAS_429.test(message) && LIMIT_TEXT.test(message)) {
|
|
154
|
+
return limit("cursor", { window: windowFromText(message), wording: LIMIT_WORDING.test(message), verified: false, source: "UNVERIFIED ACP error text with HTTP 429" });
|
|
155
|
+
}
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
/** The limit an event reports, {harness, window, windowName, resetsAt (ms|null), wording, verified, source}, or null. */
|
|
159
|
+
export function classifyLimit(harness, event) {
|
|
160
|
+
switch (harness) {
|
|
161
|
+
case "claude": return classifyClaude(event);
|
|
162
|
+
case "codex": return classifyCodex(event);
|
|
163
|
+
case "opencode": return classifyOpenCode(event);
|
|
164
|
+
case "cursor": return classifyCursor(event);
|
|
165
|
+
default: return null;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/** The limit a runner RUN_ERROR reports: its message, and for Codex its metadata codexErrorInfo; the kind follows the adapter's error source. */
|
|
169
|
+
export function limitFromRunError(harness, message, metadata = {}) {
|
|
170
|
+
const kind = harness === "claude" ? "result_error" : harness === "codex" ? "turn_error" : "run_error";
|
|
171
|
+
// An adapter that saw an HTTP status (OpenCode's provider error) or an ACP error code (Cursor) forwards it here.
|
|
172
|
+
const status = Number.isInteger(metadata.status) && metadata.status > 0 ? metadata.status : undefined;
|
|
173
|
+
return classifyLimit(harness, {
|
|
174
|
+
kind, text: message, message, codexErrorInfo: metadata.codexErrorInfo,
|
|
175
|
+
...(status ? { status } : {}), ...(metadata.code !== undefined ? { code: metadata.code } : {}),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The one detector for an error: a text (classified as the harness's run error) or a structured event.
|
|
180
|
+
* Returns the limit with kind, or null when the text or event is not a limit.
|
|
181
|
+
*/
|
|
182
|
+
export function detectLimit(harness, errorOrText) {
|
|
183
|
+
const found = typeof errorOrText === "string" ? limitFromRunError(harness, errorOrText) : classifyLimit(harness, errorOrText);
|
|
184
|
+
if (!found)
|
|
185
|
+
return null;
|
|
186
|
+
return { ...found, kind: isBlockingLimit(found) ? "limit" : "rate" };
|
|
187
|
+
}
|
|
188
|
+
/** Whether a limit stops the work and starts the fallback: wording, a window or a reset. A bare rate limit does not. Every path uses this. */
|
|
189
|
+
export function isBlockingLimit(limit) {
|
|
190
|
+
return Boolean(limit && (limit.wording || limit.window || limit.resetsAt));
|
|
191
|
+
}
|
|
192
|
+
// Cursor names the end of its monthly cycle in a limit line; the limit lasts through the day after it.
|
|
193
|
+
const CURSOR_MONTHLY = /monthly cycle ends on (\d{1,2})\/(\d{1,2})\/(\d{4})/i;
|
|
194
|
+
// A Cursor limit with no usable cycle date lasts this long.
|
|
195
|
+
const CURSOR_UNKNOWN_LIMIT_MS = 5 * 3600_000;
|
|
196
|
+
/** The reset (ms) a Cursor limit line names, or null when it names none or the date has passed. */
|
|
197
|
+
export function cursorResetFrom(line, now = Date.now()) {
|
|
198
|
+
const found = CURSOR_MONTHLY.exec(line);
|
|
199
|
+
if (!found)
|
|
200
|
+
return null;
|
|
201
|
+
const at = Date.UTC(Number(found[3]), Number(found[1]) - 1, Number(found[2]) + 1);
|
|
202
|
+
return at > now ? at : null;
|
|
203
|
+
}
|
|
204
|
+
// Cursor's limit record per model: builder-limits/cursor-<sha256 of the lower-case model>.json, holding {until} in ms.
|
|
205
|
+
export function cursorLimitFile(model, env = process.env) {
|
|
206
|
+
const key = createHash("sha256").update(model.toLowerCase()).digest("hex");
|
|
207
|
+
return join(stateDir(env), "builder-limits", `cursor-${key}.json`);
|
|
208
|
+
}
|
|
209
|
+
/** The time (ms) a Cursor model is limited until, or 0. A missing or unreadable record is no limit. */
|
|
210
|
+
export function cursorLimitUntil(model, env = process.env) {
|
|
211
|
+
const record = readJson(cursorLimitFile(model, env));
|
|
212
|
+
return typeof record?.until === "number" && Number.isFinite(record.until) ? record.until : 0;
|
|
213
|
+
}
|
|
214
|
+
/** Records a Cursor model's limit from its limit line, lasting to the cycle end or 5 hours; keeps the later of old and new. */
|
|
215
|
+
export async function recordCursorLimit(model, line, { env = process.env, now = Date.now() } = {}) {
|
|
216
|
+
const file = cursorLimitFile(model, env);
|
|
217
|
+
await withLock(file, async () => {
|
|
218
|
+
const until = cursorResetFrom(line, now) ?? now + CURSOR_UNKNOWN_LIMIT_MS;
|
|
219
|
+
writeJson(file, { until: Math.max(until, cursorLimitUntil(model, env)) });
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
// A role's fallback as {harness, model}, or null; read defensively, since the attribute is optional.
|
|
223
|
+
function fallbackOf(fallback) {
|
|
224
|
+
const parsed = parseHarnessModel(fallback);
|
|
225
|
+
return parsed?.model ? parsed : null;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Models to try after a limit, in order: the configured fallback first (a different model on the same harness is allowed),
|
|
229
|
+
* then Cursor DeepSeek, then the free OpenCode model, then the first listed model of each other available harness.
|
|
230
|
+
* Harness `harness` is the one that stopped; `fallback` defaults to defaults.json limitFallback.
|
|
231
|
+
*/
|
|
232
|
+
export function fallbackChain({ harness, model = "", fallback, models = {}, available = [], env }) {
|
|
233
|
+
const picks = [];
|
|
234
|
+
const add = (item, description, { sameHarness = false } = {}) => {
|
|
235
|
+
if (!item || !HARNESSES.includes(item.harness) || !modelShape(item.harness, item.model))
|
|
236
|
+
return;
|
|
237
|
+
if (item.harness === harness && !(sameHarness && model && item.model !== model))
|
|
238
|
+
return;
|
|
239
|
+
const label = who(item.harness, item.model);
|
|
240
|
+
if (picks.some((pick) => pick.label === label) || picks.length >= REPLACEMENT_MAX)
|
|
241
|
+
return;
|
|
242
|
+
picks.push({ label, harness: item.harness, model: item.model, ...(description ? { description } : {}) });
|
|
243
|
+
};
|
|
244
|
+
const defaults = env ? autoDefaults(env) : null;
|
|
245
|
+
const configured = fallback ?? defaults?.limitFallback;
|
|
246
|
+
add(fallbackOf(configured), "Configured fallback", { sameHarness: true });
|
|
247
|
+
add(CURSOR_FALLBACK, "Cursor fallback");
|
|
248
|
+
add(OPENCODE_FALLBACK, "Free fallback");
|
|
249
|
+
for (const other of available) {
|
|
250
|
+
if (other === harness || !HARNESSES.includes(other))
|
|
251
|
+
continue;
|
|
252
|
+
const first = (models[other] ?? []).find((name) => modelShape(other, name));
|
|
253
|
+
if (first)
|
|
254
|
+
add({ harness: other, model: first });
|
|
255
|
+
}
|
|
256
|
+
return picks;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Manual limit card options: the role's fallback first, then the first listed model of each other available harness, at most REPLACEMENT_MAX.
|
|
260
|
+
* Returns [{label, harness, model, description?}]; the caller appends its wait option.
|
|
261
|
+
*/
|
|
262
|
+
export function replacementOptions({ harness, model = "", fallback, models = {}, available = [] }) {
|
|
263
|
+
const picks = [];
|
|
264
|
+
const fb = fallbackOf(fallback);
|
|
265
|
+
if (fb)
|
|
266
|
+
picks.push({ ...fb, description: "Role fallback" });
|
|
267
|
+
for (const other of available) {
|
|
268
|
+
if (other === harness || !HARNESSES.includes(other))
|
|
269
|
+
continue;
|
|
270
|
+
const first = (models[other] ?? []).find((name) => modelShape(other, name));
|
|
271
|
+
if (first)
|
|
272
|
+
picks.push({ harness: other, model: first });
|
|
273
|
+
}
|
|
274
|
+
const seen = new Set([who(harness, model)]);
|
|
275
|
+
const out = [];
|
|
276
|
+
for (const pick of picks) {
|
|
277
|
+
const label = who(pick.harness, pick.model);
|
|
278
|
+
if (seen.has(label) || out.length >= REPLACEMENT_MAX)
|
|
279
|
+
continue;
|
|
280
|
+
seen.add(label);
|
|
281
|
+
out.push({ label, harness: pick.harness, model: pick.model, ...(pick.description ? { description: pick.description } : {}) });
|
|
282
|
+
}
|
|
283
|
+
return out;
|
|
284
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Prompt text that did not come from the operator typing: wake runs, harness machinery, other agents, temmo.
|
|
2
|
+
// Pure, so the browser UI and the server share one definition.
|
|
3
|
+
// Prompt a wake run sends to a resumed session (lib/sessions/control.ts); it is not the operator typing.
|
|
4
|
+
export const WAKE_PROMPT = "Read the pending Temmo operator messages for this exact session and reply to the operator in the same Temmo conversation.";
|
|
5
|
+
// Set in the environment of harness runs started by wake, so their hooks never count as the operator.
|
|
6
|
+
export const WAKE_ENV = "TEMMO_WAKE";
|
|
7
|
+
export const SYSTEM_PROMPT_ENV = "TEMMO_SYSTEM_PROMPT";
|
|
8
|
+
// Prompt text that harness machinery (task notifications, subagent hand-backs), other agents, or temmo produced.
|
|
9
|
+
export const MACHINE_PREFIXES = ["<task-notification>", "[SYSTEM NOTIFICATION", "<agent-message", "<cross-session-message", "[temmo]", "Another Claude session sent a message"];
|
|
10
|
+
/** True when prompt text came from harness machinery, another agent, or temmo itself. */
|
|
11
|
+
export function machinePrompt(prompt) {
|
|
12
|
+
const text = typeof prompt === "string" ? prompt.trimStart() : "";
|
|
13
|
+
return MACHINE_PREFIXES.some((prefix) => text.startsWith(prefix));
|
|
14
|
+
}
|
|
15
|
+
/** True when a submitted prompt came from the operator: not a wake run, the wake prompt, or machine text. */
|
|
16
|
+
export function operatorPrompt(prompt, env = process.env) {
|
|
17
|
+
const text = typeof prompt === "string" ? prompt.trim() : "";
|
|
18
|
+
return env[WAKE_ENV] !== "1" && text !== "" && !machinePrompt(text) && text !== WAKE_PROMPT;
|
|
19
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// The factory's merge sweep, run on the host with gh. Agents never merge. The policy file comes from the base branch, so
|
|
2
|
+
// a PR cannot loosen its own gate; shadow mode writes nothing and logs what it would do. docs/teams.md#merge-policy
|
|
3
|
+
import { posix } from "node:path";
|
|
4
|
+
import { checkState, execRun } from "./land.js";
|
|
5
|
+
const SHA = /^[0-9a-f]{40}$/;
|
|
6
|
+
export const POLICY_PATH = ".ai-collab/factory/merge-policy.json";
|
|
7
|
+
export const MODES = ["disabled", "shadow", "live"];
|
|
8
|
+
export const SEVERITIES = ["low", "medium", "high", "critical"];
|
|
9
|
+
export const MERGE_OPTION = "Merge";
|
|
10
|
+
export const HOLD_OPTION = "Hold";
|
|
11
|
+
const FINDING = /^finding (low|medium|high|critical) ([\w.-]+):/;
|
|
12
|
+
const RESOLVED = /^resolved ([\w.-]+)\b/;
|
|
13
|
+
/** Parses the policy text; throws on anything malformed, so a bad policy merges nothing. */
|
|
14
|
+
export function parsePolicy(text) {
|
|
15
|
+
const raw = JSON.parse(text);
|
|
16
|
+
if (!MODES.includes(raw?.mode))
|
|
17
|
+
throw new Error(`merge policy mode must be one of ${MODES.join(", ")}`);
|
|
18
|
+
if (!SEVERITIES.includes(raw.blockSeverity))
|
|
19
|
+
throw new Error(`merge policy blockSeverity must be one of ${SEVERITIES.join(", ")}`);
|
|
20
|
+
for (const key of ["maxFiles", "maxLines"])
|
|
21
|
+
if (!Number.isInteger(raw[key]) || raw[key] < 1)
|
|
22
|
+
throw new Error(`merge policy ${key} must be a positive integer`);
|
|
23
|
+
if (!Array.isArray(raw.only) || !Array.isArray(raw.never) || !raw.never.length)
|
|
24
|
+
throw new Error("merge policy needs an only list and a non-empty never list");
|
|
25
|
+
return { mode: raw.mode, blockSeverity: raw.blockSeverity, maxFiles: raw.maxFiles, maxLines: raw.maxLines, only: raw.only.map(String), never: raw.never.map((rule) => ({ glob: String(rule.glob), reason: String(rule.reason) })) };
|
|
26
|
+
}
|
|
27
|
+
/** Why the operator must tap before a merge: never paths, existing tests, paths off the only list, the blast radius. Renames count both paths. */
|
|
28
|
+
export function needsOperator(policy, changes) {
|
|
29
|
+
const reasons = new Set();
|
|
30
|
+
for (const change of changes) {
|
|
31
|
+
const paths = [change.filename, ...(change.previous_filename ? [change.previous_filename] : [])];
|
|
32
|
+
for (const path of paths) {
|
|
33
|
+
for (const rule of policy.never)
|
|
34
|
+
if (posix.matchesGlob(path, rule.glob))
|
|
35
|
+
reasons.add(rule.reason);
|
|
36
|
+
if (policy.only.length && !policy.only.some((glob) => posix.matchesGlob(path, glob)))
|
|
37
|
+
reasons.add("paths outside the only list");
|
|
38
|
+
// The old path of a rename existed on main; a new path exists there only when modified or removed.
|
|
39
|
+
const existed = path === change.previous_filename || ["modified", "removed", "changed"].includes(change.status);
|
|
40
|
+
if (path.startsWith("test/") && existed)
|
|
41
|
+
reasons.add("existing tests");
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (changes.length > policy.maxFiles)
|
|
45
|
+
reasons.add(`${changes.length} files (cap ${policy.maxFiles})`);
|
|
46
|
+
const lines = changes.reduce((sum, change) => sum + (change.additions ?? 0) + (change.deletions ?? 0), 0);
|
|
47
|
+
if (lines > policy.maxLines)
|
|
48
|
+
reasons.add(`${lines} lines (cap ${policy.maxLines})`);
|
|
49
|
+
return [...reasons];
|
|
50
|
+
}
|
|
51
|
+
/** Open review findings at or above the policy's severity. Only the finding's author clears it with "resolved <id>". */
|
|
52
|
+
export function openFindings(task, blockSeverity) {
|
|
53
|
+
const open = new Map();
|
|
54
|
+
for (const entry of task?.progress ?? []) {
|
|
55
|
+
const text = String(entry.text ?? "");
|
|
56
|
+
const found = FINDING.exec(text);
|
|
57
|
+
if (found) {
|
|
58
|
+
open.set(found[2], { severity: found[1], by: String(entry.by ?? "") });
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const resolved = RESOLVED.exec(text);
|
|
62
|
+
if (resolved && open.get(resolved[1])?.by === String(entry.by ?? ""))
|
|
63
|
+
open.delete(resolved[1]);
|
|
64
|
+
}
|
|
65
|
+
const floor = SEVERITIES.indexOf(blockSeverity);
|
|
66
|
+
return [...open].filter(([, item]) => SEVERITIES.indexOf(item.severity) >= floor).map(([id, item]) => `${item.severity} ${id}`);
|
|
67
|
+
}
|
|
68
|
+
/** The task whose progress approves this head: "approved <sha>" from the feature run's reviewer. */
|
|
69
|
+
export function approvedTask(tasks, headSha) {
|
|
70
|
+
return tasks.find((task) => (task.progress ?? []).some((entry) => String(entry.text ?? "").split(/\s+/).join(" ").includes(`approved ${headSha}`)));
|
|
71
|
+
}
|
|
72
|
+
async function gh(run, cwd, argv) {
|
|
73
|
+
const result = await run("gh", argv, { cwd, encoding: "utf8" });
|
|
74
|
+
if (result.status !== 0)
|
|
75
|
+
throw new Error(`gh ${argv.slice(0, 2).join(" ")} failed: ${String(result.stderr ?? "").trim().split("\n").at(-1) || `exit ${result.status}`}`);
|
|
76
|
+
return String(result.stdout).trim();
|
|
77
|
+
}
|
|
78
|
+
/** The base branch's policy. Throws when it is missing or malformed. */
|
|
79
|
+
export async function basePolicy(run, cwd) {
|
|
80
|
+
await run("git", ["fetch", "--quiet", "origin", "main"], { cwd, encoding: "utf8" });
|
|
81
|
+
const shown = await run("git", ["show", `origin/main:${POLICY_PATH}`], { cwd, encoding: "utf8" });
|
|
82
|
+
if (shown.status !== 0)
|
|
83
|
+
throw new Error(`no merge policy at origin/main:${POLICY_PATH}`);
|
|
84
|
+
return parsePolicy(String(shown.stdout));
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* One pass over open team/* PRs into main, re-evaluated from scratch each tick, so a push is re-checked. A PR merges when
|
|
88
|
+
* a task records "approved <its head sha>", every check on that head passed, no finding at or above blockSeverity is open,
|
|
89
|
+
* and nothing needs the operator, or the operator answered Merge to the question naming that head. A ready PR whose head
|
|
90
|
+
* lost its approval goes back to draft. `gh pr merge --rebase --match-head-commit` refuses a head that moved.
|
|
91
|
+
*/
|
|
92
|
+
export async function mergeSweep({ cwd, tasks, run = execRun, by = "merge-sweep" }) {
|
|
93
|
+
const policy = await basePolicy(run, cwd);
|
|
94
|
+
if (policy.mode === "disabled")
|
|
95
|
+
return [];
|
|
96
|
+
const live = policy.mode === "live";
|
|
97
|
+
const prs = JSON.parse(await gh(run, cwd, ["pr", "list", "--state", "open", "--base", "main", "--limit", "50", "--json", "number,headRefName,headRefOid,isDraft,statusCheckRollup"]));
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const pr of prs) {
|
|
100
|
+
if (!String(pr.headRefName).startsWith("team/") || !SHA.test(pr.headRefOid))
|
|
101
|
+
continue;
|
|
102
|
+
const task = approvedTask(tasks.list(), pr.headRefOid);
|
|
103
|
+
if (!task) {
|
|
104
|
+
if (!pr.isDraft && live)
|
|
105
|
+
await gh(run, cwd, ["pr", "ready", String(pr.number), "--undo"]);
|
|
106
|
+
out.push({ pr: pr.number, action: pr.isDraft ? "skipped" : live ? "withdrawn" : "would withdraw", detail: "no approval for this head" });
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
const findings = openFindings(task, policy.blockSeverity);
|
|
110
|
+
if (findings.length) {
|
|
111
|
+
out.push({ pr: pr.number, task: task.id, action: "blocked", detail: `open findings: ${findings.join(", ")}` });
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const checks = checkState(pr.statusCheckRollup);
|
|
115
|
+
if (checks !== "success") {
|
|
116
|
+
out.push({ pr: pr.number, task: task.id, action: "waiting", detail: `checks ${checks}` });
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const listed = await gh(run, cwd, ["api", "--paginate", `repos/{owner}/{repo}/pulls/${pr.number}/files`, "--jq", ".[] | {filename, previous_filename, status, additions, deletions}"]);
|
|
120
|
+
const changes = listed.split("\n").filter(Boolean).map((line) => JSON.parse(line));
|
|
121
|
+
const reasons = needsOperator(policy, changes);
|
|
122
|
+
if (reasons.length) {
|
|
123
|
+
const short = pr.headRefOid.slice(0, 12);
|
|
124
|
+
const asked = String(task.question?.text ?? "").includes(short);
|
|
125
|
+
const answer = asked ? task.question?.answer?.text : undefined;
|
|
126
|
+
if (!asked) {
|
|
127
|
+
if (live)
|
|
128
|
+
await tasks.update(task.id, { ask: { text: `Merge #${pr.number} (${short})? It touches ${reasons.join(", ")}.`, by, options: [MERGE_OPTION, HOLD_OPTION] } });
|
|
129
|
+
out.push({ pr: pr.number, task: task.id, action: live ? "asked" : "would ask", detail: reasons.join(", ") });
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (answer !== MERGE_OPTION) {
|
|
133
|
+
out.push({ pr: pr.number, task: task.id, action: "held", detail: answer ? `operator answered ${answer}` : "waiting for the operator" });
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const detail = reasons.length ? "operator approved" : "low risk";
|
|
138
|
+
if (!live) {
|
|
139
|
+
out.push({ pr: pr.number, task: task.id, action: "would merge", detail });
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (pr.isDraft)
|
|
143
|
+
await gh(run, cwd, ["pr", "ready", String(pr.number)]);
|
|
144
|
+
await gh(run, cwd, ["pr", "merge", String(pr.number), "--rebase", "--match-head-commit", pr.headRefOid]);
|
|
145
|
+
await tasks.update(task.id, { status: "done", progress: { by, text: `merged #${pr.number} at ${pr.headRefOid}` } });
|
|
146
|
+
out.push({ pr: pr.number, task: task.id, action: "merged", detail });
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|