Compare commits

..
16 changed files with 1768 additions and 24 deletions

No files matched your search

+50
View File
@@ -3,6 +3,56 @@
All notable changes to CodeCraft. Versions follow [Semantic Versioning](https://semver.org/);
until 1.0, minor versions may contain breaking changes.
## [v202611-00049] – 2026-11-16
### Added
- **Factory versions and tags.** Every merged factory issue (merged through the factory or on the forge)
gets a version: the patch number goes up with each issue (0.1.0 → 0.1.1); the issue that completes a
milestone (the last open `M1.x` issue) raises the minor number and restarts the patch (0.0.7 → 0.1.0).
The factory commits a `VERSION` file on the default branch, tags the commit `vX.Y.Z`, closes the issue
and notes the version in it. The version shows on the repository tile. Versioning starts with the next
merged issue; issues that were done before are not counted.
- **Factory release (0.x → 1.0.0 and on).** The new "Release" button makes a release you choose the
version of: `VERSION`, tag, the Docker image for amd64 and arm64 (buildx, pushed to the registry of the
image name), the source zip and further files, and the release on the forge (Gitea and GitHub attach the
files; GitLab gets the release without attachments). How to build is described in
`.factory/release.json` in the repository (`image`, `platforms`, `dockerfile`, `context`,
`build_args`, `commands`, `files`, `name`); without it only tag, release and source zip are made. The
dialog shows the recipe first, because its commands run on the server outside the sandbox.
- The image now contains the buildx plugin.
- **The factory's checkout of the default branch is pulled** (fast-forward) after every fetch, and right after
a merge is detected and the version commit is pushed – before, the review read the files of the first clone.
Local changes or a diverged branch are left alone with a warning.
- **Settings for repetitions** per repository: *Rework rounds* (how often a failed acceptance sends the
issue back to the build, default 2, 0 = never) and *Tries* per phase (how often a phase is repeated after
a technical failure such as a timeout, default 2).
## [v202611-00048] – 2026-11-16
### Fixed
- The factory page showed a blank page since v202611-00047 (the new pull request panel declared its state
after an early return, which breaks React's hook order). The hooks now sit above the early returns.
## [v202611-00047] – 2026-11-16
### Added
- **Factory: show and approve pull requests.** Selecting an issue shows its open pull request (state,
conflicts, files, +/− lines, link) with "Approve and merge" (merge commit, squash or rebase). Merging only
happens on your click after a confirmation; the factory itself still never merges.
- **Factory: plan with a model and file the issues.** "Plan a feature" starts a chat that works out a new
feature with you; "Cut a milestone" lets a model cut a milestone of the spec into numbered deliverables
("M2.1 – …"). The chat reads the repository and ends with an issue list; a dialog lets you tick and edit
the issues, which are then created on the forge with `Spec:` and `Scope:` lines and the prerequisites.
They get the factory label only if you ask for it, so you can start them one after the other.
### Fixed
- An accepted rework build now gets a new pull request when the earlier one was merged or closed already;
before, the commits of the rework rounds stayed on the branch without any pull request.
## [v202611-00046] – 2026-11-16
### Changed
+5
View File
@@ -74,6 +74,10 @@ ARG DOCKER_VERSION=29.9.3
RUN case "$TARGETARCH" in amd64) arch=x86_64 ;; arm64) arch=aarch64 ;; *) echo "unsupported $TARGETARCH" >&2; exit 1 ;; esac \
&& curl -fsSL "https://download.docker.com/linux/static/stable/$arch/docker-$DOCKER_VERSION.tgz" | tar -xz -C /tmp docker/docker \
&& install -m 0755 /tmp/docker/docker /docker
# buildx plugin: the factory builds multi-arch release images with it (own builder on the host daemon).
ARG BUILDX_VERSION=v0.19.3
RUN curl -fsSL -o /docker-buildx "https://github.com/docker/buildx/releases/download/${BUILDX_VERSION}/buildx-${BUILDX_VERSION}.linux-${TARGETARCH}" \
&& chmod 0755 /docker-buildx
# --- runtime ------------------------------------------------------------------
# Node is included so agents can work on JS projects and run npx-based MCP servers.
@@ -95,6 +99,7 @@ COPY --from=web /web/dist /app/web
COPY --from=cli /out /app/cli
# Used with a mounted /var/run/docker.sock (see docs/MOVING.md, --docker-sock).
COPY --from=dockercli /docker /usr/local/bin/docker
COPY --from=dockercli /docker-buildx /usr/local/lib/docker/cli-plugins/docker-buildx
COPY server/ghidra /app/ghidra
# git for agent shells: commits get the co-author trailer of the model (server.commit_trailer).
COPY --chmod=755 docker/git-coauthor /usr/local/lib/codecraft/bin/git
+1 -1
View File
@@ -11,7 +11,7 @@
</p>
<p align="center">
<img alt="Version v202611-00046" src="https://img.shields.io/badge/version-v202611--00046-d69e2e?style=flat-square">
<img alt="Version v202611-00049" src="https://img.shields.io/badge/version-v202611--00049-d69e2e?style=flat-square">
<img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-689d6a?style=flat-square">
<img alt="Rust backend" src="https://img.shields.io/badge/backend-Rust-b7410e?style=flat-square&logo=rust">
<img alt="React PWA" src="https://img.shields.io/badge/frontend-React%20PWA-2d81ff?style=flat-square&logo=react">
+157 -1
View File
@@ -164,6 +164,13 @@ pub fn router(app: AppState) -> Router {
.route("/factory/overview", get(factory_overview))
.route("/factory/poll", post(factory_poll))
.route("/factory/issues/restart", post(factory_restart))
.route("/factory/issue-chats", post(factory_new_issue_chat))
.route("/factory/issue-chats/{id}", get(factory_issue_chat))
.route("/factory/issue-chats/{id}/create", post(factory_create_issues))
.route("/factory/release/preview", get(factory_release_preview))
.route("/factory/release", post(factory_release))
.route("/factory/issues/pr", get(factory_pr))
.route("/factory/issues/pr/merge", post(factory_pr_merge))
.route("/account/factory/connection/test", post(test_factory_connection))
.route("/factory/drafts", post(factory_new_draft))
.route("/factory/drafts/{id}", get(factory_draft))
@@ -2632,12 +2639,13 @@ async fn test_factory(Extension(user): Extension<User>, State(app): State<AppSta
/// Everything the factory page shows: repositories, issues with state, runs with tokens/cost.
async fn factory_overview(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
let repos: Vec<Value> = s.repos.iter().map(|r| json!({"url": r.url, "enabled": r.enabled, "label": r.label, "max_parallel": r.max_parallel, "kind": s.resolve(r).kind, "has_token": !s.resolve(r).token.is_empty(), "models": {"review": r.review.model, "build": r.build.model, "qa": r.qa.model}, "running": app.store.factory_running(&r.url).unwrap_or(0)})).collect();
let repos: Vec<Value> = s.repos.iter().map(|r| json!({"url": r.url, "enabled": r.enabled, "label": r.label, "max_parallel": r.max_parallel, "kind": s.resolve(r).kind, "has_token": !s.resolve(r).token.is_empty(), "models": {"review": r.review.model, "build": r.build.model, "qa": r.qa.model}, "running": app.store.factory_running(&r.url).unwrap_or(0), "version": app.store.factory_version(&r.url).ok().flatten()})).collect();
Ok(Json(json!({
"area": app.factory_dir().is_some(),
"repos": repos,
"issues": app.store.factory_issues(&user.id)?,
"runs": app.store.factory_runs(&user.id, None, None, 300)?,
"releases": app.store.factory_releases(&user.id, 10)?,
})))
}
@@ -2653,6 +2661,154 @@ async fn factory_poll(Extension(user): Extension<User>, State(app): State<AppSta
Ok(Json(json!({"errors": errors})))
}
#[derive(Deserialize)]
struct ReleaseQuery {
repo: String,
}
/// Current version, suggested next major version and the release recipe (.factory/release.json).
async fn factory_release_preview(Extension(user): Extension<User>, State(app): State<AppState>, Query(q): Query<ReleaseQuery>) -> ApiResult {
let cfg = factory_repo_cfg(&app, &user, &q.repo)?;
let v = crate::factory_version::preview(&app, &user, &cfg).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
Ok(Json(v))
}
#[derive(Deserialize)]
struct StartRelease {
repo: String,
version: String,
}
/// Start a release: tag, Docker image, downloads and the release on the forge (runs in the background).
async fn factory_release(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<StartRelease>) -> ApiResult {
let cfg = factory_repo_cfg(&app, &user, &b.repo)?;
let id = crate::factory_version::start_release(&app, &user, &cfg, b.version.trim()).await.map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
app.audit(Some(&user), "factory.release.start", &format!("{} {}", b.repo, b.version.trim()), &crate::auth::client_ip(&headers));
Ok(Json(json!({"id": id})))
}
#[derive(Deserialize)]
struct NewIssueChat {
repo: String,
/// "feature" or "slice"
mode: String,
#[serde(default)]
topic: String,
#[serde(default)]
model: Option<String>,
}
fn factory_repo_cfg(app: &AppState, user: &User, repo: &str) -> Result<crate::factory::RepoCfg, ApiError> {
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
s.repos.iter().find(|r| r.url == repo).map(|r| s.resolve(r)).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "the repository is not configured".into()))
}
/// Start a chat that works out a feature or cuts a milestone into issues.
async fn factory_new_issue_chat(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<NewIssueChat>) -> ApiResult {
if !["feature", "slice"].contains(&b.mode.as_str()) {
return Err(ApiError(StatusCode::BAD_REQUEST, "unknown mode".into()));
}
let cfg = factory_repo_cfg(&app, &user, &b.repo)?;
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
let model = b.model.filter(|m| !m.is_empty()).unwrap_or(s.defaults.spec_model.clone());
let session = crate::factory::start_issue_chat(&app, &user, &cfg, &model, &b.mode, &b.topic).await.map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
Ok(Json(json!(session)))
}
fn issue_chat_session(app: &AppState, user: &User, id: &str) -> Result<(String, std::path::PathBuf), ApiError> {
let session = app.session(id).map_err(|_| ApiError(StatusCode::NOT_FOUND, "unknown chat".into()))?;
let dir = crate::factory::issue_chat_of(app, user, &session).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "not an issue chat".into()))?;
let repo = std::fs::read_to_string(dir.join("repo.txt")).unwrap_or_default().trim().to_string();
Ok((repo, dir))
}
/// The issue list the model proposed in its last message.
async fn factory_issue_chat(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>) -> ApiResult {
let (repo, _) = issue_chat_session(&app, &user, &id)?;
Ok(Json(json!({"repo": repo, "proposal": crate::factory::issue_proposal(&app, &id)})))
}
#[derive(Deserialize)]
struct CreateIssues {
spec: String,
issues: Vec<Value>,
/// Give the issues the factory label so the workflow starts right away.
#[serde(default)]
start: bool,
}
/// Create the (possibly edited) issues of a proposal on the forge.
async fn factory_create_issues(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Path(id): Path<String>, Json(b): Json<CreateIssues>) -> ApiResult {
let (repo, _) = issue_chat_session(&app, &user, &id)?;
let cfg = factory_repo_cfg(&app, &user, &repo)?;
if b.issues.is_empty() || b.issues.len() > 100 {
return Err(ApiError(StatusCode::BAD_REQUEST, "choose between 1 and 100 issues".into()));
}
let created = crate::factory::create_issues(&cfg, &b.spec, &b.issues, b.start).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
app.audit(Some(&user), "factory.issues.create", &format!("{repo} ({} issues)", created.len()), &crate::auth::client_ip(&headers));
if b.start {
let _ = crate::factory::poll_repo(&app, &user, &cfg).await;
}
Ok(Json(json!({"created": created})))
}
#[derive(Deserialize)]
struct PrQuery {
repo: String,
number: i64,
}
/// The issue's forge client and row; the issue must belong to the user.
fn factory_issue_forge(app: &AppState, user: &User, repo: &str, number: i64) -> Result<(crate::factory::Forge, Value), ApiError> {
let row = app.store.factory_issue(repo, number)?.filter(|r| r["owner_id"].as_str() == Some(user.id.as_str())).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "unknown issue".into()))?;
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
let cfg = s.repos.iter().find(|r| r.url == repo).map(|r| s.resolve(r)).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "the repository is not configured".into()))?;
let g = crate::factory::Forge::new(&cfg).map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
Ok((g, row))
}
/// The pull request of an issue: the open one from its branch, else the one on record.
async fn factory_pr(Extension(user): Extension<User>, State(app): State<AppState>, Query(q): Query<PrQuery>) -> ApiResult {
let (g, row) = factory_issue_forge(&app, &user, &q.repo, q.number)?;
let bad = |e: anyhow::Error| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}"));
let branch = row["branch"].as_str().unwrap_or("");
let mut pr = if branch.is_empty() { None } else { g.find_pr(branch).await.map_err(bad)? };
if pr.is_none() {
let n: u64 = row["pr_url"].as_str().unwrap_or("").trim_end_matches('/').rsplit('/').next().and_then(|n| n.parse().ok()).unwrap_or(0);
if n > 0 {
pr = g.pr(n).await.ok();
}
}
Ok(Json(json!({"pr": pr})))
}
#[derive(Deserialize)]
struct MergePr {
repo: String,
number: i64,
pr: u64,
#[serde(default)]
method: String,
}
/// Merge the pull request of an issue – only on the user's own click in the factory page.
async fn factory_pr_merge(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<MergePr>) -> ApiResult {
let (g, row) = factory_issue_forge(&app, &user, &b.repo, b.number)?;
let method = if b.method.is_empty() { "merge" } else { b.method.as_str() };
if !["merge", "squash", "rebase"].contains(&method) {
return Err(ApiError(StatusCode::BAD_REQUEST, "unknown merge method".into()));
}
let pr = g.pr(b.pr).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
// Only the pull request of this issue's own branch may be merged from here.
if pr["head"].as_str() != row["branch"].as_str() || pr["state"].as_str() != Some("open") {
return Err(ApiError(StatusCode::BAD_REQUEST, "this is not the open pull request of the issue".into()));
}
g.merge_pr(b.pr, method).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
app.store.factory_issue_set(&b.repo, b.number, &[("pr_url", json!(pr["html_url"].as_str().unwrap_or("")))])?;
app.audit(Some(&user), "factory.pr.merge", &format!("{}#{}", b.repo, b.number), &crate::auth::client_ip(&headers));
Ok(Json(json!({"ok": true})))
}
#[derive(Deserialize)]
struct RestartIssue {
repo: String,
+323 -14
View File
@@ -43,6 +43,9 @@ pub struct PhaseCfg {
pub permission_mode: String,
#[serde(default = "default_timeout")]
pub timeout_minutes: u64,
/// Tries of this phase when it fails technically (timeout, no result, no changes) before the issue is `failed`.
#[serde(default = "default_attempts")]
pub max_attempts: i64,
/// Extra instructions appended to the phase prompt.
#[serde(default)]
pub extra_prompt: String,
@@ -57,10 +60,16 @@ fn default_mode() -> String {
fn default_timeout() -> u64 {
60
}
fn default_attempts() -> i64 {
2
}
fn default_rework() -> i64 {
2
}
impl Default for PhaseCfg {
fn default() -> Self {
Self { model: String::new(), agent: default_agent(), permission_mode: default_mode(), timeout_minutes: default_timeout(), extra_prompt: String::new() }
Self { model: String::new(), agent: default_agent(), permission_mode: default_mode(), timeout_minutes: default_timeout(), max_attempts: default_attempts(), extra_prompt: String::new() }
}
}
@@ -101,6 +110,9 @@ pub struct RepoCfg {
pub label: String,
#[serde(default = "default_parallel")]
pub max_parallel: usize,
/// Rounds in which a failed acceptance sends the issue back to the build (0 = no rework).
#[serde(default = "default_rework")]
pub max_rework: i64,
/// Only issues opened by these users start a run (empty = only the token's owner).
#[serde(default)]
pub allowed_users: Vec<String>,
@@ -147,6 +159,7 @@ impl RepoCfg {
self.label = default_label();
}
self.max_parallel = self.max_parallel.clamp(1, 4);
self.max_rework = self.max_rework.clamp(0, 10);
self.allowed_users = self.allowed_users.iter().map(|u| u.trim().to_string()).filter(|u| !u.is_empty()).collect();
for p in [&mut self.review, &mut self.build, &mut self.qa] {
p.model = p.model.trim().to_string();
@@ -157,6 +170,7 @@ impl RepoCfg {
bail!("invalid permission_mode '{}'", p.permission_mode);
}
p.timeout_minutes = p.timeout_minutes.clamp(1, 24 * 60);
p.max_attempts = p.max_attempts.clamp(1, 10);
}
Ok(())
}
@@ -504,6 +518,146 @@ impl Forge {
}
/// Open a pull request (GitLab: merge request); returns {number, html_url}.
fn authed(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
let req = req.header("User-Agent", "codecraft-factory");
match self.kind {
Kind::Gitea => req.header("Authorization", format!("token {}", self.token)),
Kind::Github => req.header("Authorization", format!("Bearer {}", self.token)).header("Accept", "application/vnd.github+json").header("X-GitHub-Api-Version", "2022-11-28"),
Kind::Gitlab => req.header("PRIVATE-TOKEN", &self.token),
}
}
/// (number, title) of the open issues of the repository, newest page first, at most 200.
pub async fn open_issue_titles(&self) -> Result<Vec<(i64, String)>> {
let mut out = Vec::new();
for page in 1..=4 {
let (url, key) = match self.kind {
Kind::Gitea => (self.rp(&format!("/issues?state=open&type=issues&limit=50&page={page}")), "number"),
Kind::Github => (self.rp(&format!("/issues?state=open&per_page=50&page={page}")), "number"),
Kind::Gitlab => (self.rp(&format!("/issues?state=opened&per_page=50&page={page}")), "iid"),
};
let v = self.call(reqwest::Method::GET, url, None).await?;
let a = v.as_array().cloned().unwrap_or_default();
let n = a.len();
for i in a {
if i.get("pull_request").is_some() {
continue;
}
out.push((i[key].as_i64().unwrap_or(0), i["title"].as_str().unwrap_or("").to_string()));
}
if n < 50 {
break;
}
}
Ok(out)
}
pub async fn close_issue(&self, number: u64) -> Result<()> {
match self.kind {
Kind::Gitlab => self.call(reqwest::Method::PUT, self.rp(&format!("/issues/{number}")), Some(json!({"state_event": "close"}))).await.map(|_| ()),
_ => self.call(reqwest::Method::PATCH, self.rp(&format!("/issues/{number}")), Some(json!({"state": "closed"}))).await.map(|_| ()),
}
}
/// A release for an existing tag. Returns {id, html_url}.
pub async fn create_release(&self, tag: &str, name: &str, body: &str) -> Result<Value> {
match self.kind {
Kind::Gitlab => {
let v = self.call(reqwest::Method::POST, self.rp("/releases"), Some(json!({"tag_name": tag, "name": name, "description": body}))).await?;
Ok(json!({"id": tag, "html_url": v["_links"]["self"]}))
}
_ => {
let v = self.call(reqwest::Method::POST, self.rp("/releases"), Some(json!({"tag_name": tag, "name": name, "body": body, "draft": false, "prerelease": false}))).await?;
Ok(json!({"id": v["id"], "html_url": v["html_url"]}))
}
}
}
/// Attach a file to a release (Gitea and GitHub; GitLab has no plain attachment upload).
pub async fn upload_asset(&self, release_id: &Value, name: &str, path: &std::path::Path) -> Result<()> {
let size = std::fs::metadata(path)?.len();
if size > 400 * 1024 * 1024 {
bail!("{name} is larger than 400 MB");
}
let data = tokio::fs::read(path).await?;
let id = release_id.as_i64().map(|i| i.to_string()).or_else(|| release_id.as_str().map(String::from)).unwrap_or_default();
let resp = match self.kind {
Kind::Gitea => {
let part = reqwest::multipart::Part::bytes(data).file_name(name.to_string());
let form = reqwest::multipart::Form::new().part("attachment", part);
self.authed(crate::provider::http_client().post(self.rp(&format!("/releases/{id}/assets?name={}", urlenc(name)))).multipart(form).timeout(Duration::from_secs(900))).send().await?
}
Kind::Github => {
let base = if self.api == "https://api.github.com" { "https://uploads.github.com".to_string() } else { self.api.replace("/api/v3", "/api/uploads") };
let url = format!("{base}/repos/{}/{}/releases/{id}/assets?name={}", self.owner, self.repo, urlenc(name));
self.authed(crate::provider::http_client().post(url).header("Content-Type", "application/octet-stream").body(data).timeout(Duration::from_secs(900))).send().await?
}
Kind::Gitlab => bail!("GitLab has no plain release attachment upload – the file {name} was not attached"),
};
if !resp.status().is_success() {
bail!("uploading {name}: {} {}", resp.status(), resp.text().await.unwrap_or_default().chars().take(200).collect::<String>());
}
Ok(())
}
/// A pull/merge request in one shape: number, html_url, title, state (open|merged|closed),
/// mergeable, changed_files, additions, deletions, head.
fn norm_pr(&self, v: &Value) -> Value {
match self.kind {
Kind::Gitlab => json!({
"number": v["iid"], "html_url": v["web_url"], "title": v["title"],
"state": match v["state"].as_str() { Some("opened") => "open", Some("merged") => "merged", _ => "closed" },
"mergeable": v["merge_status"].as_str() == Some("can_be_merged"),
"changed_files": v["changes_count"], "additions": Value::Null, "deletions": Value::Null, "head": v["source_branch"],
}),
_ => json!({
"number": v["number"], "html_url": v["html_url"], "title": v["title"],
"state": if v["merged"].as_bool() == Some(true) || v["merged_at"].is_string() { json!("merged") } else if v["state"].as_str() == Some("open") { json!("open") } else { json!("closed") },
"mergeable": v["mergeable"], "changed_files": v["changed_files"], "additions": v["additions"], "deletions": v["deletions"], "head": v["head"]["ref"],
}),
}
}
pub async fn pr(&self, number: u64) -> Result<Value> {
let path = if self.kind == Kind::Gitlab { format!("/merge_requests/{number}") } else { format!("/pulls/{number}") };
let v = self.call(reqwest::Method::GET, self.rp(&path), None).await?;
Ok(self.norm_pr(&v))
}
/// The open pull request from a branch with its details, if there is one.
pub async fn find_pr(&self, head: &str) -> Result<Option<Value>> {
let url = self.open_pr(head).await?;
let Some(url) = url else { return Ok(None) };
let n: u64 = url.trim_end_matches('/').rsplit('/').next().and_then(|n| n.parse().ok()).unwrap_or(0);
if n == 0 {
return Ok(None);
}
Ok(Some(self.pr(n).await?))
}
/// Merge a pull request (method: merge, squash or rebase). Only ever called on the user's click.
pub async fn merge_pr(&self, number: u64, method: &str) -> Result<()> {
match self.kind {
Kind::Gitea => self.call(reqwest::Method::POST, self.rp(&format!("/pulls/{number}/merge")), Some(json!({"Do": method}))).await.map(|_| ()),
Kind::Github => self.call(reqwest::Method::PUT, self.rp(&format!("/pulls/{number}/merge")), Some(json!({"merge_method": method}))).await.map(|_| ()),
Kind::Gitlab => self.call(reqwest::Method::PUT, self.rp(&format!("/merge_requests/{number}/merge")), Some(json!({"squash": method == "squash"}))).await.map(|_| ()),
}
}
/// URL of the open pull/merge request from this branch, if there is one.
pub async fn open_pr(&self, head: &str) -> Result<Option<String>> {
match self.kind {
Kind::Gitlab => {
let v = self.call(reqwest::Method::GET, self.rp(&format!("/merge_requests?state=opened&source_branch={}", urlenc(head))), None).await?;
Ok(v.as_array().and_then(|a| a.first()).and_then(|m| m["web_url"].as_str()).map(String::from))
}
_ => {
let v = self.call(reqwest::Method::GET, self.rp("/pulls?state=open&per_page=100&limit=100"), None).await?;
Ok(v.as_array().and_then(|a| a.iter().find(|p| p["head"]["ref"].as_str() == Some(head))).and_then(|p| p["html_url"].as_str()).map(String::from))
}
}
}
pub async fn create_pr(&self, title: &str, body: &str, head: &str, base: &str) -> Result<Value> {
match self.kind {
Kind::Gitlab => {
@@ -597,7 +751,7 @@ pub fn parse_result(text: &str) -> Option<Value> {
candidates.into_iter().rev().find_map(|c| serde_json::from_str::<Value>(c.trim()).ok().filter(|v| v["decision"].is_string()))
}
fn issue_no(v: &Value) -> i64 {
pub(crate) fn issue_no(v: &Value) -> i64 {
v["number"].as_i64().unwrap_or(0)
}
@@ -673,6 +827,10 @@ pub async fn checkout(app: &App, user: &User, cfg: &RepoCfg) -> Result<std::path
let (base, owner, name) = cfg.parts()?;
if dir.join(".git").exists() {
git(cfg, &dir, &["fetch", "--prune", "origin"]).await?;
// The reviews read the files in this checkout: bring the default branch up to date (git pull).
if let Err(e) = crate::factory_version::sync_default(cfg, &dir).await {
tracing::warn!("factory {}: pull of the default branch: {e:#}", cfg.url);
}
} else {
let parent = dir.parent().context("no parent folder")?;
std::fs::create_dir_all(parent)?;
@@ -743,7 +901,7 @@ async fn wait_run(app: &Arc<App>, session_id: &str, timeout_minutes: u64) -> Opt
Some(last_text(app, session_id))
}
async fn bot_comment(g: &Forge, issue: u64, text: &str) {
pub(crate) async fn bot_comment(g: &Forge, issue: u64, text: &str) {
if let Err(e) = g.comment(issue, &format!("{BOT}\n{text}")).await {
tracing::warn!("factory: comment on #{issue}: {e:#}");
}
@@ -759,6 +917,10 @@ async fn review(app: Arc<App>, user: User, cfg: RepoCfg, issue: Value, comments:
};
set(&[("state", json!("review"))]);
let _ = g.set_labels(n as u64, &status_labels(&cfg, "review")).await;
// The review reads the checkout: fetch and pull first so it sees everything merged so far.
if let Err(e) = checkout(&app, &user, &cfg).await {
tracing::warn!("factory {repo}#{n}: update before review: {e:#}");
}
let prompt = review_prompt(&cfg, &issue, &comments, &cfg.review.extra_prompt);
let title = format!("Factory #{n} – review – {}", issue["title"].as_str().unwrap_or(""));
let (run_id, sid) = match start_phase(&app, &user, &cfg, n, "review", 0, prompt, &title, None) {
@@ -883,7 +1045,7 @@ async fn prepare_worktree(app: &App, user: &User, cfg: &RepoCfg, n: i64, branch:
/// Build failure: back to `approved` (the next poll tries again) or, after the second failure, `failed`.
async fn build_fail(app: &Arc<App>, g: &Forge, cfg: &RepoCfg, n: i64, why: &str) {
let attempts = app.store.factory_issue(&cfg.url, n).ok().flatten().and_then(|i| i["attempts"].as_i64()).unwrap_or(0) + 1;
if attempts >= 2 {
if attempts >= cfg.build.max_attempts {
let _ = app.store.factory_issue_set(&cfg.url, n, &[("state", json!("failed")), ("attempts", json!(attempts)), ("note", json!(why))]);
let _ = g.set_labels(n as u64, &status_labels(cfg, "failed")).await;
bot_comment(g, n as u64, &format!("**Build failed:** {why}.")).await;
@@ -964,8 +1126,7 @@ async fn build(app: Arc<App>, user: User, cfg: RepoCfg, issue: Value, comments:
// --- phase 3: acceptance (qa) -------------------------------------------------------------
/// Reworks after a failed acceptance, at most.
const MAX_REWORK: i64 = 2;
pub fn qa_prompt(cfg: &RepoCfg, issue: &Value, scenarios: &str, built: &str, extra: &str) -> String {
format!(
@@ -994,7 +1155,7 @@ How to work:\n\
/// Acceptance failure of the process itself: retried once from `qa`, then `failed`.
async fn qa_fail(app: &Arc<App>, g: &Forge, cfg: &RepoCfg, n: i64, why: &str) {
let attempts = app.store.factory_issue(&cfg.url, n).ok().flatten().and_then(|i| i["attempts"].as_i64()).unwrap_or(0) + 1;
if attempts >= 2 {
if attempts >= cfg.qa.max_attempts {
let _ = app.store.factory_issue_set(&cfg.url, n, &[("state", json!("failed")), ("attempts", json!(attempts)), ("note", json!(why))]);
let _ = g.set_labels(n as u64, &status_labels(cfg, "failed")).await;
bot_comment(g, n as u64, &format!("**Acceptance failed to run:** {why}.")).await;
@@ -1068,21 +1229,23 @@ async fn qa(app: Arc<App>, user: User, cfg: RepoCfg, issue: Value) {
} else {
res["findings"].as_str().filter(|f| !f.trim().is_empty()).unwrap_or(&summary).trim().to_string()
};
if round >= MAX_REWORK {
if round >= cfg.max_rework {
set(&[("state", json!("failed")), ("note", json!(findings.clone()))]);
let _ = g.set_labels(n as u64, &status_labels(&cfg, "failed")).await;
bot_comment(&g, n as u64, &format!("**Acceptance failed after {MAX_REWORK} rework rounds.** {summary}\n\n{table}\n{findings}")).await;
bot_comment(&g, n as u64, &format!("**Acceptance failed after {} rework rounds.** {summary}\n\n{table}\n{findings}", cfg.max_rework)).await;
notify(&app, &user, &format!("Factory #{n}"), "acceptance failed, rework limit reached", n).await;
} else {
set(&[("state", json!("rework")), ("rounds", json!(round + 1)), ("attempts", json!(0)), ("note", json!(findings.clone()))]);
let _ = g.set_labels(n as u64, &status_labels(&cfg, "building")).await;
bot_comment(&g, n as u64, &format!("**Acceptance: problems found** – rework round {} of {MAX_REWORK} starts. {summary}\n\n{table}\n{findings}", round + 1)).await;
notify(&app, &user, &format!("Factory #{n}"), &format!("acceptance found problems, rework {}/{MAX_REWORK}", round + 1), n).await;
bot_comment(&g, n as u64, &format!("**Acceptance: problems found** – rework round {} of {} starts. {summary}\n\n{table}\n{findings}", round + 1, cfg.max_rework)).await;
notify(&app, &user, &format!("Factory #{n}"), &format!("acceptance found problems, rework {}/{}", round + 1, cfg.max_rework), n).await;
}
return;
}
// Accepted: now the pull request is opened (unless one exists from an earlier run).
let mut pr_url = row["pr_url"].as_str().unwrap_or("").to_string();
// An earlier pull request may be merged or closed already (later rework commits would be lost):
// only an open one counts.
let mut pr_url = g.open_pr(&branch).await.ok().flatten().unwrap_or_default();
if pr_url.is_empty() {
let built = row["note"].as_str().unwrap_or("").trim();
let body = format!("Built and accepted by the software factory for #{n}.\n\n**Build**\n{}\n\n**Acceptance** – {summary}\n\n{table}", if built.is_empty() { "–" } else { built });
@@ -1102,7 +1265,7 @@ async fn qa(app: Arc<App>, user: User, cfg: RepoCfg, issue: Value) {
/// First failure: back to `new` (retried by the next poll); second: failed.
async fn fail_or_retry(app: &Arc<App>, g: &Forge, cfg: &RepoCfg, n: i64, why: &str) {
let attempts = app.store.factory_issue(&cfg.url, n).ok().flatten().and_then(|i| i["attempts"].as_i64()).unwrap_or(0) + 1;
if attempts >= 2 {
if attempts >= cfg.review.max_attempts {
let _ = app.store.factory_issue_set(&cfg.url, n, &[("state", json!("failed")), ("attempts", json!(attempts)), ("note", json!(why))]);
let _ = g.set_labels(n as u64, &status_labels(cfg, "failed")).await;
bot_comment(g, n as u64, &format!("**Failed:** {why}.")).await;
@@ -1111,7 +1274,7 @@ async fn fail_or_retry(app: &Arc<App>, g: &Forge, cfg: &RepoCfg, n: i64, why: &s
}
}
async fn notify(app: &App, user: &User, title: &str, body: &str, issue: i64) {
pub(crate) async fn notify(app: &App, user: &User, title: &str, body: &str, issue: i64) {
let payload = json!({"kind": "factory", "title": title, "body": body, "tag": format!("factory-{issue}"), "url": "/#/factory"});
let _ = crate::push::send_to_user(app, &user.id, &payload).await;
}
@@ -1171,6 +1334,10 @@ pub async fn poll_repo(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<()>
app.store.factory_issue_set(&cfg.url, n, &[("title", json!(title)), ("state", json!("review"))])?;
tokio::spawn(review(app.clone(), user.clone(), cfg.clone(), issue, comments));
}
// Merged issues get their version and tag.
if let Err(e) = crate::factory_version::version_pass(app, user, cfg).await {
tracing::warn!("factory {}: versions: {e:#}", cfg.url);
}
Ok(())
}
@@ -1201,6 +1368,135 @@ pub fn spawn(app: Arc<App>) {
}
// --- issue chats: work out features / cut milestones with a model and file the issues ---------
/// Instructions of an issue chat. `{repo_dir}` is the checkout (read-only for the chat), `{mode}` the task.
pub const ISSUE_INSTRUCTIONS: &str = r#"You are the planning stage of a software factory. Autonomous agents will later review, build and accept every issue you help to write – without being able to ask questions. Answer in the user's language.
Your working directory is a scratch folder. The project is checked out at {repo_dir} (read it, never change anything in it; do not create issues or touch the forge yourself). Its specification lives under docs/specs/ in that checkout.
{mode}
Rules for every issue you propose:
- One issue is one deliverable that one agent can build and check in about an hour: a single function or a few closely related ones, never a whole milestone.
- Give it a short title WITHOUT numbering prefix unless you are cutting a numbered milestone (then "M2.3 – Title"), a description of what must exist afterwards, and checkable facts (what someone sees in the running app). Do not repeat the spec; name the spec sections instead.
- `scope` is one line naming exactly what is in scope (e.g. "M2.3 – Quotas (spec section 12)"); everything else in the spec is out of scope for that issue.
- `depends` names the deliverables that must be merged first, or "none".
- Order the issues so that each builds on the earlier ones. Point out gaps and contradictions in the spec instead of guessing.
When the user says the plan is done, end your message with exactly one fenced json block and nothing after it:
```json
{"decision": "issues", "spec": "docs/specs/<file>.md", "issues": [{"title": "…", "description": "…", "scope": "…", "depends": "…"}]}
```
The user reviews the list in a dialog and the issues are created from it."#;
/// The two tasks of an issue chat.
fn issue_mode(mode: &str, topic: &str) -> String {
if mode == "slice" {
format!("Task: cut the milestone \"{topic}\" of the specification into single numbered deliverables (titles like \"{topic}.1 – …\", \"{topic}.2 – …\"). Read the milestone and every feature it names, check what the code already has, and propose the smallest sensible slices in build order. Show the user the list first and adjust it together before you finish.")
} else {
format!("Task: work out a new feature together with the user{}. Interview step by step (a few questions at a time): goal, users, behaviour and edge cases, how it fits the existing code, what is out of scope, how someone checks that it works. Then propose one or more issues; split a larger feature into deliverables that can be built one after the other.", if topic.trim().is_empty() { String::new() } else { format!(" – starting point: {topic}") })
}
}
/// Folder of an issue chat: <factory>/<user>/_issues/<id> (holds repo.txt with the repository URL).
pub fn issue_chat_dir(app: &App, user: &User, id: &str) -> Result<std::path::PathBuf> {
let home = app.factory_home(user).context("the factory area is not mounted (FACTORY_DIR → /factory)")?;
Ok(home.join("_issues").join(id))
}
/// Is this chat an issue chat of the user? Returns its folder.
pub fn issue_chat_of(app: &App, user: &User, session: &crate::types::Session) -> Option<std::path::PathBuf> {
let home = app.factory_home(user)?.join("_issues");
let cwd = std::path::PathBuf::from(&session.cwd);
(session.owner_id.as_deref() == Some(&user.id) && cwd.starts_with(&home) && cwd != home).then_some(cwd)
}
/// Start an issue chat for a repository. mode: "feature" or "slice" (topic = the milestone).
pub async fn start_issue_chat(app: &Arc<App>, user: &User, cfg: &RepoCfg, model: &str, mode: &str, topic: &str) -> Result<crate::types::Session> {
if mode == "slice" && topic.trim().is_empty() {
bail!("name the milestone to cut (e.g. M2)");
}
let repo = checkout(app, user, cfg).await?;
let id = crate::types::new_id();
let dir = issue_chat_dir(app, user, &id)?;
std::fs::create_dir_all(&dir)?;
std::fs::write(dir.join("repo.txt"), &cfg.url)?;
let model = Some(model.to_string()).filter(|m| !m.is_empty()).or_else(|| Some(app.config().server.default_model.clone()).filter(|m| !m.is_empty())).or_else(|| app.registry().first_model()).context("no model configured")?;
let (_, _, name) = cfg.parts()?;
let now = crate::types::now_ms();
let session = crate::types::Session {
id,
title: format!("Factory – issues – {name}"),
cwd: dir.display().to_string(),
model,
agent: "build".into(),
permission_mode: "default".into(),
parent_id: None,
owner_id: Some(user.id.clone()),
created_at: now,
updated_at: now,
todos: Value::Null,
last_usage: None,
clean_room: None,
phase: None,
worktree: None,
pinned: false,
archived: false,
folder: Some(FACTORY_FOLDER.to_string()),
instructions: ISSUE_INSTRUCTIONS.replace("{repo_dir}", &repo.display().to_string()).replace("{mode}", &issue_mode(mode, topic.trim())),
telegram_quiet: true,
summary: String::new(),
color: None,
icon: None,
};
app.save_session(session)
}
/// The issue list the model ended its last message with.
pub fn issue_proposal(app: &App, session_id: &str) -> Option<Value> {
parse_result(&last_text(app, session_id)).filter(|v| v["decision"] == "issues" && v["issues"].is_array())
}
/// Body of an issue made from a proposal: the description plus the lines the factory reads.
pub fn issue_body(description: &str, spec: &str, scope: &str, depends: &str) -> String {
let mut body = description.trim().to_string();
body.push_str(&format!("\n\nSpec: {spec}"));
if !scope.trim().is_empty() {
body.push_str(&format!("\nScope: {}", scope.trim().replace('\n', " ")));
}
let d = depends.trim();
if !d.is_empty() && !d.eq_ignore_ascii_case("none") && !d.eq_ignore_ascii_case("keine") {
body.push_str(&format!("\n\nPrerequisite: {d} – merge it first, then start this issue."));
}
body.push('\n');
body
}
/// Create the issues on the forge; with `start` they get the factory label (the workflow starts).
pub async fn create_issues(cfg: &RepoCfg, spec: &str, issues: &[Value], start: bool) -> Result<Vec<Value>> {
let spec = spec.trim();
if spec.is_empty() || spec.starts_with('/') || spec.contains("..") {
bail!("the spec path is missing or invalid");
}
let g = Forge::new(cfg)?;
if start {
g.ensure_labels().await?;
}
let mut out = Vec::new();
for i in issues {
let title = i["title"].as_str().unwrap_or("").trim();
if title.is_empty() {
bail!("an issue has no title");
}
let body = issue_body(i["description"].as_str().unwrap_or(""), spec, i["scope"].as_str().unwrap_or(""), i["depends"].as_str().unwrap_or(""));
let labels = if start { vec![cfg.label.clone()] } else { Vec::new() };
let r = g.create_issue(title, &body, &labels).await?;
out.push(json!({"number": issue_no(&r), "title": title, "url": r["html_url"]}));
}
Ok(out)
}
// --- spec chat and project creation ---------------------------------------------------
/// Instructions of the chat in which the user writes a spec together with a model.
@@ -1495,6 +1791,19 @@ mod tests {
assert!(SPEC_INSTRUCTIONS.contains("setup.json"));
}
#[test]
fn issue_body_carries_the_factory_lines() {
let b = issue_body("Do X.", "docs/specs/a.md", "M2.1 – X (section 3)", "M1.4");
assert!(b.contains("Spec: docs/specs/a.md") && b.contains("Scope: M2.1 – X (section 3)") && b.contains("Prerequisite: M1.4"));
assert!(!issue_body("Do X.", "a.md", "", "none").contains("Prerequisite"));
assert_eq!(spec_path(&json!({"body": b})).as_deref(), Some("docs/specs/a.md"));
assert!(issue_mode("slice", "M2").contains("\"M2.1 – …\""));
let p = ISSUE_INSTRUCTIONS.replace("{repo_dir}", "/f/r");
assert!(p.contains("/f/r") && p.contains("\"decision\": \"issues\""));
let t = "Fertig.\n```json\n{\"decision\": \"issues\", \"spec\": \"a.md\", \"issues\": []}\n```";
assert!(parse_result(t).is_some_and(|v| v["decision"] == "issues"));
}
#[test]
fn encodes_labels() {
assert_eq!(urlenc("factory:qa"), "factory%3Aqa");
+609
View File
@@ -0,0 +1,609 @@
//! Versions, tags and releases of factory repositories.
//!
//! Every merged factory issue gets a version (`MAJOR.MINOR.PATCH`): the patch number goes up with each
//! issue, the minor number when the issue completes a milestone (`M1.3` was the last open `M1.x`
//! issue); the patch restarts at 0. A version is a commit with a `VERSION` file on the default branch
//! plus the tag `vX.Y.Z` on it. Major versions are only made by a manual release, which also builds
//! the Docker image and the downloads described in `.factory/release.json`.
use crate::app::App;
use crate::factory::{Forge, RepoCfg, bot_comment, checkout, git, issue_no, notify};
use crate::store::User;
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
pub type Ver = (u64, u64, u64);
pub fn parse_version(s: &str) -> Option<Ver> {
let mut it = s.trim().trim_start_matches('v').split('.');
let v = (it.next()?.parse().ok()?, it.next()?.parse().ok()?, it.next()?.parse().ok()?);
it.next().is_none().then_some(v)
}
pub fn fmt(v: Ver) -> String {
format!("{}.{}.{}", v.0, v.1, v.2)
}
/// Milestone of an issue title: `M1.3 – x` → (1, Some(3)), `M1 – x` → (1, None).
pub fn milestone_of(title: &str) -> Option<(u64, Option<u64>)> {
let t = title.trim();
let rest = t.strip_prefix('M').or_else(|| t.strip_prefix('m'))?;
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
let k: u64 = digits.parse().ok()?;
let after = &rest[digits.len()..];
if let Some(a) = after.strip_prefix('.') {
let d: String = a.chars().take_while(|c| c.is_ascii_digit()).collect();
if !d.is_empty() {
return Some((k, Some(d.parse().ok()?)));
}
}
match after.chars().next() {
None | Some(' ') | Some('–') | Some('-') | Some(':') => Some((k, None)),
_ => None,
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Bump {
Patch,
Minor,
}
/// How an issue raises the version, given the titles of the *other* open issues of the repository.
pub fn bump_for(title: &str, other_open: &[String]) -> Bump {
match milestone_of(title) {
Some((_, None)) => Bump::Minor,
Some((k, Some(_))) => {
if other_open.iter().any(|t| matches!(milestone_of(t), Some((k2, Some(_))) if k2 == k)) {
Bump::Patch
} else {
Bump::Minor
}
}
None => Bump::Patch,
}
}
pub fn next_version(cur: Ver, b: Bump) -> Ver {
match b {
Bump::Patch => (cur.0, cur.1, cur.2 + 1),
Bump::Minor => (cur.0, cur.1 + 1, 0),
}
}
// --- git helpers ---------------------------------------------------------------------------
/// Highest `vX.Y.Z` tag of the remote (0.0.0 when there is none).
async fn tags_version(cfg: &RepoCfg, dir: &Path) -> Ver {
let _ = git(cfg, dir, &["fetch", "--tags", "--force", "origin"]).await;
git(cfg, dir, &["tag", "-l", "v[0-9]*"]).await.unwrap_or_default().lines().filter_map(parse_version).max().unwrap_or((0, 0, 0))
}
/// `git pull --ff-only` of the default branch in the main checkout, so everything that was merged
/// (also by others) is on disk for the reviews. Does nothing harmful: with local changes or a
/// diverged branch it reports an error and leaves the checkout alone.
pub async fn sync_default(cfg: &RepoCfg, dir: &Path) -> Result<()> {
let base = base_branch(cfg, dir).await;
let current = git(cfg, dir, &["rev-parse", "--abbrev-ref", "HEAD"]).await.unwrap_or_default();
if current != base {
if !git(cfg, dir, &["status", "--porcelain"]).await.unwrap_or_default().is_empty() {
bail!("the checkout has local changes and is on '{current}', not on {base}");
}
git(cfg, dir, &["checkout", "-q", &base]).await?;
}
git(cfg, dir, &["merge", "--ff-only", "-q", &format!("origin/{base}")]).await?;
Ok(())
}
async fn base_branch(cfg: &RepoCfg, repo: &Path) -> String {
git(cfg, repo, &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]).await.ok().and_then(|s| s.strip_prefix("origin/").map(String::from)).unwrap_or_else(|| "main".to_string())
}
/// A throw-away detached worktree of the default branch below `<owner>/<sub>/<name>`.
async fn fresh_worktree(cfg: &RepoCfg, repo: &Path, sub: &str, name: &str, base: &str) -> Result<PathBuf> {
let work = repo.parent().context("no parent folder")?.join(sub).join(name);
std::fs::create_dir_all(work.parent().unwrap())?;
if work.exists() {
let _ = git(cfg, repo, &["worktree", "remove", "--force", &work.display().to_string()]).await;
let _ = std::fs::remove_dir_all(&work);
}
let _ = git(cfg, repo, &["worktree", "prune"]).await;
git(cfg, repo, &["worktree", "add", "--detach", &work.display().to_string(), &format!("origin/{base}")]).await?;
Ok(work)
}
async fn drop_worktree(cfg: &RepoCfg, repo: &Path, work: &Path) {
let _ = git(cfg, repo, &["worktree", "remove", "--force", &work.display().to_string()]).await;
let _ = std::fs::remove_dir_all(work);
}
const IDENT: [&str; 4] = ["-c", "user.name=CodeCraft Factory", "-c", "user.email=factory@codecraft.invalid"];
/// Write `VERSION` and commit it locally (nothing is pushed yet).
async fn commit_version(cfg: &RepoCfg, work: &Path, ver: &str, msg: &str) -> Result<()> {
std::fs::write(work.join("VERSION"), format!("{ver}\n"))?;
git(cfg, work, &["add", "VERSION"]).await?;
if !git(cfg, work, &["diff", "--cached", "--name-only"]).await?.is_empty() {
let mut args = IDENT.to_vec();
args.extend(["commit", "-m", msg]);
git(cfg, work, &args).await?;
}
Ok(())
}
/// Tag the commit and push default branch and tag. Returns a warning when the branch could not be
/// pushed (e.g. protected): then the tag goes onto the commit already on the branch.
async fn publish_version(cfg: &RepoCfg, work: &Path, base: &str, ver: &str, msg: &str) -> Result<String> {
let mut warn = String::new();
let target = format!("HEAD:refs/heads/{base}");
let mut pushed = git(cfg, work, &["push", "origin", &target]).await;
if pushed.is_err() {
// The branch moved meanwhile: put the version commit on top and try once more.
let _ = git(cfg, work, &["fetch", "origin"]).await;
let upstream = format!("origin/{base}");
let mut args = IDENT.to_vec();
args.extend(["rebase", &upstream]);
if git(cfg, work, &args).await.is_ok() {
pushed = git(cfg, work, &["push", "origin", &target]).await;
} else {
let _ = git(cfg, work, &["rebase", "--abort"]).await;
}
}
if let Err(e) = pushed {
warn = format!("the VERSION commit could not be pushed to {base} ({e:#}); the tag points to the branch head instead");
git(cfg, work, &["reset", "--hard", &format!("origin/{base}")]).await?;
}
let tag = format!("v{ver}");
let mut args = IDENT.to_vec();
args.extend(["tag", "-a", "-f", &tag, "-m", msg]);
git(cfg, work, &args).await?;
git(cfg, work, &["push", "origin", &format!("refs/tags/{tag}")]).await?;
Ok(warn)
}
// --- version of merged issues -----------------------------------------------------------------
static BUSY: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
/// Keeps two passes (poller and manual poll) from versioning the same repository at once.
struct Busy(String);
fn busy(repo: &str) -> Option<Busy> {
let set = BUSY.get_or_init(Default::default);
set.lock().unwrap().insert(repo.to_string()).then(|| Busy(repo.to_string()))
}
impl Drop for Busy {
fn drop(&mut self) {
if let Some(set) = BUSY.get() {
set.lock().unwrap().remove(&self.0);
}
}
}
fn pr_number(url: &str) -> u64 {
url.trim_end_matches('/').rsplit('/').next().and_then(|n| n.parse().ok()).unwrap_or(0)
}
/// Give every merged, accepted issue its version. The first pass over a repository only
/// sets the baseline: issues that were done before are not versioned.
pub async fn version_pass(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<()> {
let Some(_guard) = busy(&cfg.url) else { return Ok(()) };
let rows: Vec<Value> = app.store.factory_issues(&user.id)?.into_iter().filter(|r| r["repo"].as_str() == Some(cfg.url.as_str())).collect();
let pending = |r: &&Value| r["state"].as_str() == Some("done") && r["version"].as_str() == Some("");
if app.store.factory_version(&cfg.url)?.is_none() {
let dir = checkout(app, user, cfg).await?;
let cur = tags_version(cfg, &dir).await;
for r in rows.iter().filter(pending) {
app.store.factory_issue_set(&cfg.url, issue_no(r), &[("version", json!("-"))])?;
}
app.store.factory_version_set(&cfg.url, &fmt(cur))?;
return Ok(());
}
let mut todo: Vec<&Value> = rows.iter().filter(pending).collect();
if todo.is_empty() {
return Ok(());
}
todo.sort_by_key(|r| issue_no(r));
let g = Forge::new(cfg)?;
for r in todo {
let n = issue_no(r);
let pr_n = pr_number(r["pr_url"].as_str().unwrap_or(""));
if pr_n == 0 {
continue;
}
let pr = match g.pr(pr_n).await {
Ok(p) => p,
Err(e) => {
tracing::warn!("factory {}#{n}: pull request: {e:#}", cfg.url);
continue;
}
};
if pr["state"].as_str() != Some("merged") {
continue;
}
let title = r["title"].as_str().unwrap_or("").to_string();
let others: Vec<String> = g.open_issue_titles().await?.into_iter().filter(|(num, _)| *num != n).map(|(_, t)| t).collect();
let dir = checkout(app, user, cfg).await?;
let cur = tags_version(cfg, &dir).await;
let bump = bump_for(&title, &others);
let new = fmt(next_version(cur, bump));
let base = base_branch(cfg, &dir).await;
let (_, _, name) = cfg.parts()?;
let work = fresh_worktree(cfg, &dir, "_release", &format!("{name}-version"), &base).await?;
let msg = format!("Release v{new}: {title} (#{n})");
let published = async {
commit_version(cfg, &work, &new, &msg).await?;
publish_version(cfg, &work, &base, &new, &msg).await
}
.await;
drop_worktree(cfg, &dir, &work).await;
let warn = match published {
Ok(w) => w,
Err(e) => {
tracing::warn!("factory {}#{n}: version {new}: {e:#}", cfg.url);
continue;
}
};
let _ = checkout(app, user, cfg).await; // pulls the merge and the VERSION commit
app.store.factory_issue_set(&cfg.url, n, &[("version", json!(new.clone()))])?;
app.store.factory_version_set(&cfg.url, &new)?;
let _ = g.close_issue(n as u64).await;
let why = if bump == Bump::Minor && milestone_of(&title).is_some() { " – the milestone is complete" } else { "" };
let extra = if warn.is_empty() { String::new() } else { format!("\n\nNote: {warn}.") };
bot_comment(&g, n as u64, &format!("**Version v{new}**{why}. The change is merged; tag `v{new}` and `VERSION` are on the default branch.{extra}")).await;
notify(app, user, &format!("Factory #{n}"), &format!("v{new}{why}"), n).await;
}
Ok(())
}
// --- manual release ----------------------------------------------------------------------------
/// `.factory/release.json`: how to build the downloads of a release.
#[derive(Debug, Default, Deserialize)]
pub struct ReleaseSpec {
/// Docker image name without tag, e.g. registry.example.org/team/app (empty = no image).
#[serde(default)]
pub image: String,
#[serde(default = "default_platforms")]
pub platforms: String,
#[serde(default = "default_dockerfile")]
pub dockerfile: String,
#[serde(default = "default_context")]
pub context: String,
#[serde(default)]
pub build_args: HashMap<String, String>,
/// Shell commands run in the release checkout before the image is built (e.g. to make zips).
#[serde(default)]
pub commands: Vec<String>,
/// Files (globs relative to the checkout) attached to the release; the source zip is always attached.
#[serde(default)]
pub files: Vec<String>,
/// Name used for the source zip (default: the repository name).
#[serde(default)]
pub name: String,
}
fn default_platforms() -> String {
"linux/amd64,linux/arm64".into()
}
fn default_dockerfile() -> String {
"Dockerfile".into()
}
fn default_context() -> String {
".".into()
}
/// Run a command with a timeout; returns the last lines of its output.
async fn run(cmd: &mut tokio::process::Command, timeout: Duration, stdin: Option<&str>) -> Result<String> {
use tokio::io::AsyncWriteExt;
cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).stdin(if stdin.is_some() { std::process::Stdio::piped() } else { std::process::Stdio::null() }).kill_on_drop(true);
let mut child = cmd.spawn().context("could not start the command")?;
if let (Some(text), Some(mut si)) = (stdin, child.stdin.take()) {
si.write_all(text.as_bytes()).await?;
}
let out = tokio::time::timeout(timeout, child.wait_with_output()).await.map_err(|_| anyhow::anyhow!("timed out after {} min", timeout.as_secs() / 60))??;
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
let tail: Vec<&str> = text.lines().rev().take(25).collect::<Vec<_>>().into_iter().rev().collect();
let tail = tail.join("\n");
if !out.status.success() {
bail!("{}", tail);
}
Ok(tail)
}
fn clean_env(cmd: &mut tokio::process::Command, extra: &[(&str, &str)]) {
cmd.env_clear().env("PATH", std::env::var("PATH").unwrap_or_default()).env("HOME", "/tmp");
for (k, v) in extra {
cmd.env(k, v);
}
}
/// Current version, suggested next major version and the release recipe of the default branch.
pub async fn preview(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<Value> {
let dir = checkout(app, user, cfg).await?;
let cur = tags_version(cfg, &dir).await;
let base = base_branch(cfg, &dir).await;
let spec = git(cfg, &dir, &["show", &format!("origin/{base}:.factory/release.json")]).await.ok();
Ok(json!({"current": fmt(cur), "suggested": fmt((cur.0 + 1, 0, 0)), "spec": spec, "running": app.store.factory_release_running(&cfg.url)?}))
}
/// Validate and start a release in the background; returns the release id.
pub async fn start_release(app: &Arc<App>, user: &User, cfg: &RepoCfg, version: &str) -> Result<String> {
let Some(new) = parse_version(version) else { bail!("the version must look like 1.0.0") };
if app.store.factory_release_running(&cfg.url)? {
bail!("a release of this repository is already running");
}
let dir = checkout(app, user, cfg).await?;
let cur = tags_version(cfg, &dir).await;
if new <= cur {
bail!("v{} is not newer than the current version v{}", fmt(new), fmt(cur));
}
let id = crate::types::new_id();
app.store.factory_release_add(&id, &user.id, &cfg.url, &fmt(new))?;
let (app, user, cfg, rid) = (app.clone(), user.clone(), cfg.clone(), id.clone());
tokio::spawn(async move {
let log = |m: &str| {
let _ = app.store.factory_release_log(&rid, m);
};
match run_release(&app, &user, &cfg, new, &rid, &log).await {
Ok(url) => {
let _ = app.store.factory_release_end(&rid, "done", &url);
notify(&app, &user, "Factory release", &format!("v{} released", fmt(new)), 0).await;
}
Err(e) => {
log(&format!("FAILED: {e:#}"));
let _ = app.store.factory_release_end(&rid, "failed", "");
notify(&app, &user, "Factory release", &format!("v{} failed", fmt(new)), 0).await;
}
}
});
Ok(id)
}
async fn run_release(app: &Arc<App>, user: &User, cfg: &RepoCfg, new: Ver, rid: &str, log: &(dyn Fn(&str) + Sync)) -> Result<String> {
let ver = fmt(new);
let tag = format!("v{ver}");
let dir = checkout(app, user, cfg).await?;
let base = base_branch(cfg, &dir).await;
let (_, _, name) = cfg.parts()?;
let g = Forge::new(cfg)?;
log(&format!("release {tag} from {base}"));
let work = fresh_worktree(cfg, &dir, "_release", &format!("{name}-release"), &base).await?;
let tmp = std::env::temp_dir().join(format!("factory-release-{rid}"));
std::fs::create_dir_all(&tmp)?;
let result = release_steps(cfg, &g, &work, &tmp, &base, &name, &ver, &tag, rid, log).await;
drop_worktree(cfg, &dir, &work).await;
let _ = std::fs::remove_dir_all(&tmp);
result
}
#[allow(clippy::too_many_arguments)]
async fn release_steps(cfg: &RepoCfg, g: &Forge, work: &Path, tmp: &Path, base: &str, name: &str, ver: &str, tag: &str, rid: &str, log: &(dyn Fn(&str) + Sync)) -> Result<String> {
let msg = format!("Release {tag}");
commit_version(cfg, work, ver, &msg).await?;
let spec: ReleaseSpec = match std::fs::read_to_string(work.join(".factory/release.json")) {
Ok(t) => serde_json::from_str(&t).context(".factory/release.json is not valid")?,
Err(_) => {
log("no .factory/release.json – only the tag, the release and the source zip are made");
ReleaseSpec::default()
}
};
let hour = Duration::from_secs(3600);
for cmd in &spec.commands {
log(&format!("$ {cmd}"));
let mut c = tokio::process::Command::new("bash");
c.arg("-c").arg(cmd).current_dir(work);
clean_env(&mut c, &[("VERSION", ver), ("CI", "1")]);
log(&run(&mut c, hour, None).await?);
}
if !spec.image.trim().is_empty() {
build_image(cfg, g, &spec, work, tmp, ver, rid, log).await?;
}
// Publish: branch + tag, then the release with its files.
let warn = publish_version(cfg, work, base, ver, &msg).await?;
if !warn.is_empty() {
log(&format!("note: {warn}"));
}
log(&format!("tag {tag} pushed"));
let prev = git(cfg, work, &["tag", "-l", "v[0-9]*"]).await.unwrap_or_default().lines().filter_map(|t| parse_version(t).map(|v| (v, t.to_string()))).filter(|(v, _)| fmt(*v) != ver && *v < parse_version(ver).unwrap_or((0, 0, 0))).max().map(|(_, t)| t);
let range = prev.as_ref().map(|p| format!("{p}..{tag}")).unwrap_or_else(|| tag.to_string());
let changes = git(cfg, work, &["log", "--pretty=format:- %s", "--max-count=200", &range]).await.unwrap_or_default();
let mut notes = format!("Release {tag}\n\n");
if !spec.image.trim().is_empty() {
notes.push_str(&format!("Docker image: `{}:{ver}` ({})\n\n", spec.image.trim(), spec.platforms));
}
notes.push_str(&format!("## Changes\n\n{changes}\n"));
let rel = g.create_release(tag, &format!("{name} {tag}"), &notes).await?;
let url = rel["html_url"].as_str().unwrap_or("").to_string();
log(&format!("release created {url}"));
// Downloads: the source zip and the configured files.
let zip_name = format!("{}-{ver}-source.zip", Some(spec.name.trim()).filter(|n| !n.is_empty()).unwrap_or(name));
let zip = tmp.join(&zip_name);
git(cfg, work, &["archive", "--format=zip", &format!("--prefix={name}-{ver}/"), "-o", &zip.display().to_string(), "HEAD"]).await?;
let mut files: Vec<(String, PathBuf)> = vec![(zip_name, zip)];
if !spec.files.is_empty() {
let mut builder = globset::GlobSetBuilder::new();
for f in &spec.files {
builder.add(globset::Glob::new(f).with_context(|| format!("bad file pattern {f}"))?);
}
let set = builder.build()?;
let mut stack = vec![work.to_path_buf()];
while let Some(d) = stack.pop() {
for e in std::fs::read_dir(&d)?.flatten() {
let p = e.path();
let rel_path = p.strip_prefix(work).unwrap_or(&p).to_path_buf();
if rel_path.starts_with(".git") || rel_path.starts_with("node_modules") || rel_path.starts_with("target") && !set.is_match(&rel_path) {
continue;
}
if p.is_dir() {
stack.push(p);
} else if set.is_match(&rel_path) && files.len() < 60 {
files.push((e.file_name().to_string_lossy().to_string(), p));
}
}
}
}
for (fname, path) in &files {
match g.upload_asset(&rel["id"], fname, path).await {
Ok(()) => log(&format!("attached {fname}")),
Err(e) => log(&format!("not attached: {e:#}")),
}
}
Ok(url)
}
/// Build and push the multi-arch Docker image with buildx (own builder, own login, both removed afterwards).
#[allow(clippy::too_many_arguments)]
async fn build_image(cfg: &RepoCfg, g: &Forge, spec: &ReleaseSpec, work: &Path, tmp: &Path, ver: &str, rid: &str, log: &(dyn Fn(&str) + Sync)) -> Result<()> {
let image = spec.image.trim();
let first = image.split('/').next().unwrap_or("");
let host = if image.contains('/') && (first.contains('.') || first.contains(':')) { first } else { "docker.io" };
let conf = tmp.join("docker");
std::fs::create_dir_all(&conf)?;
let conf_s = conf.display().to_string();
let builder = format!("factory-{}", &rid[..8.min(rid.len())]);
let minute = Duration::from_secs(120);
let env = [("DOCKER_CONFIG", conf_s.as_str())];
let mut c = tokio::process::Command::new("docker");
c.args(["buildx", "version"]);
clean_env(&mut c, &env);
run(&mut c, minute, None).await.context("docker buildx is not available in this installation")?;
let login = g.login().await?;
log(&format!("docker login {host}"));
let mut c = tokio::process::Command::new("docker");
c.args(["login", host, "-u", &login, "--password-stdin"]);
clean_env(&mut c, &env);
run(&mut c, minute, Some(&cfg.token)).await.context("docker login failed")?;
let mut c = tokio::process::Command::new("docker");
c.args(["buildx", "create", "--name", &builder, "--driver", "docker-container"]);
clean_env(&mut c, &env);
run(&mut c, minute, None).await.context("could not create the buildx builder")?;
let mut args: Vec<String> = ["buildx", "build", "--builder", &builder, "--platform", &spec.platforms, "-f", &spec.dockerfile, "-t", &format!("{image}:{ver}"), "-t", &format!("{image}:latest"), "--build-arg", &format!("VERSION={ver}")].iter().map(|s| s.to_string()).collect();
for (k, v) in &spec.build_args {
args.extend(["--build-arg".to_string(), format!("{k}={v}")]);
}
args.extend(["--push".to_string(), spec.context.clone()]);
log(&format!("docker buildx build {} → {image}:{ver}", spec.platforms));
let mut c = tokio::process::Command::new("docker");
c.args(&args).current_dir(work);
clean_env(&mut c, &env);
let built = run(&mut c, Duration::from_secs(3 * 3600), None).await;
let mut c = tokio::process::Command::new("docker");
c.args(["buildx", "rm", "--force", &builder]);
clean_env(&mut c, &env);
let _ = run(&mut c, minute, None).await;
log(&built.context("the image build failed")?);
log("image pushed");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_and_formats_versions() {
assert_eq!(parse_version("v1.2.3"), Some((1, 2, 3)));
assert_eq!(parse_version("0.0.0"), Some((0, 0, 0)));
assert_eq!(parse_version("1.2"), None);
assert_eq!(parse_version("1.2.3.4"), None);
assert_eq!(parse_version("vx.1.2"), None);
assert_eq!(fmt((0, 1, 10)), "0.1.10");
assert!(parse_version("0.10.0") > parse_version("0.9.9"));
}
#[test]
fn reads_milestones_from_titles() {
assert_eq!(milestone_of("M1.3 – Import"), Some((1, Some(3))));
assert_eq!(milestone_of("M12.10 - x"), Some((12, Some(10))));
assert_eq!(milestone_of("M1 – Foundation"), Some((1, None)));
assert_eq!(milestone_of("M0"), Some((0, None)));
assert_eq!(milestone_of("Make it faster"), None);
assert_eq!(milestone_of("M1abc"), None);
assert_eq!(milestone_of("Fix login"), None);
}
#[test]
fn issues_raise_patch_and_the_last_one_of_a_milestone_the_minor() {
let open = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
// other M1 issues still open: patch
assert_eq!(bump_for("M1.3 – Import", &open(&["M1.4 – Debayering", "M2.1 – Mail"])), Bump::Patch);
// the last open M1 issue: minor (other milestones do not matter)
assert_eq!(bump_for("M1.11 – Log", &open(&["M2.1 – Mail", "Fix typo"])), Bump::Minor);
assert_eq!(bump_for("Fix login bug", &open(&["M1.1 – x"])), Bump::Patch);
assert_eq!(bump_for("M3 – Mosaics", &open(&[])), Bump::Minor);
assert_eq!(next_version((0, 0, 7), Bump::Patch), (0, 0, 8));
assert_eq!(next_version((0, 0, 10), Bump::Minor), (0, 1, 0));
assert_eq!(next_version((0, 1, 4), Bump::Minor), (0, 2, 0));
}
#[test]
fn release_spec_has_defaults() {
let s: ReleaseSpec = serde_json::from_str(r#"{"image": "r.example/app"}"#).unwrap();
assert_eq!((s.platforms.as_str(), s.dockerfile.as_str(), s.context.as_str()), ("linux/amd64,linux/arm64", "Dockerfile", "."));
assert!(s.commands.is_empty() && s.files.is_empty());
}
#[tokio::test]
async fn sync_default_pulls_what_was_merged() {
let run = |dir: &Path, args: &[&str]| {
let o = std::process::Command::new("git").args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "init.defaultBranch=main"]).args(args).current_dir(dir).output().unwrap();
assert!(o.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&o.stderr));
};
let root = std::env::temp_dir().join(format!("factory-sync-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
run(&root, &["init", "-q", "--bare", "origin.git"]);
run(&root, &["clone", "-q", "origin.git", "a"]);
std::fs::write(root.join("a/one.txt"), "1").unwrap();
run(&root.join("a"), &["add", "."]);
run(&root.join("a"), &["commit", "-qm", "one"]);
run(&root.join("a"), &["push", "-q", "origin", "HEAD:main"]);
run(&root, &["--git-dir=origin.git", "symbolic-ref", "HEAD", "refs/heads/main"]);
run(&root, &["clone", "-q", "origin.git", "checkout"]);
// somebody merges a second change on the remote
std::fs::write(root.join("a/two.txt"), "2").unwrap();
run(&root.join("a"), &["add", "."]);
run(&root.join("a"), &["commit", "-qm", "two"]);
run(&root.join("a"), &["push", "-q", "origin", "HEAD:main"]);
let cfg: RepoCfg = serde_json::from_value(json!({"url": "https://g.example/o/r.git", "token": "t"})).unwrap();
let dir = root.join("checkout");
git(&cfg, &dir, &["fetch", "origin"]).await.unwrap();
assert!(!dir.join("two.txt").exists(), "a fetch alone does not update the files");
sync_default(&cfg, &dir).await.unwrap();
assert!(dir.join("two.txt").exists());
// local changes block switching, nothing is damaged
std::fs::write(dir.join("one.txt"), "edited").unwrap();
sync_default(&cfg, &dir).await.unwrap();
assert_eq!(std::fs::read_to_string(dir.join("one.txt")).unwrap(), "edited");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn pr_numbers_come_from_urls() {
assert_eq!(pr_number("https://g.example/o/r/pulls/72"), 72);
assert_eq!(pr_number("https://g.example/o/r/-/merge_requests/5/"), 5);
assert_eq!(pr_number(""), 0);
}
#[test]
fn busy_guard_blocks_a_second_pass() {
let a = busy("https://g.example/o/busy-test");
assert!(a.is_some());
assert!(busy("https://g.example/o/busy-test").is_none());
drop(a);
assert!(busy("https://g.example/o/busy-test").is_some());
}
}
+1
View File
@@ -14,6 +14,7 @@ mod digest;
mod docs;
mod export;
mod factory;
mod factory_version;
mod files;
mod git;
mod health;
+69 -3
View File
@@ -204,6 +204,22 @@ impl Store {
result TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS factory_runs_issue ON factory_runs(repo_url, issue);
CREATE TABLE IF NOT EXISTS factory_versions (
repo_url TEXT PRIMARY KEY,
current TEXT NOT NULL DEFAULT '0.0.0',
since INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS factory_releases (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL,
repo_url TEXT NOT NULL,
version TEXT NOT NULL,
state TEXT NOT NULL DEFAULT 'running',
log TEXT NOT NULL DEFAULT '',
url TEXT NOT NULL DEFAULT '',
started_at INTEGER NOT NULL,
ended_at INTEGER
);
CREATE TABLE IF NOT EXISTS project_defaults (
cwd TEXT PRIMARY KEY,
data TEXT NOT NULL
@@ -238,6 +254,7 @@ impl Store {
("jobs", "settings", "ALTER TABLE jobs ADD COLUMN settings TEXT"),
("images", "blob", "ALTER TABLE images ADD COLUMN blob TEXT"),
("usage", "allowance", "ALTER TABLE usage ADD COLUMN allowance REAL"),
("factory_issues", "version", "ALTER TABLE factory_issues ADD COLUMN version TEXT NOT NULL DEFAULT ''"),
] {
let exists: bool = conn
.prepare(&format!("SELECT 1 FROM pragma_table_info('{table}') WHERE name = ?1"))?
@@ -1465,8 +1482,8 @@ impl Store {
pub fn factory_issue(&self, repo: &str, number: i64) -> Result<Option<Value>> {
let conn = self.conn.lock().unwrap();
Ok(conn
.query_row("SELECT title, author, state, attempts, rounds, last_comment, scenarios, branch, pr_url, note, created_at, updated_at, owner_id FROM factory_issues WHERE repo_url = ?1 AND number = ?2", params![repo, number], |r| {
Ok(json!({"repo": repo, "number": number, "title": r.get::<_, String>(0)?, "author": r.get::<_, String>(1)?, "state": r.get::<_, String>(2)?, "attempts": r.get::<_, i64>(3)?, "rounds": r.get::<_, i64>(4)?, "last_comment": r.get::<_, i64>(5)?, "scenarios": r.get::<_, String>(6)?, "branch": r.get::<_, String>(7)?, "pr_url": r.get::<_, String>(8)?, "note": r.get::<_, String>(9)?, "created_at": r.get::<_, i64>(10)?, "updated_at": r.get::<_, i64>(11)?, "owner_id": r.get::<_, String>(12)?}))
.query_row("SELECT title, author, state, attempts, rounds, last_comment, scenarios, branch, pr_url, note, created_at, updated_at, owner_id, version FROM factory_issues WHERE repo_url = ?1 AND number = ?2", params![repo, number], |r| {
Ok(json!({"repo": repo, "number": number, "title": r.get::<_, String>(0)?, "author": r.get::<_, String>(1)?, "state": r.get::<_, String>(2)?, "attempts": r.get::<_, i64>(3)?, "rounds": r.get::<_, i64>(4)?, "last_comment": r.get::<_, i64>(5)?, "scenarios": r.get::<_, String>(6)?, "branch": r.get::<_, String>(7)?, "pr_url": r.get::<_, String>(8)?, "note": r.get::<_, String>(9)?, "created_at": r.get::<_, i64>(10)?, "updated_at": r.get::<_, i64>(11)?, "owner_id": r.get::<_, String>(12)?, "version": r.get::<_, String>(13)?}))
})
.optional()?)
}
@@ -1482,7 +1499,7 @@ impl Store {
/// Update the given columns (whitelisted) of an issue.
pub fn factory_issue_set(&self, repo: &str, number: i64, fields: &[(&str, Value)]) -> Result<()> {
const COLS: [&str; 10] = ["title", "state", "attempts", "rounds", "last_comment", "scenarios", "branch", "pr_url", "note", "author"];
const COLS: [&str; 11] = ["title", "state", "attempts", "rounds", "last_comment", "scenarios", "branch", "pr_url", "note", "author", "version"];
let conn = self.conn.lock().unwrap();
for (k, v) in fields {
if !COLS.contains(k) {
@@ -1498,6 +1515,54 @@ impl Store {
Ok(())
}
/// Version of a repository, None while versioning has not been started for it.
pub fn factory_version(&self, repo: &str) -> Result<Option<String>> {
Ok(self.conn.lock().unwrap().query_row("SELECT current FROM factory_versions WHERE repo_url = ?1", [repo], |r| r.get(0)).optional()?)
}
pub fn factory_version_set(&self, repo: &str, current: &str) -> Result<()> {
self.conn.lock().unwrap().execute(
"INSERT INTO factory_versions (repo_url, current, since) VALUES (?1, ?2, ?3) ON CONFLICT(repo_url) DO UPDATE SET current = ?2",
params![repo, current, crate::types::now_ms()],
)?;
Ok(())
}
pub fn factory_release_add(&self, id: &str, owner: &str, repo: &str, version: &str) -> Result<()> {
self.conn.lock().unwrap().execute(
"INSERT INTO factory_releases (id, owner_id, repo_url, version, started_at) VALUES (?1,?2,?3,?4,?5)",
params![id, owner, repo, version, crate::types::now_ms()],
)?;
Ok(())
}
/// Append a line to the log of a release (the log is capped).
pub fn factory_release_log(&self, id: &str, line: &str) -> Result<()> {
self.conn.lock().unwrap().execute(
"UPDATE factory_releases SET log = substr(log || ?2 || char(10), -30000) WHERE id = ?1",
params![id, line],
)?;
Ok(())
}
pub fn factory_release_end(&self, id: &str, state: &str, url: &str) -> Result<()> {
self.conn.lock().unwrap().execute("UPDATE factory_releases SET state = ?2, url = ?3, ended_at = ?4 WHERE id = ?1", params![id, state, url, crate::types::now_ms()])?;
Ok(())
}
pub fn factory_release_running(&self, repo: &str) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM factory_releases WHERE repo_url = ?1 AND state = 'running'", [repo], |r| r.get::<_, i64>(0))? > 0)
}
pub fn factory_releases(&self, owner: &str, limit: i64) -> Result<Vec<Value>> {
let conn = self.conn.lock().unwrap();
let mut st = conn.prepare("SELECT id, repo_url, version, state, log, url, started_at, ended_at FROM factory_releases WHERE owner_id = ?1 ORDER BY started_at DESC LIMIT ?2")?;
let rows = st.query_map(params![owner, limit], |r| {
Ok(json!({"id": r.get::<_, String>(0)?, "repo": r.get::<_, String>(1)?, "version": r.get::<_, String>(2)?, "state": r.get::<_, String>(3)?, "log": r.get::<_, String>(4)?, "url": r.get::<_, String>(5)?, "started_at": r.get::<_, i64>(6)?, "ended_at": r.get::<_, Option<i64>>(7)?}))
})?;
Ok(rows.filter_map(|r| r.ok()).collect())
}
pub fn factory_issues(&self, owner: &str) -> Result<Vec<Value>> {
let nums: Vec<(String, i64)> = {
let conn = self.conn.lock().unwrap();
@@ -1548,6 +1613,7 @@ impl Store {
conn.execute("UPDATE factory_issues SET state = 'new' WHERE state = 'review'", [])?;
conn.execute("UPDATE factory_issues SET state = CASE WHEN rounds > 0 THEN 'rework' ELSE 'approved' END WHERE state = 'building'", [])?;
conn.execute("UPDATE factory_issues SET state = 'qa' WHERE state = 'testing'", [])?;
conn.execute("UPDATE factory_releases SET state = 'failed', ended_at = ?1, log = log || char(10) || 'interrupted by a restart' WHERE state = 'running'", [crate::types::now_ms()])?;
// All factory chats live in one sidebar folder (older ones are moved there once).
conn.execute(
"UPDATE sessions SET data = json_set(data, '$.folder', 'Factory') WHERE (json_extract(data, '$.folder') IS NULL OR json_extract(data, '$.folder') = '') AND (id IN (SELECT session_id FROM factory_runs) OR json_extract(data, '$.cwd') LIKE '%/_drafts/%')",
+2 -1
View File
@@ -1,4 +1,4 @@
import { DraftBar, isDraftChat } from "./FactoryDraft";
import { DraftBar, IssueBar, isDraftChat, isIssueChat } from "./FactoryDraft";
import { takePrefill } from "../share";
import { Icon } from "./Icon";
import { FileChip, FileFigure, fileType, imageSize, imageSrc } from "./FileFigure";
@@ -1091,6 +1091,7 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
{sharing && <ShareDialog sessionId={sessionId} onClose={() => setSharing(false)} />}
{rewinding && <RewindDialog sessionId={sessionId} messageId={rewinding.id} onDone={rewindDone} onClose={() => setRewinding(undefined)} />}
{!readOnly && isDraftChat(session.cwd) && <DraftBar sessionId={sessionId} />}
{!readOnly && isIssueChat(session.cwd) && <IssueBar sessionId={sessionId} />}
{!readOnly && <OutboxBar sessionId={sessionId} />}
{!readOnly && <QueueList sessionId={sessionId} busy={busy} />}
{readOnly ? (
+148 -4
View File
@@ -2,10 +2,23 @@ import { useEffect, useMemo, useState } from "react";
import { get, post, put } from "../api";
import { fmtCompact, fmtCost, fmtRelative, useT } from "../i18n";
import { navigate } from "../router";
import { confirmDialog, toast } from "../dialogs";
import { choiceDialog, confirmDialog, promptDialog, toast } from "../dialogs";
import { Icon } from "./Icon";
import { Spinner } from "./Activity";
import { ModelSelect } from "./ModelSelect";
import { ReleaseDialog, ReleasesPanel, type ReleaseRow } from "./FactoryRelease";
interface PrInfo {
number: number;
html_url: string;
title: string;
state: "open" | "merged" | "closed";
mergeable: boolean | null;
changed_files: number | null;
additions: number | null;
deletions: number | null;
head: string;
}
type Phase = "review" | "build" | "qa";
const PHASES: Phase[] = ["review", "build", "qa"];
@@ -15,6 +28,7 @@ interface PhaseCfg {
agent: string;
permission_mode: string;
timeout_minutes: number;
max_attempts: number;
extra_prompt: string;
}
interface RepoCfg {
@@ -24,6 +38,7 @@ interface RepoCfg {
token: string;
label: string;
max_parallel: number;
max_rework: number;
allowed_users: string[];
enabled: boolean;
review: PhaseCfg;
@@ -86,12 +101,14 @@ interface RepoInfo {
has_token: boolean;
models: Record<Phase, string>;
running: number;
version?: string | null;
}
interface Overview {
area: boolean;
repos: RepoInfo[];
issues: Issue[];
runs: Run[];
releases: ReleaseRow[];
}
/** Board columns: a column collects one or more issue states. */
@@ -180,8 +197,71 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
}
};
const [releaseRepo, setReleaseRepo] = useState("");
const startRelease = async () => {
if (!data) return;
let target = repo;
if (!target) {
const repos = data.repos.filter((r) => r.enabled);
if (repos.length === 1) target = repos[0].url;
else {
const pick = await choiceDialog({ message: t("issues.pickRepo"), choices: repos.map((r) => ({ value: r.url, label: repoName(r.url) })) });
if (!pick) return;
target = pick;
}
}
setReleaseRepo(target);
};
/** Start a chat that works out a feature or cuts a milestone into issues. */
const issueChat = async (mode: "feature" | "slice") => {
if (!data) return;
let target = repo;
if (!target) {
const repos = data.repos.filter((r) => r.enabled);
if (repos.length === 1) target = repos[0].url;
else {
const pick = await choiceDialog({ message: t("issues.pickRepo"), choices: repos.map((r) => ({ value: r.url, label: repoName(r.url) })) });
if (!pick) return;
target = pick;
}
}
let topic = "";
if (mode === "slice") {
const name = await promptDialog({ message: t("issues.sliceWhich"), placeholder: "M2", confirmLabel: t("issues.sliceGo") });
if (!name?.trim()) return;
topic = name.trim();
}
setBusy(true);
try {
const s = await post<{ id: string }>("/factory/issue-chats", { repo: target, mode, topic });
navigate(`/s/${s.id}`);
} catch (e: any) {
toast(e.message);
setBusy(false);
}
};
const issues = useMemo(() => (data?.issues ?? []).filter((i) => !repo || i.repo === repo), [data, repo]);
const runs = useMemo(() => (data?.runs ?? []).filter((r) => !repo || r.repo === repo), [data, repo]);
const selected = issues.find((i) => `${i.repo}#${i.number}` === sel);
const [pr, setPr] = useState<PrInfo | null>(null);
const [prMethod, setPrMethod] = useState("merge");
const selKey = selected ? `${selected.repo}#${selected.number}` : "";
const loadPr = async () => {
if (!selected || (!selected.branch && !selected.pr_url)) return setPr(null);
try {
const r = await get<{ pr: PrInfo | null }>(`/factory/issues/pr?repo=${encodeURIComponent(selected.repo)}&number=${selected.number}`);
setPr(r.pr);
} catch {
setPr(null);
}
};
useEffect(() => {
setPr(null);
void loadPr();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selKey, selected?.state]);
if (!data) return <div className="empty"><Spinner /></div>;
if (data.repos.length === 0)
return (
@@ -202,7 +282,6 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
const done = issues.filter((i) => i.state === "done").length;
const failed = issues.filter((i) => ["failed", "rejected"].includes(i.state)).length;
const runsOf = (i: Issue) => data.runs.filter((r) => r.repo === i.repo && r.issue === i.number);
const selected = issues.find((i) => `${i.repo}#${i.number}` === sel);
const shown = selected ? runsOf(selected) : runs.slice(0, 12);
const poll = async () => {
@@ -231,6 +310,20 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
setBusy(false);
}
};
const mergePr = async () => {
if (!selected || !pr) return;
if (!(await confirmDialog({ message: t("factory.mergeConfirm", { n: pr.number, method: t(`factory.merge.${prMethod}` as any) }) }))) return;
setBusy(true);
try {
await post("/factory/issues/pr/merge", { repo: selected.repo, number: selected.number, pr: pr.number, method: prMethod });
toast(t("factory.merged"));
await loadPr();
} catch (e: any) {
toast(e.message);
} finally {
setBusy(false);
}
};
const phaseRunning = !!selected && ["review", "building", "testing"].includes(selected.state);
return (
@@ -277,6 +370,7 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
<button key={r.url} className={`factory-repo ${repo === r.url ? "active" : ""} ${r.enabled ? "" : "off"}`} onClick={() => setRepo(r.url)}>
<b>{repoName(r.url)}</b>
<span className="chip">{KIND_NAME[r.kind] ?? r.kind}</span>
{r.version && <span className="chip ok mono">v{r.version}</span>}
<span className="hint">
{r.running > 0 && <span className="factory-pulse" />}
{t("factory.repoLine", { n: mine.length, run: r.running })}
@@ -289,6 +383,15 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
<button className="small primary" onClick={newProject} disabled={busy}>
<Icon name="plus" /> {t("factory.newProject")}
</button>
<button className="small" onClick={() => issueChat("feature")} disabled={busy} title={t("issues.featureHint")}>
<Icon name="sparkle" /> {t("issues.feature")}
</button>
<button className="small" onClick={() => issueChat("slice")} disabled={busy} title={t("issues.sliceHint")}>
<Icon name="sparkle" /> {t("issues.slice")}
</button>
<button className="small" onClick={startRelease} disabled={busy} title={t("release.hint")}>
<Icon name="download" /> {t("release.button")}
</button>
<button className="small" onClick={poll} disabled={busy} title={t("factory.pollNow")}>
<Icon name="refresh" /> {t("factory.pollNow")}
</button>
@@ -328,6 +431,9 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
})}
</div>
<ReleasesPanel releases={(data.releases ?? []).filter((r) => !repo || r.repo === repo)} />
{releaseRepo && <ReleaseDialog repo={releaseRepo} onClose={() => setReleaseRepo("")} onStarted={() => void reload()} />}
<div className="panel" style={{ marginTop: 16 }}>
<div className="row">
<h3 style={{ margin: 0 }}>{selected ? `${repoName(selected.repo)} #${selected.number} – ${selected.title}` : t("factory.latestRuns")}</h3>
@@ -360,6 +466,36 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
)}
</div>
{selected?.note && <div className="hint" style={{ margin: "6px 0" }}>{selected.note}</div>}
{pr && (
<div className="factory-pr">
<a href={pr.html_url} target="_blank" rel="noreferrer">
<Icon name="external" /> #{pr.number} {pr.title}
</a>
<span className={`chip ${pr.state === "merged" ? "ok" : pr.state === "open" ? "" : "warn"}`}>{t(`factory.pr.${pr.state}` as any)}</span>
{pr.state === "open" && pr.mergeable === false && <span className="chip warn">{t("factory.pr.conflict")}</span>}
{pr.changed_files != null && (
<span className="hint">
{t("factory.pr.files", { n: pr.changed_files })}
{pr.additions != null && ` · +${pr.additions} −${pr.deletions ?? 0}`}
</span>
)}
<span className="spacer" />
{pr.state === "open" && (
<>
<select value={prMethod} onChange={(e) => setPrMethod(e.target.value)} disabled={busy}>
{["merge", "squash", "rebase"].map((m) => (
<option key={m} value={m}>
{t(`factory.merge.${m}` as any)}
</option>
))}
</select>
<button className="small primary" onClick={mergePr} disabled={busy || pr.mergeable === false}>
{t("factory.mergeBtn")}
</button>
</>
)}
</div>
)}
{shown.length === 0 && <div className="hint">{t("factory.noRuns")}</div>}
{shown.length > 0 && (
<div className="table-wrap">
@@ -418,8 +554,8 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
);
}
const blankPhase = (): PhaseCfg => ({ model: "", agent: "codecraft", permission_mode: "auto", timeout_minutes: 60, extra_prompt: "" });
const blankRepo = (connection = "", kind = "gitea"): RepoCfg => ({ url: "", kind, connection, token: "", label: "factory", max_parallel: 1, allowed_users: [], enabled: true, review: blankPhase(), build: blankPhase(), qa: blankPhase() });
const blankPhase = (): PhaseCfg => ({ model: "", agent: "codecraft", permission_mode: "auto", timeout_minutes: 60, max_attempts: 2, extra_prompt: "" });
const blankRepo = (connection = "", kind = "gitea"): RepoCfg => ({ url: "", kind, connection, token: "", label: "factory", max_parallel: 1, max_rework: 2, allowed_users: [], enabled: true, review: blankPhase(), build: blankPhase(), qa: blankPhase() });
const blankConn = (): Connection => ({ id: "", name: "", kind: "gitea", url: "", token: "", owner: "" });
const MODES = ["default", "auto", "accept_edits", "bypass"];
@@ -453,6 +589,10 @@ function PhaseForm({ phase, value, onChange }: { phase: Phase; value: PhaseCfg;
<span>{t("factory.timeout")}</span>
<input type="number" min={1} value={value.timeout_minutes} onChange={(e) => onChange({ timeout_minutes: Number(e.target.value) || 60 })} />
</label>
<label>
<span>{t("factory.attempts")}</span>
<input type="number" min={1} max={10} value={value.max_attempts} title={t("factory.attemptsHint")} onChange={(e) => onChange({ max_attempts: Math.max(1, Number(e.target.value) || 1) })} />
</label>
<label>
<span>{t("factory.extraPrompt")}</span>
<textarea rows={3} value={value.extra_prompt} onChange={(e) => onChange({ extra_prompt: e.target.value })} />
@@ -672,6 +812,10 @@ function FactorySettings() {
<span>{t("factory.parallel")}</span>
<input type="number" min={1} max={4} value={r.max_parallel} onChange={(e) => up(i, { max_parallel: Number(e.target.value) || 1 })} />
</label>
<label>
<span>{t("factory.rework")}</span>
<input type="number" min={0} max={10} value={r.max_rework} title={t("factory.reworkHint")} onChange={(e) => up(i, { max_rework: Math.max(0, Number(e.target.value) || 0) })} />
</label>
<label>
<span>{t("factory.allowed")}</span>
<input value={r.allowed_users.join(", ")} placeholder={t("factory.allowedPlaceholder")} onChange={(e) => up(i, { allowed_users: e.target.value.split(",").map((u) => u.trim()).filter(Boolean) })} />
+129
View File
@@ -183,3 +183,132 @@ function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClos
</div>
);
}
export const isIssueChat = (cwd: string) => /\/_issues\/[^/]+$/.test(cwd);
interface ProposedIssue {
title: string;
description: string;
scope: string;
depends: string;
}
interface IssueProposal {
repo: string;
proposal: { spec?: string; issues: ProposedIssue[] } | null;
}
/** Bar above the composer of an issue chat: file the proposed issues on the forge. */
export function IssueBar({ sessionId }: { sessionId: string }) {
const t = useT();
const [open, setOpen] = useState(false);
return (
<>
<div className="draft-bar">
<Icon name="scroll" />
<span>{t("issues.hint")}</span>
<span className="spacer" />
<button className="small primary" onClick={() => setOpen(true)}>
<Icon name="check" /> {t("issues.create")}
</button>
</div>
{open && <CreateIssuesDialog sessionId={sessionId} onClose={() => setOpen(false)} />}
</>
);
}
function CreateIssuesDialog({ sessionId, onClose }: { sessionId: string; onClose: () => void }) {
const t = useT();
const [data, setData] = useState<IssueProposal>();
const [items, setItems] = useState<(ProposedIssue & { on: boolean })[]>([]);
const [spec, setSpec] = useState("");
const [start, setStart] = useState(false);
const [busy, setBusy] = useState(false);
useEffect(() => {
get<IssueProposal>(`/factory/issue-chats/${sessionId}`)
.then((d) => {
setData(d);
setSpec(d.proposal?.spec ?? "");
setItems((d.proposal?.issues ?? []).map((i) => ({ title: i.title ?? "", description: i.description ?? "", scope: i.scope ?? "", depends: i.depends ?? "", on: true })));
})
.catch((e) => {
toast(e.message);
onClose();
});
}, [sessionId]);
if (!data)
return (
<div className="modal-backdrop">
<div className="modal">
<Spinner />
</div>
</div>
);
const chosen = items.filter((i) => i.on && i.title.trim());
const set = (k: number, patch: Partial<ProposedIssue & { on: boolean }>) => setItems(items.map((x, j) => (j === k ? { ...x, ...patch } : x)));
const create = async () => {
setBusy(true);
try {
const r = await post<{ created: { number: number }[] }>(`/factory/issue-chats/${sessionId}/create`, {
spec,
start,
issues: chosen.map(({ on, ...i }) => i),
});
toast(t("issues.created", { n: r.created.length }), "success");
onClose();
navigate("/factory");
} catch (e: any) {
toast(e.message);
setBusy(false);
}
};
return (
<div className="modal-backdrop" onClick={busy ? undefined : onClose}>
<div className="modal draft-modal" role="dialog" aria-label={t("issues.create")} onClick={(e) => e.stopPropagation()}>
<h3>{t("issues.create")}</h3>
{!data.proposal ? (
<div className="notice err">{t("issues.noProposal")}</div>
) : (
<>
<label className="factory-form" style={{ display: "block" }}>
<span>{t("issues.spec")}</span>
<input className="mono" value={spec} onChange={(e) => setSpec(e.target.value)} />
</label>
<div className="issue-list">
{items.map((i, k) => (
<div key={k} className="issue-item">
<label className="row" style={{ gap: 8 }}>
<input type="checkbox" checked={i.on} onChange={(e) => set(k, { on: e.target.checked })} />
<input style={{ flex: 1 }} value={i.title} onChange={(e) => set(k, { title: e.target.value })} />
</label>
<div className="hint">{i.scope}</div>
{i.depends && i.depends.toLowerCase() !== "none" && <div className="hint">{t("issues.depends", { d: i.depends })}</div>}
<details>
<summary>{t("issues.description")}</summary>
<textarea rows={4} value={i.description} onChange={(e) => set(k, { description: e.target.value })} />
</details>
</div>
))}
</div>
<label className="row" style={{ gap: 8, marginTop: 8 }}>
<input type="checkbox" checked={start} onChange={(e) => setStart(e.target.checked)} />
<span>{t("issues.start")}</span>
</label>
<div className="hint">{t("issues.startHint")}</div>
</>
)}
<div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 12 }}>
<button onClick={onClose} disabled={busy}>
{t("common.cancel")}
</button>
<button className="primary" onClick={create} disabled={!data.proposal || chosen.length === 0 || !spec.trim() || busy}>
{busy ? <Spinner small /> : <Icon name="check" />} {t("issues.createGo", { n: chosen.length })}
</button>
</div>
</div>
</div>
);
}
+136
View File
@@ -0,0 +1,136 @@
import { useEffect, useState } from "react";
import { get, post } from "../api";
import { fmtRelative, useT } from "../i18n";
import { toast } from "../dialogs";
import { Icon } from "./Icon";
import { Spinner } from "./Activity";
export interface ReleaseRow {
id: string;
repo: string;
version: string;
state: "running" | "done" | "failed";
log: string;
url: string;
started_at: number;
ended_at: number | null;
}
interface Preview {
current: string;
suggested: string;
spec: string | null;
running: boolean;
}
const repoName = (url: string) => url.replace(/\.git$/, "").split("/").slice(-2).join("/");
/** Confirm and start a release: version, the recipe that will run, then tag + image + downloads. */
export function ReleaseDialog({ repo, onClose, onStarted }: { repo: string; onClose: () => void; onStarted: () => void }) {
const t = useT();
const [pv, setPv] = useState<Preview>();
const [version, setVersion] = useState("");
const [busy, setBusy] = useState(false);
useEffect(() => {
get<Preview>(`/factory/release/preview?repo=${encodeURIComponent(repo)}`)
.then((p) => {
setPv(p);
setVersion(p.suggested);
})
.catch((e) => {
toast(e.message);
onClose();
});
}, [repo]);
if (!pv)
return (
<div className="modal-backdrop">
<div className="modal">
<Spinner />
</div>
</div>
);
const start = async () => {
setBusy(true);
try {
await post("/factory/release", { repo, version });
toast(t("release.started", { v: version }), "success");
onStarted();
onClose();
} catch (e: any) {
toast(e.message);
setBusy(false);
}
};
return (
<div className="modal-backdrop" onClick={busy ? undefined : onClose}>
<div className="modal draft-modal" role="dialog" aria-label={t("release.title")} onClick={(e) => e.stopPropagation()}>
<h3>
{t("release.title")} – {repoName(repo)}
</h3>
<div className="hint">{t("release.current", { v: pv.current })}</div>
<label className="factory-form" style={{ display: "block", margin: "8px 0" }}>
<span>{t("release.version")}</span>
<input className="mono" value={version} onChange={(e) => setVersion(e.target.value.trim().replace(/^v/, ""))} />
</label>
<div className="notice">{t("release.what")}</div>
{pv.spec ? (
<details open>
<summary>{t("release.recipe")}</summary>
<pre className="draft-spec">{pv.spec}</pre>
<div className="notice err">{t("release.trust")}</div>
</details>
) : (
<div className="hint">{t("release.noRecipe")}</div>
)}
{pv.running && <div className="notice err">{t("release.running")}</div>}
<div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 12 }}>
<button onClick={onClose} disabled={busy}>
{t("common.cancel")}
</button>
<button className="primary" onClick={start} disabled={busy || pv.running || !/^\d+\.\d+\.\d+$/.test(version)}>
{busy ? <Spinner small /> : <Icon name="check" />} {t("release.go", { v: version })}
</button>
</div>
</div>
</div>
);
}
/** The latest releases with their log. */
export function ReleasesPanel({ releases }: { releases: ReleaseRow[] }) {
const t = useT();
if (releases.length === 0) return null;
return (
<div className="panel" style={{ marginTop: 16 }}>
<h3 style={{ margin: "0 0 8px" }}>{t("release.list")}</h3>
{releases.map((r) => (
<details key={r.id} className="release-row" open={r.state === "running"}>
<summary>
<b>
{repoName(r.repo)} v{r.version}
</b>{" "}
<span className={`chip ${r.state === "done" ? "ok" : r.state === "running" ? "" : "warn"}`}>
{r.state === "running" && <span className="factory-pulse" />}
{t(`release.state.${r.state}` as any)}
</span>{" "}
<span className="hint">{fmtRelative(r.started_at)}</span>
{r.url && (
<>
{" "}
<a href={r.url} target="_blank" rel="noreferrer" onClick={(e) => e.stopPropagation()}>
<Icon name="external" />
</a>
</>
)}
</summary>
<pre className="draft-spec">{r.log || "–"}</pre>
</details>
))}
</div>
);
}
+48
View File
@@ -1213,6 +1213,54 @@ export const de: Messages = {
"factory.cost": "Kosten",
"factory.restartAt": "Neu starten bei:",
"factory.restarted": "Issue ist wieder im Ablauf",
"factory.mergeBtn": "Freigeben und mergen",
"factory.mergeConfirm": "Pull Request #{n} mergen ({method})? Die Factory merged nie selbst – das ist deine Freigabe.",
"factory.merged": "Pull Request gemergt",
"factory.merge.merge": "Merge-Commit",
"factory.merge.squash": "Squash",
"factory.merge.rebase": "Rebase",
"factory.pr.open": "offen",
"factory.pr.merged": "gemergt",
"factory.pr.closed": "geschlossen",
"factory.pr.conflict": "Konflikt mit dem Zielbranch",
"factory.pr.files": "{n} Dateien",
"issues.hint": "Wenn der Plan steht, die Issues im Repository anlegen.",
"issues.create": "Issues anlegen",
"issues.createGo": "{n} Issues anlegen",
"issues.created": "{n} Issues angelegt",
"issues.noProposal": "Das Modell hat noch keine Issue-Liste vorgeschlagen. Sag ihm, dass der Plan fertig ist; es schließt dann mit der Liste ab.",
"issues.spec": "Spec-Datei im Repository",
"issues.depends": "Voraussetzung: {d}",
"issues.description": "Beschreibung",
"issues.start": "Sofort starten (Label factory setzen)",
"issues.startHint": "Standardmäßig aus: die Issues werden nur angelegt, das Label setzt du selbst nacheinander – spätere bauen auf den gemergten früheren auf.",
"issues.pickRepo": "Für welches Repository?",
"issues.sliceWhich": "Welcher Meilenstein soll in Deliverables zerlegt werden?",
"issues.sliceGo": "Starten",
"issues.feature": "Feature planen",
"issues.featureHint": "Ein neues Feature mit einem Modell ausarbeiten und daraus Issues anlegen",
"issues.slice": "Meilenstein zerlegen",
"issues.sliceHint": "Ein Modell zerlegt einen Meilenstein in nummerierte Deliverables und legt die Issues an",
"factory.attempts": "Versuche",
"factory.attemptsHint": "Wie oft diese Phase bei technischem Scheitern (Zeitüberschreitung, kein Ergebnis, keine Änderungen) versucht wird, bevor das Issue als fehlgeschlagen gilt",
"factory.rework": "Nachbesserungsrunden",
"factory.reworkHint": "Wie oft eine durchgefallene Abnahme das Issue zurück an den Build schickt (0 = nie, das Issue scheitert sofort)",
"release.button": "Release",
"release.hint": "Release erstellen: Tag, Docker-Image und Downloads",
"release.title": "Release",
"release.current": "Aktuelle Version: v{v}",
"release.version": "Neue Version",
"release.what": "Die Factory schreibt VERSION, baut, was das Rezept beschreibt, pusht den Tag und erstellt das Release auf der Forge mit Quell-ZIP und den Dateien des Rezepts. Das Docker-Image geht in die Registry des Image-Namens.",
"release.recipe": "Release-Rezept (.factory/release.json)",
"release.trust": "Die Befehle in diesem Rezept laufen auf dem Server mit Docker-Zugriff außerhalb der Sandbox. Starte das Release nur, wenn du sie gelesen hast und ihnen vertraust.",
"release.noRecipe": "Keine .factory/release.json auf dem Default-Branch: es werden nur Tag, Release und Quell-ZIP erstellt, kein Docker-Image.",
"release.running": "Für dieses Repository läuft bereits ein Release.",
"release.go": "Release v{v}",
"release.started": "Release v{v} gestartet",
"release.list": "Releases",
"release.state.running": "läuft",
"release.state.done": "fertig",
"release.state.failed": "fehlgeschlagen",
"factory.pr": "Pull Request",
"factory.round": "Runde {n}",
"factory.openChat": "Chat öffnen",
+48
View File
@@ -1212,6 +1212,54 @@ export const en = {
"factory.cost": "Cost",
"factory.restartAt": "Restart at:",
"factory.restarted": "Issue is back in the flow",
"factory.mergeBtn": "Approve and merge",
"factory.mergeConfirm": "Merge pull request #{n} ({method})? The factory itself never merges – this is your approval.",
"factory.merged": "Pull request merged",
"factory.merge.merge": "Merge commit",
"factory.merge.squash": "Squash",
"factory.merge.rebase": "Rebase",
"factory.pr.open": "open",
"factory.pr.merged": "merged",
"factory.pr.closed": "closed",
"factory.pr.conflict": "conflicts with the target branch",
"factory.pr.files": "{n} files",
"issues.hint": "When the plan is done, file the issues on the forge.",
"issues.create": "Create issues",
"issues.createGo": "Create {n} issues",
"issues.created": "{n} issues created",
"issues.noProposal": "The model has not proposed an issue list yet. Tell it that the plan is done; it ends with the list.",
"issues.spec": "Spec file in the repository",
"issues.depends": "Needs first: {d}",
"issues.description": "Description",
"issues.start": "Start right away (set the factory label)",
"issues.startHint": "Off by default: the issues are only created and you set the label yourself, one after the other – later ones build on the merged earlier ones.",
"issues.pickRepo": "For which repository?",
"issues.sliceWhich": "Which milestone should be cut into deliverables?",
"issues.sliceGo": "Start",
"issues.feature": "Plan a feature",
"issues.featureHint": "Work out a new feature with a model and create issues from it",
"issues.slice": "Cut a milestone",
"issues.sliceHint": "Let a model cut a milestone into numbered deliverables and create the issues",
"factory.attempts": "Tries",
"factory.attemptsHint": "How often this phase is tried when it fails technically (timeout, no result, no changes) before the issue is marked failed",
"factory.rework": "Rework rounds",
"factory.reworkHint": "How often a failed acceptance sends the issue back to the build (0 = never, the issue fails right away)",
"release.button": "Release",
"release.hint": "Make a release: tag, Docker image and downloads",
"release.title": "Release",
"release.current": "Current version: v{v}",
"release.version": "New version",
"release.what": "The factory writes VERSION, builds what the recipe describes, pushes the tag and creates the release on the forge with the source zip and the files of the recipe. The Docker image goes to the registry of the image name.",
"release.recipe": "Release recipe (.factory/release.json)",
"release.trust": "The commands in this recipe run on the server with Docker access, outside the sandbox. Only start the release if you have read and trust them.",
"release.noRecipe": "No .factory/release.json on the default branch: only the tag, the release and the source zip are made, no Docker image.",
"release.running": "A release of this repository is already running.",
"release.go": "Release v{v}",
"release.started": "Release v{v} started",
"release.list": "Releases",
"release.state.running": "running",
"release.state.done": "done",
"release.state.failed": "failed",
"factory.pr": "Pull request",
"factory.round": "round {n}",
"factory.openChat": "Open chat",
+30
View File
@@ -5170,3 +5170,33 @@ td.fold-indent {
padding: 8px;
font-size: 12px;
}
.factory-pr {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
padding: 8px 0 12px;
}
.issue-list {
display: flex;
flex-direction: column;
gap: 8px;
max-height: 46vh;
overflow: auto;
margin-top: 8px;
}
.issue-item {
border: 1px solid var(--border);
border-radius: 8px;
padding: 8px;
}
.issue-item textarea {
width: 100%;
}
.release-row {
border-top: 1px solid var(--border);
padding: 6px 0;
}
+12
View File
@@ -3,6 +3,18 @@
* under "unreleased"; scripts/release.sh renames the key to the release version.
*/
export const WHATS_NEW: Record<string, { en: string[]; de: string[] }> = {
"202611-00049": {
en: ["Factory: every merged issue gets a version and a git tag (patch per issue, minor per finished milestone)", "Factory: start a release with Docker image (amd64 + arm64), downloads and a release on the forge", "Factory: set the number of rework rounds and tries per phase"],
de: ["Factory: jedes gemergte Issue bekommt eine Version und einen Git-Tag (Patch je Issue, Minor je abgeschlossenem Meilenstein)", "Factory: Release mit Docker-Image (amd64 + arm64), Downloads und Release auf der Forge anstoßen", "Factory: Anzahl der Nachbesserungsrunden und Versuche je Phase einstellbar"],
},
"202611-00048": {
en: ["Fixed: the factory page was blank"],
de: ["Behoben: die Factory-Seite blieb leer"],
},
"202611-00047": {
en: ["Factory: see an issue's pull request and approve/merge it right in the factory page", "Factory: plan a feature with a model or cut a milestone into numbered deliverables – the issues are created for you"],
de: ["Factory: Pull Request eines Issues ansehen und direkt in der Factory freigeben/mergen", "Factory: Feature mit einem Modell planen oder einen Meilenstein in nummerierte Deliverables zerlegen – die Issues werden für dich angelegt"],
},
"202611-00044": {
en: ["Factory: the pull request is now opened by the acceptance, after it passed", "Factory has its own icon and all its chats sit in one sidebar folder", "Factory acceptance only judges the scenarios in the issue's scope"],
de: ["Factory: den Pull Request erstellt jetzt die Abnahme, nachdem sie bestanden ist", "Die Factory hat ein eigenes Icon, alle ihre Chats liegen in einem Ordner in der Seitenleiste", "Die Factory-Abnahme beurteilt nur die Szenarien im Umfang des Issues"],