@uniqbit/mate-core 0.18.5 → 0.21.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-capability-plugins/companion-mentions/.claude-plugin/marketplace.json +14 -0
- package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +8 -0
- package/claude-capability-plugins/companion-mentions/hooks/companion.ts +457 -0
- package/claude-capability-plugins/companion-mentions/hooks/hooks.json +1 -0
- package/claude-capability-plugins/companion-mentions/hooks/register.ts +403 -0
- package/claude-plugin/hooks/companion-instructions.mjs +9 -0
- package/claude-plugin/hooks/hooks.json +50 -2
- package/claude-plugin/hooks/rtk-worktree-git.mjs +58 -0
- package/claude-plugin/hooks/session-attention.mjs +10 -0
- package/claude-plugin/hooks/session-end.mjs +9 -0
- package/claude-plugin/hooks/session-guidance.mjs +1 -1
- package/claude-plugin/hooks/tokensave-route.mjs +52 -0
- package/opencode-plugin/src/server.ts +25 -3
- package/opencode-plugin/src/tui.tsx +3 -1
- package/opencode-plugin/tui.tsx +4 -1
- package/package.json +53 -15
- package/src/brand/art.generated.ts +69 -0
- package/src/brand/index.ts +12 -0
- package/src/brand/palette.ts +19 -0
- package/src/brand/svg.generated.ts +8 -0
- package/src/brand/terminal.ts +88 -0
- package/src/brand/types.ts +33 -0
- package/src/cli/commands/artifact/apply-context.ts +275 -0
- package/src/cli/commands/artifact/artifact.ts +12 -0
- package/src/cli/commands/artifact/delivery/archive.ts +125 -0
- package/src/cli/commands/artifact/delivery/branch-flags.ts +55 -0
- package/src/cli/commands/artifact/delivery/environment.ts +147 -0
- package/src/cli/commands/artifact/delivery/link.ts +210 -0
- package/src/cli/commands/artifact/delivery/output.ts +104 -0
- package/src/cli/commands/artifact/finish/command.ts +83 -8
- package/src/cli/commands/artifact/finish/engine.ts +91 -14
- package/src/cli/commands/artifact/finish/finisher.ts +10 -0
- package/src/cli/commands/artifact/finish/git.ts +132 -19
- package/src/cli/commands/artifact/finish/openspec.ts +180 -138
- package/src/cli/commands/artifact/finish/secret-scan.ts +43 -0
- package/src/cli/commands/artifact/finish/worktree-cleanup.ts +92 -0
- package/src/cli/commands/artifact/pending/command.ts +31 -3
- package/src/cli/commands/artifact/pending/discovery.ts +21 -57
- package/src/cli/commands/cap/graphify.ts +52 -3
- package/src/cli/commands/cap/index-cmd.ts +71 -15
- package/src/cli/commands/cap/openspec.ts +13 -25
- package/src/cli/commands/cap/tokensave.ts +7 -5
- package/src/cli/commands/companion/companion.ts +1 -1
- package/src/cli/commands/companion/link.ts +50 -5
- package/src/cli/commands/companion/open.ts +101 -51
- package/src/cli/commands/companion/sync.ts +10 -0
- package/src/cli/commands/companion/tui.ts +17 -7
- package/src/cli/commands/companion/update.ts +144 -66
- package/src/cli/commands/doctor.ts +317 -7
- package/src/cli/commands/factory/factory.ts +311 -0
- package/src/cli/commands/install.ts +180 -45
- package/src/cli/commands/launch/claude.ts +2 -0
- package/src/cli/commands/launch/shared.ts +48 -16
- package/src/cli/commands/plugin/install.ts +36 -15
- package/src/cli/commands/plugin/plugin.ts +3 -2
- package/src/cli/commands/report/adapter.ts +11 -2
- package/src/cli/commands/report/contract.ts +21 -0
- package/src/cli/commands/report/highlight.ts +34 -4
- package/src/cli/commands/report/index.ts +186 -171
- package/src/cli/commands/report/markdown.ts +105 -0
- package/src/cli/commands/report/palette.ts +118 -0
- package/src/cli/commands/report/renderer.ts +456 -153
- package/src/cli/commands/report/types.ts +16 -0
- package/src/cli/commands/session/context.ts +102 -0
- package/src/cli/commands/session/prepare.ts +32 -4
- package/src/cli/commands/session/registry.ts +90 -0
- package/src/cli/commands/setup.ts +50 -24
- package/src/cli/commands/shared/companion-selection.ts +3 -1
- package/src/cli/commands/studio/access.ts +6 -14
- package/src/cli/commands/studio/areas.ts +112 -33
- package/src/cli/commands/studio/companion-add.ts +87 -0
- package/src/cli/commands/studio/companion-removal.ts +86 -0
- package/src/cli/commands/studio/factory-credential.ts +35 -0
- package/src/cli/commands/studio/factory-git-tokens.ts +40 -0
- package/src/cli/commands/studio/factory-relay.ts +18 -0
- package/src/cli/commands/studio/graph-model.ts +61 -0
- package/src/cli/commands/studio/graph.ts +336 -0
- package/src/cli/commands/studio/index.ts +33 -6
- package/src/cli/commands/studio/mate-inventory.ts +1 -1
- package/src/cli/commands/studio/openspec-cli.ts +10 -58
- package/src/cli/commands/studio/payload.ts +292 -20
- package/src/cli/commands/studio/repository-add.ts +116 -0
- package/src/cli/commands/studio/routes.ts +47 -6
- package/src/cli/commands/studio/selection.ts +170 -17
- package/src/cli/commands/studio/server.ts +552 -327
- package/src/cli/commands/studio/services.ts +120 -0
- package/src/cli/commands/studio/skill-files.ts +133 -0
- package/src/cli/commands/studio/studio-app.ts +67 -0
- package/src/cli/commands/studio/terminal-assets.ts +21 -33
- package/src/cli/commands/studio/terminal.ts +128 -16
- package/src/cli/commands/studio/vault.ts +218 -44
- package/src/cli/commands/studio/views/model.ts +13 -0
- package/src/cli/commands/studio/views/vault/markdown-tree.ts +599 -0
- package/src/cli/commands/studio/views/vault/view.ts +185 -0
- package/src/cli/commands/studio/workset-session.ts +164 -0
- package/src/cli/commands/unwrap.ts +19 -0
- package/src/cli/commands/update.ts +55 -9
- package/src/cli/commands/vscode/release-vsix.json +4 -0
- package/src/cli/commands/vscode/setup.ts +213 -0
- package/src/cli/commands/vscode/vsix.ts +114 -0
- package/src/cli/commands/working/cleanup.ts +83 -18
- package/src/cli/commands/working/link.ts +76 -0
- package/src/cli/commands/working/working.ts +10 -0
- package/src/cli/commands/working/worktree.ts +547 -0
- package/src/cli/commands/wrap.ts +38 -20
- package/src/cli/companion-link-wizard.tsx +2 -0
- package/src/cli/companion-selector.tsx +2 -0
- package/src/cli/confirm.ts +2 -0
- package/src/cli/install-plan.tsx +127 -160
- package/src/cli/launch-selector.tsx +2 -0
- package/src/cli/main.ts +48 -5
- package/src/cli/parse-flags.ts +32 -6
- package/src/cli/repo-list-table.tsx +2 -0
- package/src/cli/setup-selector.tsx +86 -151
- package/src/cli/usage.ts +20 -1
- package/src/create-mate.ts +5 -4
- package/src/hooks/companion-instructions.ts +198 -0
- package/src/hooks/hook-io.ts +78 -0
- package/src/hooks/rtk-worktree-git.ts +48 -0
- package/src/hooks/session-banner.ts +24 -30
- package/src/hooks/session-end.ts +10 -0
- package/src/hooks/session-guidance.ts +18 -22
- package/src/hooks/session-prepare.ts +137 -34
- package/src/hooks/session-register.ts +199 -0
- package/src/hooks/tokensave-route.ts +30 -0
- package/src/hooks/validate-artifact-path.ts +121 -25
- package/src/index.ts +4 -0
- package/src/lib/apply-context/fingerprint.ts +174 -0
- package/src/lib/apply-context/protocol.ts +193 -0
- package/src/lib/change-layout.ts +154 -0
- package/src/lib/components/confirm-prompt.tsx +21 -9
- package/src/lib/components/select-menu.tsx +10 -3
- package/src/lib/components/spinner.tsx +4 -2
- package/src/lib/components/startup-progress.tsx +227 -41
- package/src/lib/components/text-input-display.tsx +2 -0
- package/src/lib/components/wizard-footer.tsx +2 -0
- package/src/lib/components/wizard-header.tsx +16 -12
- package/src/lib/context-mode-package.ts +24 -11
- package/src/lib/delivery/archive-change.ts +165 -0
- package/src/lib/delivery/branch-template.ts +122 -0
- package/src/lib/delivery/branches.ts +152 -0
- package/src/lib/delivery/checkout.ts +102 -0
- package/src/lib/delivery/environment.ts +37 -0
- package/src/lib/delivery/forge.ts +279 -0
- package/src/lib/delivery/merge-git.ts +273 -0
- package/src/lib/delivery/overlap.ts +209 -0
- package/src/lib/delivery/record-delivery.ts +392 -0
- package/src/lib/delivery/record.ts +417 -0
- package/src/lib/delivery/refresh.ts +288 -0
- package/src/lib/delivery/repository-access.ts +141 -0
- package/src/lib/delivery/resolve-branch.ts +430 -0
- package/src/lib/delivery/stages.ts +111 -0
- package/src/lib/delivery/token.ts +24 -0
- package/src/lib/factory/attach-client.ts +123 -0
- package/src/lib/factory/attach.ts +178 -0
- package/src/lib/factory/broker.ts +187 -0
- package/src/lib/factory/bun-commands.ts +39 -0
- package/src/lib/factory/client.ts +113 -0
- package/src/lib/factory/clone-url.ts +39 -0
- package/src/lib/factory/command.ts +77 -0
- package/src/lib/factory/credential-store.ts +153 -0
- package/src/lib/factory/frames.ts +77 -0
- package/src/lib/factory/git-auth.ts +61 -0
- package/src/lib/factory/git-credential-store.ts +181 -0
- package/src/lib/factory/ids.ts +68 -0
- package/src/lib/factory/keyed-serial.ts +27 -0
- package/src/lib/factory/outcomes/actions.ts +130 -0
- package/src/lib/factory/outcomes/index.ts +457 -0
- package/src/lib/factory/outcomes/lifecycle.ts +212 -0
- package/src/lib/factory/outcomes/runs.ts +81 -0
- package/src/lib/factory/outcomes/sessions.ts +60 -0
- package/src/lib/factory/prepare.ts +55 -0
- package/src/lib/factory/pty.ts +103 -0
- package/src/lib/factory/runner/companion-context.ts +178 -0
- package/src/lib/factory/runner/control.ts +92 -0
- package/src/lib/factory/runner/harness-agent.ts +250 -0
- package/src/lib/factory/runner/live.ts +159 -0
- package/src/lib/factory/runner/questions.ts +22 -0
- package/src/lib/factory/runner/rank.ts +26 -0
- package/src/lib/factory/runner/run-policy.ts +12 -0
- package/src/lib/factory/runner/run.ts +199 -0
- package/src/lib/factory/runner/scheduler.ts +498 -0
- package/src/lib/factory/runner/state.ts +233 -0
- package/src/lib/factory/runner/workflow.ts +546 -0
- package/src/lib/factory/runtime.ts +1081 -0
- package/src/lib/factory/sandbox.ts +292 -0
- package/src/lib/factory/worktree-branch.ts +17 -0
- package/src/lib/frontmatter.ts +18 -0
- package/src/lib/install.ts +66 -14
- package/src/lib/live-progress.ts +36 -0
- package/src/lib/member-choices.ts +67 -0
- package/src/lib/opencode-plugin-package.ts +5 -5
- package/src/lib/opencode-server.ts +238 -0
- package/src/lib/openspec-cli.ts +116 -0
- package/src/lib/openspec-scopes.ts +86 -0
- package/src/lib/orchestrator/adapters/base.ts +55 -22
- package/src/lib/orchestrator/adapters/claude-args.ts +50 -0
- package/src/lib/orchestrator/adapters/claude.ts +201 -43
- package/src/lib/orchestrator/adapters/opencode.ts +55 -2
- package/src/lib/orchestrator/checkout-adoption.ts +125 -0
- package/src/lib/orchestrator/companion-hub.ts +6 -1
- package/src/lib/orchestrator/companion-registry-store.ts +6 -2
- package/src/lib/orchestrator/config-store.ts +3 -2
- package/src/lib/orchestrator/editor.ts +32 -26
- package/src/lib/orchestrator/engine-floor.ts +48 -0
- package/src/lib/orchestrator/framework-context.ts +26 -14
- package/src/lib/orchestrator/global-config-store.ts +11 -0
- package/src/lib/orchestrator/launcher.ts +49 -3
- package/src/lib/orchestrator/openspec-store.ts +14 -54
- package/src/lib/orchestrator/projection-claude-commands.ts +36 -0
- package/src/lib/orchestrator/projection-claude-entry.ts +42 -21
- package/src/lib/orchestrator/projection-claude-links.ts +230 -0
- package/src/lib/orchestrator/projection-claude-skills.ts +39 -131
- package/src/lib/orchestrator/projection-companion-link.ts +12 -1
- package/src/lib/orchestrator/projection-entries.ts +121 -51
- package/src/lib/orchestrator/projection-opencode-copies.ts +93 -32
- package/src/lib/orchestrator/projection-openspec-store.ts +54 -9
- package/src/lib/orchestrator/projection-runtime-documents.ts +81 -49
- package/src/lib/orchestrator/projection-types.ts +63 -1
- package/src/lib/orchestrator/refresh-working-claude-links.ts +89 -0
- package/src/lib/orchestrator/registry-checkouts.ts +177 -0
- package/src/lib/orchestrator/repository-link.ts +216 -57
- package/src/lib/orchestrator/serving-claude-wrap.ts +43 -0
- package/src/lib/orchestrator/session-context-link.ts +73 -0
- package/src/lib/orchestrator/session-prepare.ts +87 -12
- package/src/lib/orchestrator/setup-compatibilities.ts +56 -70
- package/src/lib/orchestrator/types.ts +16 -2
- package/src/lib/orchestrator/umbrella-checkouts.ts +102 -0
- package/src/lib/orchestrator/working-repo-projection.ts +73 -10
- package/src/lib/orchestrator/workspace-document.ts +105 -0
- package/src/lib/orchestrator/workspace-inventory.ts +5 -1
- package/src/lib/orchestrator/wrap-pass.ts +23 -1
- package/src/lib/package-paths.ts +37 -0
- package/src/lib/public-npm.ts +105 -43
- package/src/lib/runtime-directory-refresh.ts +17 -1
- package/src/lib/session-attribution.ts +52 -0
- package/src/lib/session-state.ts +355 -0
- package/src/lib/session-stop.ts +64 -0
- package/src/lib/update-checker.ts +7 -1
- package/src/lib/usage/aggregate.ts +202 -0
- package/src/lib/usage/cache.ts +87 -0
- package/src/lib/usage/claude-pricing.ts +71 -0
- package/src/lib/usage/claude.ts +189 -0
- package/src/lib/usage/collect.ts +56 -0
- package/src/lib/usage/opencode.ts +188 -0
- package/src/lib/usage/records.ts +80 -0
- package/src/lib/usage/rtk-database.ts +72 -0
- package/src/lib/usage/savings.ts +209 -0
- package/src/lib/usage/scope.ts +182 -0
- package/src/lib/usage/source.ts +102 -0
- package/src/lib/usage/types.ts +143 -0
- package/src/lib/usage/window.ts +37 -0
- package/src/lib/workset/factory-local.ts +157 -0
- package/src/lib/workset/record.ts +547 -0
- package/src/lib/workset/repositories.ts +148 -0
- package/src/lib/workset/stage.ts +148 -0
- package/src/lib/workset/stages.ts +113 -0
- package/src/lib/workset/worktree-include.ts +161 -0
- package/src/lib/workset/worktree-index.ts +120 -0
- package/src/lib/workset/worktree.ts +1388 -0
- package/src/opencode/background-server.ts +145 -0
- package/src/opencode/companion-hooks.ts +151 -9
- package/src/opencode/companion-policy.ts +54 -22
- package/src/opencode/enter-worktree.ts +320 -0
- package/src/opencode/projected-guidance.ts +6 -2
- package/src/opencode/session-prepare.ts +2 -1
- package/src/opencode/session-register.ts +176 -0
- package/src/opencode/tui.tsx +24 -27
- package/src/plugins.ts +1 -0
- package/src/runtime/artifact-refusal.ts +63 -0
- package/src/runtime/claude-bg-isolation.ts +138 -0
- package/src/runtime/claude-delivery-plan.ts +121 -11
- package/src/runtime/commit-attribution-guard.ts +181 -0
- package/src/runtime/companion-git.ts +62 -12
- package/src/runtime/companion-guidance.ts +37 -12
- package/src/runtime/companion-instructions.ts +340 -0
- package/src/runtime/companion-lock.ts +30 -7
- package/src/runtime/current-branch.ts +24 -0
- package/src/runtime/entered-worktree.ts +24 -0
- package/src/runtime/env.ts +59 -8
- package/src/runtime/error-message.ts +4 -0
- package/src/runtime/git-layout.ts +366 -0
- package/src/runtime/git-tracked.ts +60 -0
- package/src/runtime/index.ts +29 -0
- package/src/runtime/launch-env-guard.ts +65 -0
- package/src/runtime/managed-block.ts +117 -0
- package/src/runtime/markdown-scan.ts +266 -0
- package/src/runtime/opencode-server-record.ts +136 -0
- package/src/runtime/physical-path.ts +111 -0
- package/src/runtime/policy.ts +50 -2
- package/src/runtime/projected-flag.ts +7 -0
- package/src/runtime/projected-guidance.ts +1 -0
- package/src/runtime/projection.ts +40 -6
- package/src/runtime/repo-destination.ts +72 -0
- package/src/runtime/repo-local.ts +29 -2
- package/src/runtime/rtk-git-guard.ts +66 -0
- package/src/runtime/runtime-directory.ts +5 -0
- package/src/runtime/runtime-document-manifest.ts +290 -29
- package/src/runtime/runtime-document-manifest.typecheck.ts +10 -0
- package/src/runtime/secret-guard.ts +169 -0
- package/src/runtime/secret-patterns.ts +397 -0
- package/src/runtime/secret-policy-weakening.ts +122 -0
- package/src/runtime/secret-scan.ts +90 -0
- package/src/runtime/serving-claude-wrap.ts +41 -0
- package/src/runtime/session-context.ts +99 -0
- package/src/runtime/session-kind.ts +13 -0
- package/src/runtime/session-registry.ts +434 -0
- package/src/runtime/shell-heredoc.ts +81 -0
- package/src/runtime/tokensave-route.ts +157 -0
- package/src/runtime/umbrella-folder.ts +56 -0
- package/src/runtime/wrap-state.ts +80 -15
- package/src/runtime/write-atomic.ts +64 -0
- package/src/studio.ts +163 -0
- package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +14 -10
- package/src/templates/capabilities/openspec-cap/mate-minimal/templates/spec.md +3 -5
- package/src/templates/capabilities/openspec-cap/mate-v1/schema.yaml +18 -102
- package/src/templates/capabilities/openspec-cap/mate-v1/templates/spec.md +3 -5
- package/src/templates/capabilities/openspec-cap/openspec-conventions.yaml +20 -14
- package/src/templates/mate-skills/THIRD-PARTY-NOTICES.md +40 -0
- package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +217 -0
- package/src/templates/mate-skills/agents/mate-apply-change/references/mate-compact-apply.md +47 -0
- package/src/templates/mate-skills/agents/mate-apply-change/references/openspec-apply-change.md +200 -0
- package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +81 -0
- package/src/templates/mate-skills/agents/{mate-openspec-backfill → mate-backfill-spec}/SKILL.md +11 -4
- package/src/templates/mate-skills/agents/mate-clarify-intent/SKILL.md +110 -0
- package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +70 -0
- package/src/templates/mate-skills/agents/mate-explore-change/references/openspec-explore.md +350 -0
- package/src/templates/mate-skills/agents/mate-grill-me/SKILL.md +11 -4
- package/src/templates/mate-skills/agents/mate-grill-with-docs/SKILL.md +2 -2
- package/src/templates/mate-skills/agents/mate-interview-me/SKILL.md +12 -5
- package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +106 -0
- package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +45 -0
- package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-propose.md +169 -0
- package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-update-change.md +103 -0
- package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +271 -0
- package/src/templates/mate-skills/{claude/mate-artifact-publish → agents/mate-publish-artifact}/references/openspec.md +8 -5
- package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +105 -20
- package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +91 -68
- package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +217 -0
- package/src/templates/mate-skills/claude/mate-apply-change/references/mate-compact-apply.md +47 -0
- package/src/templates/mate-skills/claude/mate-apply-change/references/openspec-apply-change.md +200 -0
- package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +81 -0
- package/src/templates/mate-skills/claude/{mate-openspec-backfill → mate-backfill-spec}/SKILL.md +11 -4
- package/src/templates/mate-skills/claude/mate-clarify-intent/SKILL.md +110 -0
- package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +70 -0
- package/src/templates/mate-skills/claude/mate-explore-change/references/openspec-explore.md +350 -0
- package/src/templates/mate-skills/claude/mate-grill-me/SKILL.md +11 -4
- package/src/templates/mate-skills/claude/mate-grill-with-docs/SKILL.md +2 -2
- package/src/templates/mate-skills/claude/mate-interview-me/SKILL.md +12 -5
- package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +106 -0
- package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +45 -0
- package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-propose.md +169 -0
- package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-update-change.md +103 -0
- package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +271 -0
- package/src/templates/mate-skills/{agents/mate-artifact-publish → claude/mate-publish-artifact}/references/openspec.md +8 -5
- package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +105 -20
- package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +91 -68
- package/src/templates/mate-skills/openspec-references.ts +142 -0
- package/src/templates/root/TEMPLATE_AGENTS.md +2 -2
- package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +4581 -397
- package/src/tools/setup/capabilities/companion-mentions.ts +27 -0
- package/src/tools/setup/capabilities/context-mode.ts +56 -7
- package/src/tools/setup/capabilities/graphify-gate.ts +31 -0
- package/src/tools/setup/capabilities/graphify-secrets.ts +243 -0
- package/src/tools/setup/capabilities/graphify.ts +46 -7
- package/src/tools/setup/capabilities/openspec.ts +163 -272
- package/src/tools/setup/capabilities/react-doctor.ts +8 -1
- package/src/tools/setup/capabilities/rtk.ts +97 -1
- package/src/tools/setup/capabilities/tokensave.ts +113 -71
- package/src/tools/setup/context-services.ts +9 -17
- package/src/tools/setup/dynamic-plugins/audiences.ts +65 -21
- package/src/tools/setup/dynamic-plugins/frozen.ts +32 -13
- package/src/tools/setup/dynamic-plugins/hydrate.ts +8 -7
- package/src/tools/setup/dynamic-plugins/install.ts +46 -48
- package/src/tools/setup/dynamic-plugins/loader.ts +11 -7
- package/src/tools/setup/dynamic-plugins/paths.ts +30 -10
- package/src/tools/setup/dynamic-plugins/verify.ts +10 -7
- package/src/tools/setup/dynamic-plugins/workspaces.ts +153 -0
- package/src/tools/setup/engine.ts +100 -23
- package/src/tools/setup/install-contract.ts +8 -0
- package/src/tools/setup/managed-output.ts +51 -0
- package/src/tools/setup/mate-skill-copies.ts +51 -0
- package/src/tools/setup/mate.ts +88 -13
- package/src/tools/setup/package-managers/uv.ts +73 -11
- package/src/tools/setup/plugin.ts +40 -0
- package/src/tools/setup/plugins/gitignore.ts +15 -9
- package/src/tools/setup/plugins/guidance.ts +7 -4
- package/src/tools/setup/providers/agent-file-sections.ts +4 -2
- package/src/tools/setup/providers/claude-attribution.ts +65 -0
- package/src/tools/setup/providers/claude-plugin-folders.ts +625 -0
- package/src/tools/setup/providers/claude-plugin-hooks.ts +89 -19
- package/src/tools/setup/providers/claude-worktree-plugins.ts +122 -0
- package/src/tools/setup/providers/claude.ts +332 -8
- package/src/tools/setup/providers/opencode.ts +180 -1
- package/src/tools/setup/utils.ts +22 -6
- package/src/tools/setup/working-repo-cleanup.ts +30 -2
- package/src/tools/setup/working-repo-local-state.ts +252 -75
- package/src/tools/setup.ts +196 -28
- package/studio-dist/client/assets/app-D9cw6szy.css +2 -0
- package/studio-dist/client/assets/artifacts-WD2ZXYrx.js +1 -0
- package/studio-dist/client/assets/button-Br0O1sXw.js +1 -0
- package/studio-dist/client/assets/combobox-DA7RAUUZ.js +1 -0
- package/studio-dist/client/assets/companion-view-CrabvxS8.js +1 -0
- package/studio-dist/client/assets/dist-Dm7MtyHc.js +5 -0
- package/studio-dist/client/assets/factory-DGS0E16C.js +6 -0
- package/studio-dist/client/assets/fields-6aXBpFhJ.js +1 -0
- package/studio-dist/client/assets/getting-started-Clde4w6P.js +1 -0
- package/studio-dist/client/assets/getting-started-D6kgWwWZ.js +1 -0
- package/studio-dist/client/assets/getting-started._topic-BiunccbT.js +1 -0
- package/studio-dist/client/assets/getting-started.index-DpiNoGw8.js +1 -0
- package/studio-dist/client/assets/graph-B_TCBVbu.js +2 -0
- package/studio-dist/client/assets/graph-canvas-Ba37Y5AE.js +3242 -0
- package/studio-dist/client/assets/guides-Du_RtJxP.js +1 -0
- package/studio-dist/client/assets/index-Df8L1LQa.js +40 -0
- package/studio-dist/client/assets/jsx-runtime-MZURdZre.js +1 -0
- package/studio-dist/client/assets/markdown-view-BOX6x0rL.js +1 -0
- package/studio-dist/client/assets/panel-dbmCx7Mx.js +1 -0
- package/studio-dist/client/assets/preload-helper-BLdHbfdN.js +1 -0
- package/studio-dist/client/assets/queries-RvHeXY12.js +1 -0
- package/studio-dist/client/assets/react-3QStrcDO.js +27 -0
- package/studio-dist/client/assets/report-url-XRL0x1SY.js +1 -0
- package/studio-dist/client/assets/reports-r3IK7Doz.js +1 -0
- package/studio-dist/client/assets/routes-C0A5LTFc.js +1 -0
- package/studio-dist/client/assets/select-CnaMd617.js +1 -0
- package/studio-dist/client/assets/skills-CzjzHpBT.js +1 -0
- package/studio-dist/client/assets/specs-B0ldF_6J.js +1 -0
- package/studio-dist/client/assets/specs-view-BnCLA0gW.js +1 -0
- package/studio-dist/client/assets/spinner-Dcm3fqK1.js +1 -0
- package/studio-dist/client/assets/steps-C0p2N1Pb.js +1 -0
- package/studio-dist/client/assets/store-Dw34catY.js +1 -0
- package/studio-dist/client/assets/studio-Cpz_HRHp.js +100 -0
- package/studio-dist/client/assets/studio-queries-ibmpFo6R.js +2 -0
- package/studio-dist/client/assets/terminal-eU5fzQzv.css +1 -0
- package/studio-dist/client/assets/usage-C2QJ_0IZ.js +55 -0
- package/studio-dist/client/assets/useAnchoredPopupScrollLock-Bj-FWb8z.js +1 -0
- package/studio-dist/client/assets/useMutation-aAr2uiay.js +1 -0
- package/studio-dist/client/assets/useSelector-AYcH7lB0.js +2 -0
- package/studio-dist/client/assets/vault-BGcxkSIY.js +1 -0
- package/studio-dist/client/assets/warnings-R1cE1rLf.js +1 -0
- package/studio-dist/client/assets/wasm-inline-C2en61B5.js +1 -0
- package/studio-dist/client/assets/workflow-C2qTrMDH.js +1 -0
- package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-Bn896ZYj.js +122 -0
- package/studio-dist/server/assets/_tanstack-start-manifest_v.js +162 -0
- package/studio-dist/server/assets/actions-D8erOphH.js +44 -0
- package/studio-dist/server/assets/actions-DYSv-9VV.js +60 -0
- package/studio-dist/server/assets/artifacts-DnF9L3dZ.js +216 -0
- package/studio-dist/server/assets/button-CgOIVdmD.js +10240 -0
- package/studio-dist/server/assets/combobox-DV_s9W0s.js +483 -0
- package/studio-dist/server/assets/companion-view-BKVXD3TO.js +39 -0
- package/studio-dist/server/assets/companions-C7fctnU9.js +31 -0
- package/studio-dist/server/assets/createServerRpc-bFKFpGFG.js +11 -0
- package/studio-dist/server/assets/dist-DpJWKyCm.js +5582 -0
- package/studio-dist/server/assets/empty-plugin-adapters-Cipd4ZH4.js +4 -0
- package/studio-dist/server/assets/factory-C7Ybg0xG.js +3075 -0
- package/studio-dist/server/assets/factory-Df5uAHjb.js +116 -0
- package/studio-dist/server/assets/fields-BbieQTD0.js +1190 -0
- package/studio-dist/server/assets/getting-started-B136TP57.js +4 -0
- package/studio-dist/server/assets/getting-started-CRxMWorQ.js +67 -0
- package/studio-dist/server/assets/getting-started._topic-DJKQAzYl.js +13 -0
- package/studio-dist/server/assets/getting-started.index-D84gec1t.js +13 -0
- package/studio-dist/server/assets/graph-CSje3029.js +801 -0
- package/studio-dist/server/assets/graph-DDZzXM1L.js +16 -0
- package/studio-dist/server/assets/graph-canvas-22bWB5-2.js +21066 -0
- package/studio-dist/server/assets/graph-wire-BdSUx0G5.js +58 -0
- package/studio-dist/server/assets/guides-D9dk1Frq.js +13 -0
- package/studio-dist/server/assets/guides-IE-19POz.js +5 -0
- package/studio-dist/server/assets/guides.server-vcYRY5wx.js +66 -0
- package/studio-dist/server/assets/jsx-runtime-Bt0s0YKS.js +451 -0
- package/studio-dist/server/assets/markdown-view-BR8dJ7aR.js +105 -0
- package/studio-dist/server/assets/model-PyPALjii.js +18 -0
- package/studio-dist/server/assets/panel-BR_t9iMM.js +169 -0
- package/studio-dist/server/assets/queries-DWoTin-q.js +32 -0
- package/studio-dist/server/assets/react-CdqSUhaL.js +89 -0
- package/studio-dist/server/assets/redirect-BaZ_QyqF.js +39 -0
- package/studio-dist/server/assets/report-url-BUXPcE_8.js +9 -0
- package/studio-dist/server/assets/reports-CQ9qQ1-n.js +141 -0
- package/studio-dist/server/assets/reports-dYDEoBeq.js +18 -0
- package/studio-dist/server/assets/router-DkRHNTpE.js +11638 -0
- package/studio-dist/server/assets/routes-B6GfOew4.js +473 -0
- package/studio-dist/server/assets/search-BJnWLfkG.js +55 -0
- package/studio-dist/server/assets/select-Af7Wibii.js +1609 -0
- package/studio-dist/server/assets/shell-Hq-hXgnT.js +53 -0
- package/studio-dist/server/assets/skills-B7nEuVbx.js +267 -0
- package/studio-dist/server/assets/skills-B_YYL7q8.js +28 -0
- package/studio-dist/server/assets/specs-BpLUFntA.js +51 -0
- package/studio-dist/server/assets/specs-view-0peMVd22.js +426 -0
- package/studio-dist/server/assets/spinner-CdwJW4VB.js +20 -0
- package/studio-dist/server/assets/start-h3ICWwd2.js +36 -0
- package/studio-dist/server/assets/steps-D56DApvK.js +181 -0
- package/studio-dist/server/assets/store-Cs17okNG.js +280 -0
- package/studio-dist/server/assets/studio-CAcKp3bM.js +10340 -0
- package/studio-dist/server/assets/studio-queries-BtRGzDdh.js +1451 -0
- package/studio-dist/server/assets/usage-COdjd1gD.js +25570 -0
- package/studio-dist/server/assets/usage-f6pqE1tm.js +24 -0
- package/studio-dist/server/assets/useAnchoredPopupScrollLock-DlBKHRw7.js +756 -0
- package/studio-dist/server/assets/useMutation-DzTZGenE.js +690 -0
- package/studio-dist/server/assets/useSelector-DUmCUXAs.js +3387 -0
- package/studio-dist/server/assets/utils-C9CX1kcy.js +221 -0
- package/studio-dist/server/assets/vault-BDuIUq0F.js +1035 -0
- package/studio-dist/server/assets/vault-BVLp6zu3.js +85 -0
- package/studio-dist/server/assets/views-flRUr21z.js +80 -0
- package/studio-dist/server/assets/warnings-CDy9pdgL.js +24 -0
- package/studio-dist/server/assets/wasm-inline-CNeBKGwC.js +3 -0
- package/studio-dist/server/assets/workflow-D9GKI2EV.js +680 -0
- package/studio-dist/server/server.js +16640 -0
- package/wrappers/bin/graphify +52 -4
- package/wrappers/bin/openspec +33 -9
- package/wrappers/lib/graphify-gate.mjs +8 -0
- package/src/cli/commands/report/collector.ts +0 -288
- package/src/cli/commands/studio/views/client.ts +0 -654
- package/src/cli/commands/studio/views/companion-picker.tsx +0 -95
- package/src/cli/commands/studio/views/companion-selector.tsx +0 -94
- package/src/cli/commands/studio/views/dashboard/changes.tsx +0 -107
- package/src/cli/commands/studio/views/dashboard/index.tsx +0 -19
- package/src/cli/commands/studio/views/document.tsx +0 -842
- package/src/cli/commands/studio/views/error.tsx +0 -20
- package/src/cli/commands/studio/views/reports/index.tsx +0 -49
- package/src/cli/commands/studio/views/selection-fields.tsx +0 -14
- package/src/cli/commands/studio/views/skills/index.tsx +0 -87
- package/src/cli/commands/studio/views/specs/index.tsx +0 -157
- package/src/cli/commands/studio/views/styles.ts +0 -519
- package/src/cli/commands/studio/views/terminal.tsx +0 -484
- package/src/cli/commands/studio/views/vault/state.ts +0 -43
- package/src/cli/commands/studio/views/warnings.tsx +0 -21
- package/src/cli/commands/studio/views/workflow/index.tsx +0 -21
- package/src/cli/commands/studio/views/workflow/steps.ts +0 -337
- package/src/cli/commands/studio/views/workflow/transcript.tsx +0 -190
- package/src/lib/components/theme.ts +0 -2
- package/src/templates/mate-skills/agents/mate-artifact-publish/SKILL.md +0 -185
- package/src/templates/mate-skills/claude/mate-artifact-publish/SKILL.md +0 -185
- package/src/tools/setup/git-utils.ts +0 -30
- package/src/tools/setup/runtime-documents.ts +0 -291
|
@@ -0,0 +1,1081 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { parseRemote } from "../delivery/forge";
|
|
4
|
+
import { deliveryCheckout } from "../delivery/checkout";
|
|
5
|
+
import { newBranchBase, resolveDeliveryBranch, worktreeAddArgs } from "../delivery/resolve-branch";
|
|
6
|
+
import { resolveWorksetBranch } from "../workset/record";
|
|
7
|
+
|
|
8
|
+
import { type CommandOptions, type CommandResult, type CommandRunner, runCommand } from "./command";
|
|
9
|
+
import { checkedCloneUrl } from "./clone-url";
|
|
10
|
+
import { authFailureMessage, gitAuthEnv, isAuthFailure, scrubToken } from "./git-auth";
|
|
11
|
+
import type { GitCredentials } from "./git-credential-store";
|
|
12
|
+
import type { AgentCredential } from "./credential-store";
|
|
13
|
+
import { KeyedSerial } from "./keyed-serial";
|
|
14
|
+
import { readWorktreeBranch } from "./worktree-branch";
|
|
15
|
+
import {
|
|
16
|
+
assertRepository,
|
|
17
|
+
assertWorksetId,
|
|
18
|
+
BUN_CACHE_VOLUME,
|
|
19
|
+
containerName,
|
|
20
|
+
deliveryBranch,
|
|
21
|
+
FactoryError,
|
|
22
|
+
homeVolume,
|
|
23
|
+
LABEL_REPOSITORY,
|
|
24
|
+
LABEL_WORKSET,
|
|
25
|
+
repoKey,
|
|
26
|
+
repositoryFromKey,
|
|
27
|
+
} from "./ids";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The Workset runtime: one unprivileged Sysbox container per Workset, with its
|
|
31
|
+
* own worktree on its Delivery Branch (default `workset/<workset>`), driven through
|
|
32
|
+
* the inner Docker daemon.
|
|
33
|
+
*
|
|
34
|
+
* Runs inside the factory broker, which alone holds the inner socket. Callers
|
|
35
|
+
* name a Workset, a repository and a command; image, mounts, runtime and
|
|
36
|
+
* flags and the Docker client environment are fixed here. Git runs as the unprivileged user so clones and
|
|
37
|
+
* worktrees keep the uid the Workset containers share.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
export type WorksetState = "running" | "paused" | "missing";
|
|
41
|
+
|
|
42
|
+
export interface WorksetInfo {
|
|
43
|
+
id: string;
|
|
44
|
+
repository: string | null;
|
|
45
|
+
branch: string;
|
|
46
|
+
state: WorksetState;
|
|
47
|
+
/** What resolving a new worktree's Delivery Branch reported, e.g. a dependency not inherited. */
|
|
48
|
+
warnings?: string[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface SpawnRequest {
|
|
52
|
+
id: string;
|
|
53
|
+
repository: string;
|
|
54
|
+
/** Where to clone from when the factory has no clone yet. */
|
|
55
|
+
remoteUrl: string;
|
|
56
|
+
/** The Session Companion, mounted read-write at the same path. */
|
|
57
|
+
companion: string;
|
|
58
|
+
/** The memory size the next stage needs; `build` when absent. */
|
|
59
|
+
size?: MemorySize;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Agent stages run at the agent memory limit; builds and sessions at the full one. */
|
|
63
|
+
export type MemorySize = "agent" | "build";
|
|
64
|
+
|
|
65
|
+
export interface ExecRequest {
|
|
66
|
+
id: string;
|
|
67
|
+
command: string[];
|
|
68
|
+
/** Working directory relative to the worktree. */
|
|
69
|
+
cwd?: string;
|
|
70
|
+
/** Standard input for the command, closed after it is written. */
|
|
71
|
+
stdin?: Uint8Array;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Each Workset container's limits; memory includes swap. */
|
|
75
|
+
export interface WorksetLimits {
|
|
76
|
+
/** A Docker size such as `4g`: the build size. */
|
|
77
|
+
memory: string;
|
|
78
|
+
/** The agent size; `memory` when absent. */
|
|
79
|
+
agentMemory?: string;
|
|
80
|
+
pids: number;
|
|
81
|
+
/** Null sets no CPU limit. */
|
|
82
|
+
cpus: string | null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface RuntimeOptions {
|
|
86
|
+
dockerHost: string;
|
|
87
|
+
stateDir: string;
|
|
88
|
+
image: string;
|
|
89
|
+
/** The unprivileged user Git and Workset commands run as. */
|
|
90
|
+
user: string;
|
|
91
|
+
/** Companions must resolve inside this directory. */
|
|
92
|
+
companionsDir: string;
|
|
93
|
+
/** The Git tokens a clone or fetch of a remote may use; none when unset. */
|
|
94
|
+
gitCredentials?: GitCredentials;
|
|
95
|
+
/** Unset leaves containers unlimited. */
|
|
96
|
+
limits?: WorksetLimits;
|
|
97
|
+
/** How many Workset containers may run at once; unset caps nothing. */
|
|
98
|
+
maxWorksets?: number;
|
|
99
|
+
/** Minutes without activity before `sweepIdle` stops a container; 0 or unset never. */
|
|
100
|
+
idleMinutes?: number;
|
|
101
|
+
now?: () => number;
|
|
102
|
+
run?: CommandRunner;
|
|
103
|
+
exists?: (file: string) => boolean;
|
|
104
|
+
realpath?: (file: string) => string;
|
|
105
|
+
listDir?: (dir: string) => string[];
|
|
106
|
+
/** Where the inner daemon's container cgroups live; default `/sys/fs/cgroup`. */
|
|
107
|
+
cgroupRoot?: string;
|
|
108
|
+
writeFile?: (file: string, data: string) => void;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const SYSBOX_RUNTIME = "sysbox-runc";
|
|
112
|
+
/** The soft memory limit's share of the hard one. */
|
|
113
|
+
const SOFT_MEMORY_SHARE = 0.9;
|
|
114
|
+
const SIZE_UNITS: Record<string, number> = { b: 1, k: 1024, m: 1024 ** 2, g: 1024 ** 3 };
|
|
115
|
+
|
|
116
|
+
/** Bytes in a Docker size such as `4g` or `512m`; null when it is not one. */
|
|
117
|
+
export function dockerSizeBytes(size: string): number | null {
|
|
118
|
+
const match = /^(\d+(?:\.\d+)?)([bkmg])?$/i.exec(size.trim());
|
|
119
|
+
if (!match) return null;
|
|
120
|
+
return Math.floor(Number(match[1]) * SIZE_UNITS[(match[2] ?? "b").toLowerCase()]!);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Set on every process an attach starts in a Workset container, so a stop finds them all. */
|
|
124
|
+
export const SESSION_MARKER = "MATE_FACTORY_SESSION";
|
|
125
|
+
const SESSION_ID = /^[A-Za-z0-9-]{8,64}$/;
|
|
126
|
+
|
|
127
|
+
export function assertSessionMarker(session: unknown): asserts session is string {
|
|
128
|
+
if (typeof session !== "string" || !SESSION_ID.test(session)) {
|
|
129
|
+
throw new FactoryError("the attach session id is not valid");
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const STOP_SECONDS = "10";
|
|
133
|
+
/** A companion clone that takes longer is abandoned. */
|
|
134
|
+
const CLONE_TIMEOUT_MS = 180_000;
|
|
135
|
+
/** A reachability check that takes longer fails. */
|
|
136
|
+
const REMOTE_CHECK_TIMEOUT_MS = 60_000;
|
|
137
|
+
/**
|
|
138
|
+
* How long after its last activity a container is safe from making room: an AFK turn
|
|
139
|
+
* spawns its container, then attaches its bridge a moment later.
|
|
140
|
+
*/
|
|
141
|
+
export const ROOM_GRACE_MS = 60_000;
|
|
142
|
+
const HOME = "/home/mate";
|
|
143
|
+
const BUN_CACHE = "/var/cache/bun";
|
|
144
|
+
|
|
145
|
+
/** What uses a Workset container now; idle means neither. */
|
|
146
|
+
interface Activity {
|
|
147
|
+
sessions: number;
|
|
148
|
+
commands: number;
|
|
149
|
+
lastActivity: number;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function assertCommand(command: unknown, verb: string): asserts command is string[] {
|
|
153
|
+
if (
|
|
154
|
+
!Array.isArray(command) ||
|
|
155
|
+
command.length === 0 ||
|
|
156
|
+
!command.every((part) => typeof part === "string")
|
|
157
|
+
) {
|
|
158
|
+
throw new FactoryError(`${verb} needs a command as a list of strings`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export class WorksetRuntime {
|
|
163
|
+
private readonly run: CommandRunner;
|
|
164
|
+
private readonly exists: (file: string) => boolean;
|
|
165
|
+
private readonly realpath: (file: string) => string;
|
|
166
|
+
private readonly listDir: (dir: string) => string[];
|
|
167
|
+
private readonly cgroupRoot: string;
|
|
168
|
+
private readonly writeFile: (file: string, data: string) => void;
|
|
169
|
+
private ready = false;
|
|
170
|
+
private readonly now: () => number;
|
|
171
|
+
/** In memory: after a broker restart every container's idle clock starts at the restart. */
|
|
172
|
+
private readonly activity = new Map<string, Activity>();
|
|
173
|
+
private readonly startedAt: number;
|
|
174
|
+
/** Operations on one Workset run in order, so an idle stop cannot race a start. */
|
|
175
|
+
private readonly chains = new KeyedSerial();
|
|
176
|
+
/** Counting running containers and starting one happen together. */
|
|
177
|
+
private capacity: Promise<unknown> = Promise.resolve();
|
|
178
|
+
/** Each running container's memory size; unknown after a broker restart until read. */
|
|
179
|
+
private readonly sizes = new Map<string, MemorySize>();
|
|
180
|
+
|
|
181
|
+
constructor(private readonly options: RuntimeOptions) {
|
|
182
|
+
this.now = options.now ?? Date.now;
|
|
183
|
+
this.startedAt = this.now();
|
|
184
|
+
this.run = options.run ?? runCommand;
|
|
185
|
+
this.exists = options.exists ?? fs.existsSync;
|
|
186
|
+
this.realpath = options.realpath ?? fs.realpathSync;
|
|
187
|
+
this.listDir = options.listDir ?? ((dir) => (fs.existsSync(dir) ? fs.readdirSync(dir) : []));
|
|
188
|
+
this.cgroupRoot = options.cgroupRoot ?? "/sys/fs/cgroup";
|
|
189
|
+
this.writeFile = options.writeFile ?? ((file, data) => fs.writeFileSync(file, data));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
private activityOf(id: string): Activity {
|
|
193
|
+
let entry = this.activity.get(id);
|
|
194
|
+
if (!entry) {
|
|
195
|
+
entry = { sessions: 0, commands: 0, lastActivity: this.startedAt };
|
|
196
|
+
this.activity.set(id, entry);
|
|
197
|
+
}
|
|
198
|
+
return entry;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private touch(id: string): void {
|
|
202
|
+
this.activityOf(id).lastActivity = this.now();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** No attached session and no command in progress. */
|
|
206
|
+
isIdle(id: string): boolean {
|
|
207
|
+
const entry = this.activityOf(id);
|
|
208
|
+
return entry.sessions === 0 && entry.commands === 0;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Counts an attach session from now until the returned function is called. */
|
|
212
|
+
beginSession(id: string): () => void {
|
|
213
|
+
return this.track(id, "sessions");
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private track(id: string, kind: "sessions" | "commands"): () => void {
|
|
217
|
+
const entry = this.activityOf(id);
|
|
218
|
+
entry[kind] += 1;
|
|
219
|
+
entry.lastActivity = this.now();
|
|
220
|
+
let ended = false;
|
|
221
|
+
return () => {
|
|
222
|
+
if (ended) return;
|
|
223
|
+
ended = true;
|
|
224
|
+
entry[kind] -= 1;
|
|
225
|
+
entry.lastActivity = this.now();
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
private exclusive<T>(operation: () => Promise<T>): Promise<T> {
|
|
230
|
+
const next = this.capacity.then(operation, operation);
|
|
231
|
+
this.capacity = next.catch(() => {});
|
|
232
|
+
return next;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private repoDir(repository: string): string {
|
|
236
|
+
return path.join(this.options.stateDir, "repos", repoKey(repository));
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
worktree(id: string): string {
|
|
240
|
+
return path.join(this.options.stateDir, "worktrees", id);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
private docker(args: string[]): Promise<CommandResult> {
|
|
244
|
+
return this.run("docker", args, { env: this.dockerEnv() });
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* `remote` names the URL the command talks to: its matching token reaches this one command
|
|
249
|
+
* through its environment, output is scrubbed of it, and a refusal is reported as one.
|
|
250
|
+
*/
|
|
251
|
+
private async git(
|
|
252
|
+
args: string[],
|
|
253
|
+
options: Pick<CommandOptions, "env" | "stdin" | "timeoutMs"> & { remote?: string } = {},
|
|
254
|
+
): Promise<CommandResult> {
|
|
255
|
+
const { remote, ...commandOptions } = options;
|
|
256
|
+
const token =
|
|
257
|
+
remote === undefined ? null : (this.options.gitCredentials?.forUrl(remote) ?? null);
|
|
258
|
+
const auth = remote === undefined ? {} : gitAuthEnv(this.options.stateDir, token);
|
|
259
|
+
// A configured helper would answer before askpass and store the token it was handed.
|
|
260
|
+
const helpers = token === null ? [] : ["-c", "credential.helper="];
|
|
261
|
+
// `ext::` would run a command named by the remote URL.
|
|
262
|
+
const result = await this.run("git", ["-c", "protocol.ext.allow=never", ...helpers, ...args], {
|
|
263
|
+
...commandOptions,
|
|
264
|
+
env: { ...commandOptions.env, ...auth },
|
|
265
|
+
asUser: this.options.user,
|
|
266
|
+
});
|
|
267
|
+
const scrubbed = {
|
|
268
|
+
...result,
|
|
269
|
+
stdout: scrubToken(result.stdout, token),
|
|
270
|
+
stderr: scrubToken(result.stderr, token),
|
|
271
|
+
};
|
|
272
|
+
if (remote !== undefined && result.status !== 0 && isAuthFailure(scrubbed.stderr)) {
|
|
273
|
+
return { ...scrubbed, authFailure: authFailureMessage(remote) } as CommandResult;
|
|
274
|
+
}
|
|
275
|
+
return scrubbed;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private async must(result: Promise<CommandResult>, what: string): Promise<CommandResult> {
|
|
279
|
+
const done = await result;
|
|
280
|
+
if (done.status !== 0) {
|
|
281
|
+
const refusal = (done as CommandResult & { authFailure?: string }).authFailure;
|
|
282
|
+
if (refusal) throw new FactoryError(`${what} failed: ${refusal}`, "auth");
|
|
283
|
+
throw new FactoryError(`${what} failed: ${(done.stderr || done.stdout).trim()}`);
|
|
284
|
+
}
|
|
285
|
+
return done;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Clones a companion into the companions directory as the unprivileged user, with the stored
|
|
290
|
+
* token for its URL. The folder is named after the repository and derived here, never taken
|
|
291
|
+
* from a caller. A checkout of the same repository already there is reported, not cloned again.
|
|
292
|
+
*/
|
|
293
|
+
cloneCompanion(url: unknown): Promise<{ path: string; existing: boolean }> {
|
|
294
|
+
const remote = checkedCloneUrl(url);
|
|
295
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(remote.name)) {
|
|
296
|
+
throw new FactoryError(`${remote.name} cannot name a folder in the companions directory`);
|
|
297
|
+
}
|
|
298
|
+
const target = path.join(this.options.companionsDir, remote.name);
|
|
299
|
+
return this.chains.run(`companion:${remote.name}`, async () => {
|
|
300
|
+
if (this.exists(target)) {
|
|
301
|
+
if (!this.exists(path.join(target, ".git"))) {
|
|
302
|
+
throw new FactoryError(`${target} exists and is not a Git checkout`);
|
|
303
|
+
}
|
|
304
|
+
const origin = (
|
|
305
|
+
await this.git(["-C", target, "remote", "get-url", "origin"])
|
|
306
|
+
).stdout.trim();
|
|
307
|
+
const there = origin ? parseRemote(origin) : null;
|
|
308
|
+
if (there?.host === remote.host && `${there.owner}/${there.repo}` === remote.identity) {
|
|
309
|
+
return { path: target, existing: true };
|
|
310
|
+
}
|
|
311
|
+
throw new FactoryError(
|
|
312
|
+
`${target} already holds a different repository; remove it or add that one by its folder`,
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
try {
|
|
316
|
+
await this.must(
|
|
317
|
+
this.git(["clone", "--", remote.url, target], {
|
|
318
|
+
remote: remote.url,
|
|
319
|
+
timeoutMs: CLONE_TIMEOUT_MS,
|
|
320
|
+
}),
|
|
321
|
+
`cloning ${remote.identity}`,
|
|
322
|
+
);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
325
|
+
throw error;
|
|
326
|
+
}
|
|
327
|
+
return { path: target, existing: false };
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Whether a remote answers, with the stored token for its URL: `git ls-remote` on its HEAD, as
|
|
333
|
+
* the unprivileged user. A refusal for authentication carries the `auth` code.
|
|
334
|
+
*/
|
|
335
|
+
async checkRemote(url: unknown): Promise<void> {
|
|
336
|
+
const remote = checkedCloneUrl(url);
|
|
337
|
+
await this.must(
|
|
338
|
+
this.git(["ls-remote", "--", remote.url, "HEAD"], {
|
|
339
|
+
remote: remote.url,
|
|
340
|
+
timeoutMs: REMOTE_CHECK_TIMEOUT_MS,
|
|
341
|
+
}),
|
|
342
|
+
`reaching ${remote.identity}`,
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Factory mode is the inner daemon answering with Sysbox registered. */
|
|
347
|
+
async assertAvailable(): Promise<void> {
|
|
348
|
+
if (this.ready) return;
|
|
349
|
+
const socket = this.options.dockerHost.replace(/^unix:\/\//, "");
|
|
350
|
+
if (!this.exists(socket)) {
|
|
351
|
+
throw new FactoryError(
|
|
352
|
+
"the Workset runtime needs factory mode: the inner Docker daemon is not running",
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
const info = await this.docker(["info", "--format", "{{json .Runtimes}}"]);
|
|
356
|
+
if (info.status !== 0) {
|
|
357
|
+
throw new FactoryError(
|
|
358
|
+
`the Workset runtime needs factory mode: the inner Docker daemon does not answer (${info.stderr.trim()})`,
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
if (!info.stdout.includes(`"${SYSBOX_RUNTIME}"`)) {
|
|
362
|
+
throw new FactoryError(
|
|
363
|
+
`the Workset runtime needs factory mode: the inner Docker daemon has no ${SYSBOX_RUNTIME} runtime`,
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
this.ready = true;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** `running`, `paused` (stopped), or null when no container exists. */
|
|
370
|
+
private async containerState(id: string): Promise<"running" | "paused" | null> {
|
|
371
|
+
const inspect = await this.docker([
|
|
372
|
+
"container",
|
|
373
|
+
"inspect",
|
|
374
|
+
"--format",
|
|
375
|
+
"{{.State.Running}}",
|
|
376
|
+
containerName(id),
|
|
377
|
+
]);
|
|
378
|
+
if (inspect.status !== 0) return null;
|
|
379
|
+
return inspect.stdout.trim() === "true" ? "running" : "paused";
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
private assertCompanion(companion: unknown): string {
|
|
383
|
+
if (typeof companion !== "string" || !path.isAbsolute(companion)) {
|
|
384
|
+
throw new FactoryError(`the Session Companion must be an absolute path`);
|
|
385
|
+
}
|
|
386
|
+
let resolved: string;
|
|
387
|
+
let root: string;
|
|
388
|
+
try {
|
|
389
|
+
resolved = this.realpath(companion);
|
|
390
|
+
root = this.realpath(this.options.companionsDir);
|
|
391
|
+
} catch {
|
|
392
|
+
throw new FactoryError(`the Session Companion ${companion} does not exist`);
|
|
393
|
+
}
|
|
394
|
+
if (resolved !== companion || !resolved.startsWith(`${root}${path.sep}`)) {
|
|
395
|
+
throw new FactoryError(
|
|
396
|
+
`the Session Companion ${companion} is not a companion under ${this.options.companionsDir}`,
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
if (!this.exists(path.join(resolved, ".mate", "config", "framework.yaml"))) {
|
|
400
|
+
throw new FactoryError(`${companion} is not a Companion Repository`);
|
|
401
|
+
}
|
|
402
|
+
return resolved;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async spawn(request: SpawnRequest): Promise<WorksetInfo> {
|
|
406
|
+
assertWorksetId(request.id);
|
|
407
|
+
assertRepository(request.repository);
|
|
408
|
+
if (typeof request.remoteUrl !== "string" || request.remoteUrl.startsWith("-")) {
|
|
409
|
+
throw new FactoryError("the Working Repository needs a remote URL");
|
|
410
|
+
}
|
|
411
|
+
if (request.size !== undefined && request.size !== "agent" && request.size !== "build") {
|
|
412
|
+
throw new FactoryError("the memory size must be agent or build");
|
|
413
|
+
}
|
|
414
|
+
const companion = this.assertCompanion(request.companion);
|
|
415
|
+
await this.assertAvailable();
|
|
416
|
+
return this.chains.run(request.id, () => this.spawnNow(request, companion));
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
private async spawnNow(request: SpawnRequest, companion: string): Promise<WorksetInfo> {
|
|
420
|
+
const worktree = this.worktree(request.id);
|
|
421
|
+
const existing = this.exists(path.join(worktree, ".git"));
|
|
422
|
+
const existingBranch = existing
|
|
423
|
+
? await readWorktreeBranch(worktree, (args) => this.git(args))
|
|
424
|
+
: null;
|
|
425
|
+
if (!existing) {
|
|
426
|
+
const resolution = await resolveWorksetBranch(companion, request.id, request.repository);
|
|
427
|
+
if (resolution.id === null) throw new FactoryError(resolution.diagnostics.join("\n"));
|
|
428
|
+
}
|
|
429
|
+
// A refusal for lack of room changes nothing, not even the worktree.
|
|
430
|
+
if ((await this.containerState(request.id)) !== "running")
|
|
431
|
+
await this.makeRoom(request.id, true);
|
|
432
|
+
|
|
433
|
+
const repoDir = this.repoDir(request.repository);
|
|
434
|
+
|
|
435
|
+
if (!this.exists(path.join(repoDir, ".git"))) {
|
|
436
|
+
await this.must(
|
|
437
|
+
this.git(["clone", "--", request.remoteUrl, repoDir], { remote: request.remoteUrl }),
|
|
438
|
+
`cloning ${request.repository}`,
|
|
439
|
+
);
|
|
440
|
+
} else {
|
|
441
|
+
await this.must(
|
|
442
|
+
this.git(["-C", repoDir, "fetch", "--prune", "origin"], { remote: request.remoteUrl }),
|
|
443
|
+
`fetching ${request.repository}`,
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const { branch, warnings } = existingBranch
|
|
448
|
+
? { branch: existingBranch, warnings: [] }
|
|
449
|
+
: await this.createWorktree(request, companion, repoDir, worktree);
|
|
450
|
+
|
|
451
|
+
const size = request.size ?? "build";
|
|
452
|
+
let state = await this.containerState(request.id);
|
|
453
|
+
let migrateHome: string | null = null;
|
|
454
|
+
if (state !== null && (state !== "running" || this.isIdle(request.id))) {
|
|
455
|
+
const stale = await this.staleContainer(request.id);
|
|
456
|
+
if (stale !== null) {
|
|
457
|
+
migrateHome = stale.hasHomeVolume ? null : await this.saveHome(request.id);
|
|
458
|
+
await this.must(
|
|
459
|
+
this.docker(["rm", "--force", containerName(request.id)]),
|
|
460
|
+
`removing ${request.id}'s container from an earlier Workset image`,
|
|
461
|
+
);
|
|
462
|
+
state = null;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
if (state === null) {
|
|
466
|
+
const gitDir = path.join(repoDir, ".git");
|
|
467
|
+
await this.must(
|
|
468
|
+
this.docker([
|
|
469
|
+
"create",
|
|
470
|
+
"--name",
|
|
471
|
+
containerName(request.id),
|
|
472
|
+
"--hostname",
|
|
473
|
+
request.id,
|
|
474
|
+
"--runtime",
|
|
475
|
+
SYSBOX_RUNTIME,
|
|
476
|
+
"--label",
|
|
477
|
+
`${LABEL_WORKSET}=${request.id}`,
|
|
478
|
+
"--label",
|
|
479
|
+
`${LABEL_REPOSITORY}=${request.repository}`,
|
|
480
|
+
...this.limitArgs(size),
|
|
481
|
+
// Identical paths: a worktree's .git file names its gitdir absolutely.
|
|
482
|
+
"--volume",
|
|
483
|
+
`${worktree}:${worktree}`,
|
|
484
|
+
"--volume",
|
|
485
|
+
`${gitDir}:${gitDir}`,
|
|
486
|
+
"--volume",
|
|
487
|
+
`${companion}:${companion}`,
|
|
488
|
+
// Named volumes: Docker seeds an empty one from the image's directory.
|
|
489
|
+
"--volume",
|
|
490
|
+
`${homeVolume(request.id)}:${HOME}`,
|
|
491
|
+
"--volume",
|
|
492
|
+
`${BUN_CACHE_VOLUME}:${BUN_CACHE}`,
|
|
493
|
+
"--workdir",
|
|
494
|
+
worktree,
|
|
495
|
+
this.options.image,
|
|
496
|
+
]),
|
|
497
|
+
`creating the container for ${request.id}`,
|
|
498
|
+
);
|
|
499
|
+
if (migrateHome !== null) await this.restoreHome(request.id, migrateHome);
|
|
500
|
+
}
|
|
501
|
+
if (state === "running") await this.resize(request.id, size);
|
|
502
|
+
else await this.start(request.id, state === "paused", size);
|
|
503
|
+
if (migrateHome !== null) {
|
|
504
|
+
// Copied files keep the uid Sysbox stored them under, which reads as root inside.
|
|
505
|
+
await this.must(
|
|
506
|
+
this.docker([
|
|
507
|
+
"exec",
|
|
508
|
+
containerName(request.id),
|
|
509
|
+
"chown",
|
|
510
|
+
"-R",
|
|
511
|
+
`${this.options.user}:${this.options.user}`,
|
|
512
|
+
HOME,
|
|
513
|
+
]),
|
|
514
|
+
`giving ${request.id}'s moved home back to ${this.options.user}`,
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
this.touch(request.id);
|
|
518
|
+
return {
|
|
519
|
+
id: request.id,
|
|
520
|
+
repository: request.repository,
|
|
521
|
+
branch,
|
|
522
|
+
state: "running",
|
|
523
|
+
...(warnings.length > 0 ? { warnings } : {}),
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Puts a new worktree on the resolved Delivery Branch; call after fetching `repoDir`. The
|
|
529
|
+
* branch is resolved and merges are probed in the factory's clone, as its user.
|
|
530
|
+
*/
|
|
531
|
+
private async createWorktree(
|
|
532
|
+
request: SpawnRequest,
|
|
533
|
+
companion: string,
|
|
534
|
+
repoDir: string,
|
|
535
|
+
worktree: string,
|
|
536
|
+
): Promise<{ branch: string; warnings: string[] }> {
|
|
537
|
+
const checkout = deliveryCheckout(repoDir, async (args, { input, timeoutMs }) => {
|
|
538
|
+
const result = await this.git(["-C", repoDir, ...args], {
|
|
539
|
+
// Only the additions: a whole environment would replace the user's HOME with the broker's.
|
|
540
|
+
env: { GIT_TERMINAL_PROMPT: "0", GIT_NO_LAZY_FETCH: "1" },
|
|
541
|
+
...(input !== undefined ? { stdin: new TextEncoder().encode(input) } : {}),
|
|
542
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
543
|
+
});
|
|
544
|
+
return { code: result.status, stdout: result.stdout, stderr: result.stderr };
|
|
545
|
+
});
|
|
546
|
+
// An invalid template counts as the default; link reports it.
|
|
547
|
+
const resolution = await resolveDeliveryBranch(checkout, {
|
|
548
|
+
companionPath: companion,
|
|
549
|
+
repository: request.repository,
|
|
550
|
+
worksetId: request.id,
|
|
551
|
+
});
|
|
552
|
+
const { branch, source } = resolution;
|
|
553
|
+
if (branch === null || source === null) {
|
|
554
|
+
throw new FactoryError(resolution.diagnostics.join("\n"));
|
|
555
|
+
}
|
|
556
|
+
const base = source === "new" ? await newBranchBase(checkout.hasRef) : undefined;
|
|
557
|
+
await this.must(
|
|
558
|
+
this.git(["-C", repoDir, ...worktreeAddArgs({ branch, source }, worktree, base)]),
|
|
559
|
+
`creating the worktree for ${request.id}`,
|
|
560
|
+
);
|
|
561
|
+
return { branch, warnings: resolution.diagnostics };
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
private memoryOf(size: MemorySize): string | undefined {
|
|
565
|
+
const limits = this.options.limits;
|
|
566
|
+
return size === "agent" ? (limits?.agentMemory ?? limits?.memory) : limits?.memory;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
private limitArgs(size: MemorySize): string[] {
|
|
570
|
+
const limits = this.options.limits;
|
|
571
|
+
if (!limits) return [];
|
|
572
|
+
const memory = this.memoryOf(size)!;
|
|
573
|
+
return [
|
|
574
|
+
"--memory",
|
|
575
|
+
memory,
|
|
576
|
+
// Equal to the memory limit: no swap on top of it.
|
|
577
|
+
"--memory-swap",
|
|
578
|
+
memory,
|
|
579
|
+
"--pids-limit",
|
|
580
|
+
String(limits.pids),
|
|
581
|
+
...(limits.cpus ? ["--cpus", limits.cpus] : []),
|
|
582
|
+
];
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** Starts a stopped container within the running-container cap, at the current limits. */
|
|
586
|
+
private async start(id: string, existing: boolean, size: MemorySize = "build"): Promise<void> {
|
|
587
|
+
await this.exclusive(async () => {
|
|
588
|
+
await this.makeRoom(id);
|
|
589
|
+
if (existing && this.options.limits) {
|
|
590
|
+
await this.must(
|
|
591
|
+
this.docker(["update", ...this.limitArgs(size), containerName(id)]),
|
|
592
|
+
`updating ${id}'s limits`,
|
|
593
|
+
);
|
|
594
|
+
}
|
|
595
|
+
await this.must(this.docker(["start", containerName(id)]), `starting ${id}`);
|
|
596
|
+
});
|
|
597
|
+
this.sizes.set(id, size);
|
|
598
|
+
await this.setSoftMemoryLimit(id, size);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* Brings a running container to the size its next stage needs. It grows at once, and
|
|
603
|
+
* shrinks only while no session or command uses it: lowering the limit under a person's
|
|
604
|
+
* build makes the kernel reclaim, and may kill. A failed update is logged.
|
|
605
|
+
*/
|
|
606
|
+
private async resize(id: string, size: MemorySize): Promise<void> {
|
|
607
|
+
const wanted = this.memoryOf(size);
|
|
608
|
+
if (wanted === undefined) return;
|
|
609
|
+
const current = await this.currentSize(id);
|
|
610
|
+
if (current === size) return;
|
|
611
|
+
const wantedBytes = dockerSizeBytes(wanted);
|
|
612
|
+
const currentBytes = current === null ? null : dockerSizeBytes(this.memoryOf(current)!);
|
|
613
|
+
if (wantedBytes !== null && currentBytes !== null) {
|
|
614
|
+
if (wantedBytes === currentBytes) {
|
|
615
|
+
this.sizes.set(id, size);
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (wantedBytes < currentBytes && !this.isIdle(id)) return;
|
|
619
|
+
}
|
|
620
|
+
const update = await this.docker(["update", ...this.limitArgs(size), containerName(id)]);
|
|
621
|
+
if (update.status !== 0) {
|
|
622
|
+
process.stderr.write(
|
|
623
|
+
`mate factory: Workset ${id} keeps its memory limit: ${(update.stderr || update.stdout).trim()}\n`,
|
|
624
|
+
);
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
this.sizes.set(id, size);
|
|
628
|
+
await this.setSoftMemoryLimit(id, size);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** The running container's size, read from Docker when this broker has not set it. */
|
|
632
|
+
private async currentSize(id: string): Promise<MemorySize | null> {
|
|
633
|
+
const known = this.sizes.get(id);
|
|
634
|
+
if (known) return known;
|
|
635
|
+
const inspect = await this.docker([
|
|
636
|
+
"container",
|
|
637
|
+
"inspect",
|
|
638
|
+
"--format",
|
|
639
|
+
"{{.HostConfig.Memory}}",
|
|
640
|
+
containerName(id),
|
|
641
|
+
]);
|
|
642
|
+
if (inspect.status !== 0) return null;
|
|
643
|
+
const bytes = Number(inspect.stdout.trim());
|
|
644
|
+
for (const size of ["build", "agent"] as const) {
|
|
645
|
+
const memory = this.memoryOf(size);
|
|
646
|
+
if (memory !== undefined && dockerSizeBytes(memory) === bytes) {
|
|
647
|
+
this.sizes.set(id, size);
|
|
648
|
+
return size;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
return null;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Sets `memory.high` below the hard limit, so the kernel reclaims and
|
|
656
|
+
* throttles before it kills. Docker sets none, and the cgroup is new on each
|
|
657
|
+
* start. A failure is logged; the container runs without it.
|
|
658
|
+
*/
|
|
659
|
+
private async setSoftMemoryLimit(id: string, size: MemorySize): Promise<void> {
|
|
660
|
+
const memory = this.memoryOf(size);
|
|
661
|
+
if (memory === undefined) return;
|
|
662
|
+
try {
|
|
663
|
+
const bytes = dockerSizeBytes(memory);
|
|
664
|
+
if (bytes === null) throw new Error(`${memory} is not a Docker size`);
|
|
665
|
+
const inspect = await this.must(
|
|
666
|
+
this.docker(["container", "inspect", "--format", "{{.Id}}", containerName(id)]),
|
|
667
|
+
`reading ${id}'s container id`,
|
|
668
|
+
);
|
|
669
|
+
this.writeFile(
|
|
670
|
+
path.join(this.cgroupRoot, "docker", inspect.stdout.trim(), "memory.high"),
|
|
671
|
+
String(Math.floor(bytes * SOFT_MEMORY_SHARE)),
|
|
672
|
+
);
|
|
673
|
+
} catch (error) {
|
|
674
|
+
process.stderr.write(
|
|
675
|
+
`mate factory: Workset ${id} runs without a soft memory limit: ${(error as Error).message}\n`,
|
|
676
|
+
);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** Workset ids of the running containers. */
|
|
681
|
+
private async runningIds(): Promise<string[]> {
|
|
682
|
+
const ps = await this.must(
|
|
683
|
+
this.docker([
|
|
684
|
+
"ps",
|
|
685
|
+
"--filter",
|
|
686
|
+
`label=${LABEL_WORKSET}`,
|
|
687
|
+
"--filter",
|
|
688
|
+
"status=running",
|
|
689
|
+
"--format",
|
|
690
|
+
`{{.Label "${LABEL_WORKSET}"}}`,
|
|
691
|
+
]),
|
|
692
|
+
"listing running Workset containers",
|
|
693
|
+
);
|
|
694
|
+
return ps.stdout
|
|
695
|
+
.split("\n")
|
|
696
|
+
.map((line) => line.trim())
|
|
697
|
+
.filter(Boolean);
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Stops the least recently active idle containers until `id` fits under the
|
|
702
|
+
* cap; `check` only refuses when it could not, stopping nothing. Runs under the
|
|
703
|
+
* capacity lock, so a container with an operation pending is never waited on: that
|
|
704
|
+
* operation may itself wait for the lock.
|
|
705
|
+
*/
|
|
706
|
+
private async makeRoom(id: string, check = false): Promise<void> {
|
|
707
|
+
const cap = this.options.maxWorksets;
|
|
708
|
+
if (cap === undefined) return;
|
|
709
|
+
const others = (await this.runningIds()).filter((other) => other !== id);
|
|
710
|
+
const excess = others.length - cap + 1;
|
|
711
|
+
if (excess <= 0) return;
|
|
712
|
+
const idle = others
|
|
713
|
+
.filter(
|
|
714
|
+
(other) =>
|
|
715
|
+
this.isIdle(other) &&
|
|
716
|
+
!this.chains.has(other) &&
|
|
717
|
+
this.now() - this.activityOf(other).lastActivity >= ROOM_GRACE_MS,
|
|
718
|
+
)
|
|
719
|
+
.toSorted((a, b) => this.activityOf(a).lastActivity - this.activityOf(b).lastActivity);
|
|
720
|
+
if (idle.length < excess) {
|
|
721
|
+
throw new FactoryError(
|
|
722
|
+
`all ${others.length - idle.length} running Workset containers are busy; at most ${cap} run at once (MATE_FACTORY_MAX_WORKSETS)`,
|
|
723
|
+
"busy",
|
|
724
|
+
);
|
|
725
|
+
}
|
|
726
|
+
if (check) return;
|
|
727
|
+
for (const other of idle.slice(0, excess)) {
|
|
728
|
+
// oxlint-disable-next-line no-await-in-loop -- stopped one by one, oldest first
|
|
729
|
+
await this.chains.run(other, () => this.stopNow(other, "making room for another Workset"));
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Prunes the nested daemon's dangling images and build cache, then stops the
|
|
735
|
+
* container. The prune skips a daemon that never started rather than start it.
|
|
736
|
+
*/
|
|
737
|
+
private async stopNow(id: string, why: string): Promise<boolean> {
|
|
738
|
+
if (!this.isIdle(id) || (await this.containerState(id)) !== "running") return false;
|
|
739
|
+
await this.docker(["exec", containerName(id), "mate-workset-prune"]);
|
|
740
|
+
if (!this.isIdle(id)) return false;
|
|
741
|
+
await this.must(
|
|
742
|
+
this.docker(["stop", "--time", STOP_SECONDS, containerName(id)]),
|
|
743
|
+
`stopping ${id} (${why})`,
|
|
744
|
+
);
|
|
745
|
+
return true;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* Stops every running container idle for the configured minutes; returns the
|
|
750
|
+
* Workset ids it stopped. The broker calls it once a minute.
|
|
751
|
+
*/
|
|
752
|
+
async sweepIdle(): Promise<string[]> {
|
|
753
|
+
const minutes = this.options.idleMinutes ?? 0;
|
|
754
|
+
if (minutes <= 0) return [];
|
|
755
|
+
await this.assertAvailable();
|
|
756
|
+
const cutoff = this.now() - minutes * 60_000;
|
|
757
|
+
const stopped: string[] = [];
|
|
758
|
+
for (const id of await this.runningIds()) {
|
|
759
|
+
if (!this.isIdle(id) || this.activityOf(id).lastActivity > cutoff) continue;
|
|
760
|
+
// oxlint-disable-next-line no-await-in-loop -- one stop at a time keeps the daemon calm
|
|
761
|
+
const done = await this.chains.run(id, async () => {
|
|
762
|
+
if (this.activityOf(id).lastActivity > cutoff) return false;
|
|
763
|
+
return this.stopNow(id, "idle");
|
|
764
|
+
});
|
|
765
|
+
if (done) stopped.push(id);
|
|
766
|
+
}
|
|
767
|
+
return stopped;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** A container made from another image than the current one, and whether it mounts its home volume. */
|
|
771
|
+
private async staleContainer(id: string): Promise<{ hasHomeVolume: boolean } | null> {
|
|
772
|
+
const container = await this.must(
|
|
773
|
+
this.docker([
|
|
774
|
+
"container",
|
|
775
|
+
"inspect",
|
|
776
|
+
"--format",
|
|
777
|
+
"{{.Image}}\t{{range .Mounts}}{{.Name}} {{end}}",
|
|
778
|
+
containerName(id),
|
|
779
|
+
]),
|
|
780
|
+
`reading ${id}'s container`,
|
|
781
|
+
);
|
|
782
|
+
const image = await this.must(
|
|
783
|
+
this.docker(["image", "inspect", "--format", "{{.Id}}", this.options.image]),
|
|
784
|
+
`reading the Workset image ${this.options.image}`,
|
|
785
|
+
);
|
|
786
|
+
const [imageId = "", mounts = ""] = container.stdout.trim().split("\t");
|
|
787
|
+
if (imageId === image.stdout.trim()) return null;
|
|
788
|
+
return { hasHomeVolume: mounts.split(/\s+/).includes(homeVolume(id)) };
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
private homeStage(id: string): string {
|
|
792
|
+
return path.join(this.options.stateDir, "home-migration", id);
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/** Copies a pre-volume container's home out of it, with ownership kept. */
|
|
796
|
+
private async saveHome(id: string): Promise<string> {
|
|
797
|
+
const stage = this.homeStage(id);
|
|
798
|
+
fs.rmSync(stage, { recursive: true, force: true });
|
|
799
|
+
fs.mkdirSync(stage, { recursive: true });
|
|
800
|
+
await this.must(
|
|
801
|
+
this.docker(["cp", "--archive", `${containerName(id)}:${HOME}`, stage]),
|
|
802
|
+
`saving ${id}'s home`,
|
|
803
|
+
);
|
|
804
|
+
return path.join(stage, path.basename(HOME));
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
private async restoreHome(id: string, saved: string): Promise<void> {
|
|
808
|
+
await this.must(
|
|
809
|
+
this.docker(["cp", "--archive", `${saved}/.`, `${containerName(id)}:${HOME}`]),
|
|
810
|
+
`moving ${id}'s home to its volume`,
|
|
811
|
+
);
|
|
812
|
+
fs.rmSync(this.homeStage(id), { recursive: true, force: true });
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
async pause(id: string): Promise<void> {
|
|
816
|
+
assertWorksetId(id);
|
|
817
|
+
await this.assertAvailable();
|
|
818
|
+
await this.chains.run(id, async () => {
|
|
819
|
+
const state = await this.containerState(id);
|
|
820
|
+
if (state === null) throw new FactoryError(`Workset ${id} has no container`);
|
|
821
|
+
if (state === "running") {
|
|
822
|
+
await this.must(
|
|
823
|
+
this.docker(["stop", "--time", STOP_SECONDS, containerName(id)]),
|
|
824
|
+
`pausing ${id}`,
|
|
825
|
+
);
|
|
826
|
+
}
|
|
827
|
+
});
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
async resume(id: string): Promise<void> {
|
|
831
|
+
assertWorksetId(id);
|
|
832
|
+
await this.assertAvailable();
|
|
833
|
+
await this.chains.run(id, async () => {
|
|
834
|
+
const state = await this.containerState(id);
|
|
835
|
+
if (state === null) throw new FactoryError(`Workset ${id} has no container; spawn it`);
|
|
836
|
+
if (state === "paused") await this.start(id, true);
|
|
837
|
+
this.touch(id);
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
async exec(request: ExecRequest, credential?: AgentCredential): Promise<CommandResult> {
|
|
842
|
+
assertWorksetId(request.id);
|
|
843
|
+
assertCommand(request.command, "exec");
|
|
844
|
+
const worktree = this.worktree(request.id);
|
|
845
|
+
const cwd = path.resolve(worktree, request.cwd ?? ".");
|
|
846
|
+
if (cwd !== worktree && !cwd.startsWith(`${worktree}${path.sep}`)) {
|
|
847
|
+
throw new FactoryError(`exec's working directory ${request.cwd} is outside the worktree`);
|
|
848
|
+
}
|
|
849
|
+
// Counted before waiting, so an idle stop queued meanwhile sees it busy.
|
|
850
|
+
const done = this.track(request.id, "commands");
|
|
851
|
+
try {
|
|
852
|
+
await this.chains.settled(request.id);
|
|
853
|
+
await this.assertStarted(request.id);
|
|
854
|
+
// `-e NAME` takes the value from the docker client's environment, so no
|
|
855
|
+
// value appears in an argument list or in the container's configuration.
|
|
856
|
+
return await this.run(
|
|
857
|
+
"docker",
|
|
858
|
+
[
|
|
859
|
+
"exec",
|
|
860
|
+
...(request.stdin ? ["--interactive"] : []),
|
|
861
|
+
"--user",
|
|
862
|
+
this.options.user,
|
|
863
|
+
"--workdir",
|
|
864
|
+
cwd,
|
|
865
|
+
...(credential ? ["--env", credential.name] : []),
|
|
866
|
+
containerName(request.id),
|
|
867
|
+
...request.command,
|
|
868
|
+
],
|
|
869
|
+
{
|
|
870
|
+
env: {
|
|
871
|
+
...(credential ? { [credential.name]: credential.value } : {}),
|
|
872
|
+
...this.dockerEnv(),
|
|
873
|
+
},
|
|
874
|
+
...(request.stdin ? { stdin: request.stdin } : {}),
|
|
875
|
+
},
|
|
876
|
+
);
|
|
877
|
+
} finally {
|
|
878
|
+
done();
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/** Available, with the Workset's container created and not paused. */
|
|
883
|
+
private async assertStarted(id: string): Promise<void> {
|
|
884
|
+
await this.assertAvailable();
|
|
885
|
+
const state = await this.containerState(id);
|
|
886
|
+
if (state === null) throw new FactoryError(`Workset ${id} has no container`);
|
|
887
|
+
if (state === "paused") {
|
|
888
|
+
throw new FactoryError(`Workset ${id} is paused; resume it first`);
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/** The Workset container's address on the inner Docker network, reachable from the appliance. */
|
|
893
|
+
async address(id: string): Promise<string> {
|
|
894
|
+
assertWorksetId(id);
|
|
895
|
+
await this.assertAvailable();
|
|
896
|
+
if ((await this.containerState(id)) !== "running") {
|
|
897
|
+
throw new FactoryError(`Workset ${id} is not running`);
|
|
898
|
+
}
|
|
899
|
+
const inspect = await this.must(
|
|
900
|
+
this.docker([
|
|
901
|
+
"container",
|
|
902
|
+
"inspect",
|
|
903
|
+
"--format",
|
|
904
|
+
"{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}",
|
|
905
|
+
containerName(id),
|
|
906
|
+
]),
|
|
907
|
+
`reading ${id}'s address`,
|
|
908
|
+
);
|
|
909
|
+
const address = inspect.stdout.trim().split(/\s+/).find(Boolean);
|
|
910
|
+
if (!address) throw new FactoryError(`Workset ${id} has no network address`);
|
|
911
|
+
return address;
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
/** The environment a `docker` client needs to reach the inner daemon. */
|
|
915
|
+
dockerEnv(): Record<string, string> {
|
|
916
|
+
return { DOCKER_HOST: this.options.dockerHost };
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/**
|
|
920
|
+
* The interactive `docker exec` for an attach, run by the broker in its own PTY. Values
|
|
921
|
+
* of `envNames` and the session marker come from that client's environment, never argv.
|
|
922
|
+
*/
|
|
923
|
+
async attachCommand(request: {
|
|
924
|
+
id: string;
|
|
925
|
+
command: string[];
|
|
926
|
+
session: string;
|
|
927
|
+
envNames: string[];
|
|
928
|
+
/** False for a long-running process without a terminal, such as the harness bridge. */
|
|
929
|
+
tty?: boolean;
|
|
930
|
+
}): Promise<string[]> {
|
|
931
|
+
assertWorksetId(request.id);
|
|
932
|
+
assertSessionMarker(request.session);
|
|
933
|
+
assertCommand(request.command, "attach");
|
|
934
|
+
await this.assertStarted(request.id);
|
|
935
|
+
return [
|
|
936
|
+
"docker",
|
|
937
|
+
"exec",
|
|
938
|
+
"--interactive",
|
|
939
|
+
...(request.tty === false ? [] : ["--tty"]),
|
|
940
|
+
"--user",
|
|
941
|
+
this.options.user,
|
|
942
|
+
"--workdir",
|
|
943
|
+
this.worktree(request.id),
|
|
944
|
+
"--env",
|
|
945
|
+
SESSION_MARKER,
|
|
946
|
+
...request.envNames.flatMap((name) => ["--env", name]),
|
|
947
|
+
containerName(request.id),
|
|
948
|
+
...request.command,
|
|
949
|
+
];
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/**
|
|
953
|
+
* Stops every process inside the container that carries the session marker — the agent
|
|
954
|
+
* and everything it started — leaving the container and its `dockerd` running.
|
|
955
|
+
*/
|
|
956
|
+
async stopMarked(id: string, session: string): Promise<void> {
|
|
957
|
+
assertWorksetId(id);
|
|
958
|
+
assertSessionMarker(session);
|
|
959
|
+
if ((await this.containerState(id)) !== "running") return;
|
|
960
|
+
await this.docker(["exec", containerName(id), "mate-workset-stop", session]);
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
async list(): Promise<WorksetInfo[]> {
|
|
964
|
+
await this.assertAvailable();
|
|
965
|
+
const ps = await this.must(
|
|
966
|
+
this.docker([
|
|
967
|
+
"ps",
|
|
968
|
+
"--all",
|
|
969
|
+
"--filter",
|
|
970
|
+
`label=${LABEL_WORKSET}`,
|
|
971
|
+
"--format",
|
|
972
|
+
`{{.Label "${LABEL_WORKSET}"}}\t{{.Label "${LABEL_REPOSITORY}"}}\t{{.State}}`,
|
|
973
|
+
]),
|
|
974
|
+
"listing Workset containers",
|
|
975
|
+
);
|
|
976
|
+
const worksets = new Map<string, WorksetInfo>();
|
|
977
|
+
for (const line of ps.stdout.split("\n")) {
|
|
978
|
+
const [id, repository, state] = line.split("\t");
|
|
979
|
+
if (!id) continue;
|
|
980
|
+
worksets.set(id, {
|
|
981
|
+
id,
|
|
982
|
+
repository: repository || null,
|
|
983
|
+
branch: deliveryBranch(id),
|
|
984
|
+
state: state === "running" ? "running" : "paused",
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
for (const id of this.listDir(path.join(this.options.stateDir, "worktrees"))) {
|
|
988
|
+
if (worksets.has(id)) continue;
|
|
989
|
+
worksets.set(id, {
|
|
990
|
+
id,
|
|
991
|
+
repository: this.worktreeRepository(id),
|
|
992
|
+
branch: deliveryBranch(id),
|
|
993
|
+
state: "missing",
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
return Promise.all(
|
|
997
|
+
[...worksets.values()]
|
|
998
|
+
.toSorted((a, b) => a.id.localeCompare(b.id))
|
|
999
|
+
.map(async (info) => {
|
|
1000
|
+
const worktree = this.worktree(info.id);
|
|
1001
|
+
return {
|
|
1002
|
+
...info,
|
|
1003
|
+
branch: this.exists(path.join(worktree, ".git"))
|
|
1004
|
+
? await readWorktreeBranch(worktree, (args) => this.git(args))
|
|
1005
|
+
: info.branch,
|
|
1006
|
+
};
|
|
1007
|
+
}),
|
|
1008
|
+
);
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
/** The repository a worktree belongs to, from the clone its `.git` file points into. */
|
|
1012
|
+
private worktreeRepository(id: string): string | null {
|
|
1013
|
+
try {
|
|
1014
|
+
const pointer = fs.readFileSync(path.join(this.worktree(id), ".git"), "utf8");
|
|
1015
|
+
const key = /repos\/([^/]+)\/\.git\/worktrees\//.exec(pointer)?.[1];
|
|
1016
|
+
return key ? repositoryFromKey(key) : null;
|
|
1017
|
+
} catch {
|
|
1018
|
+
return null;
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
async delete(id: string, options: { force?: boolean } = {}): Promise<void> {
|
|
1023
|
+
assertWorksetId(id);
|
|
1024
|
+
await this.assertAvailable();
|
|
1025
|
+
await this.chains.run(id, () => this.deleteNow(id, options));
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
private async deleteNow(id: string, options: { force?: boolean }): Promise<void> {
|
|
1029
|
+
const worktree = this.worktree(id);
|
|
1030
|
+
const hasWorktree = this.exists(path.join(worktree, ".git"));
|
|
1031
|
+
|
|
1032
|
+
if (hasWorktree && !options.force) {
|
|
1033
|
+
const status = await this.must(
|
|
1034
|
+
this.git(["-C", worktree, "status", "--porcelain"]),
|
|
1035
|
+
`reading ${id}'s worktree`,
|
|
1036
|
+
);
|
|
1037
|
+
const unpushed = await this.must(
|
|
1038
|
+
this.git(["-C", worktree, "log", "--format=%h %s", "HEAD", "--not", "--remotes=origin"]),
|
|
1039
|
+
`reading ${id}'s unpushed commits`,
|
|
1040
|
+
);
|
|
1041
|
+
const commits = unpushed.stdout.split("\n").filter((line) => line.trim() !== "");
|
|
1042
|
+
const named = commits.slice(0, 3).join("; ") + (commits.length > 3 ? "; …" : "");
|
|
1043
|
+
const problems = [
|
|
1044
|
+
status.stdout.trim() !== "" ? "uncommitted changes" : null,
|
|
1045
|
+
commits.length > 0 ? `${commits.length} unpushed commit(s) (${named})` : null,
|
|
1046
|
+
].filter(Boolean);
|
|
1047
|
+
if (problems.length > 0) {
|
|
1048
|
+
throw new FactoryError(
|
|
1049
|
+
`Workset ${id} has ${problems.join(" and ")}; push them or delete with force`,
|
|
1050
|
+
);
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
if ((await this.containerState(id)) !== null) {
|
|
1055
|
+
await this.must(
|
|
1056
|
+
this.docker(["rm", "--force", containerName(id)]),
|
|
1057
|
+
`removing ${id}'s container`,
|
|
1058
|
+
);
|
|
1059
|
+
}
|
|
1060
|
+
if (hasWorktree) {
|
|
1061
|
+
const repoDir = path.dirname(
|
|
1062
|
+
path.dirname(
|
|
1063
|
+
path.dirname(
|
|
1064
|
+
fs
|
|
1065
|
+
.readFileSync(path.join(worktree, ".git"), "utf8")
|
|
1066
|
+
.replace(/^gitdir:\s*/, "")
|
|
1067
|
+
.trim(),
|
|
1068
|
+
),
|
|
1069
|
+
),
|
|
1070
|
+
);
|
|
1071
|
+
// The local and remote branches stay: only the checkout and its container go.
|
|
1072
|
+
await this.must(
|
|
1073
|
+
this.git(["-C", repoDir, "worktree", "remove", "--force", worktree]),
|
|
1074
|
+
`removing ${id}'s worktree`,
|
|
1075
|
+
);
|
|
1076
|
+
}
|
|
1077
|
+
// Missing for a Workset whose container never ran with it.
|
|
1078
|
+
await this.docker(["volume", "rm", "--force", homeVolume(id)]);
|
|
1079
|
+
this.activity.delete(id);
|
|
1080
|
+
}
|
|
1081
|
+
}
|