Compare commits

..
Author SHA1 Message Date
Richard Zink d8c5a0bf0e Release v202611-00058 2026-11-17 15:05:22 +01:00
Richard ZinkandClaude Sonnet 5.5 dad2685ea3 Skills labels without plural problems
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 15:05:21 +01:00
Richard Zink 84ee68d4da Release v202611-00057 2026-11-17 14:43:39 +01:00
Richard ZinkandClaude Sonnet 5.5 43b07aca48 Factory: skills per phase
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 14:43:38 +01:00
Richard Zink 0fd10df43d Release v202611-00056 2026-11-17 14:28:14 +01:00
Richard ZinkandClaude Sonnet 5.5 a84a3acaa0 Skills: manage and import your own, switch on per chat, search instead of listing
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 14:28:13 +01:00
Richard Zink e150de3c93 Release v202611-00055 2026-11-17 14:05:16 +01:00
Richard ZinkandClaude Sonnet 5.5 a0c95a035c New project: preselect the workspace, label the factory folder
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 14:05:15 +01:00
Richard Zink 843194b429 Release v202611-00054 2026-11-17 13:37:17 +01:00
Richard ZinkandClaude Sonnet 5.5 462171f27b README: explain the code factory
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 13:37:16 +01:00
Richard Zink 18818c1bd4 Release v202611-00053 2026-11-17 07:03:34 +01:00
Richard ZinkandClaude Sonnet 5.5 d644c97dd9 Changelog: unreleased entry
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 07:03:34 +01:00
Richard ZinkandClaude Sonnet 5.5 0a724142ff Factory: read the current version from the remote tags
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 06:58:14 +01:00
Richard Zink 18aa63e3e6 Release v202611-00052 2026-11-17 06:19:05 +01:00
Richard ZinkandClaude Sonnet 5.5 dd3dd48969 Factory: fix versioning (null pull_request hid open issues)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 06:19:03 +01:00
Richard Zink e66574b529 Release v202611-00051 2026-11-16 13:41:59 +01:00
Richard ZinkandClaude Sonnet 5.5 df02556132 Factory: close finished issues, Done column on the right
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 13:41:58 +01:00
Richard Zink fcbc052f8e Release v202611-00050 2026-11-16 13:21:35 +01:00
Richard ZinkandClaude Sonnet 5.5 fa6173d224 Factory: no review loop in planning chats
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 13:21:34 +01:00
Richard Zink a9a98a25e7 Release v202611-00049 2026-11-16 12:44:35 +01:00
Richard ZinkandClaude Sonnet 5.5 cb1e31b6e9 Factory: versions and tags, releases, retry settings, pull of the default branch
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 12:44:35 +01:00
28 changed files with 2360 additions and 50 deletions

No files matched your search

+98
View File
@@ -3,6 +3,104 @@
All notable changes to CodeCraft. Versions follow [Semantic Versioning](https://semver.org/);
until 1.0, minor versions may contain breaking changes.
## [v202611-00058] – 2026-11-17
### Changed
- **README and screenshots** brought up to date (code factory, skills, new interface); skills labels no longer say "1 files".
## [v202611-00057] – 2026-11-17
### Added
- **Factory: skills per phase.** In the repository settings, each phase (review, build, acceptance) can have
skills switched on; the chat of that phase follows them in every turn.
## [v202611-00056] – 2026-11-17
### Added
- **Skills you manage yourself.** *Settings → Skills*: create skills (a folder with `SKILL.md` and further
files) in an editor, or import them from a GitHub repository or folder – every folder with a `SKILL.md` is
offered, with a filter and multi-select. They are stored per user.
- **Skills per chat.** Switch skills on for a chat (menu ⋯ → *Skills for this chat*): their full instructions
are part of every turn. All other skills cost no context: up to 12 skills are listed by name in the prompt, a
larger library is not listed at all – the agent finds a skill with `skill(query=…)` and reads its further
files with `skill(name, file)`.
## [v202611-00055] – 2026-11-17
### Fixed
- **New project from a Git repository:** the wizard no longer clones into the factory area by default
("target folder already exists" when the factory had checked out the same repository); your workspace is
preselected, and the factory area is labelled as such in the folder list.
## [v202611-00053] – 2026-11-17
### Fixed
- **Factory versioning.** The current version is read from the tags on the forge, not from the checkout
(which kept tags that were deleted there and so counted from a stale version).
## [v202611-00054] – 2026-11-17
### Changed
- **README:** new "Code factory" section explaining phases, scope, planning chats, versions and releases.
## [v202611-00052] – 2026-11-17
### Fixed
- **Factory versioning.** Open issues of the forge were never seen (Gitea sends `"pull_request": null`), so every
deliverable counted as the last of its milestone and raised the minor version. Now only the last open issue of a
milestone raises the minor version; all others raise the patch version.
## [v202611-00051] – 2026-11-16
### Added
- **Factory: close finished issues.** A finished issue has a "Close issue" button: you write a comment, it is
posted on the issue on the forge, the issue is closed there, and only then it leaves the "Done" column.
Issues that are closed on the forge by other means (or by the version pass after the merge) leave "Done" too.
### Changed
- The "Done" column is now the rightmost column of the factory board.
## [v202611-00050] – 2026-11-16
### Fixed
- The factory's planning chats (spec chat, "Plan a feature", "Cut a milestone") no longer run the review loop
of the agent mode (the "refine" rounds of build mode), which checked their answers as if they were code.
## [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
+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
+86 -1
View File
@@ -11,7 +11,7 @@
</p>
<p align="center">
<img alt="Version v202611-00048" src="https://img.shields.io/badge/version-v202611--00048-d69e2e?style=flat-square">
<img alt="Version v202611-00058" src="https://img.shields.io/badge/version-v202611--00058-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">
@@ -25,6 +25,7 @@
<a href="#models">Models</a> ·
<a href="#terminal-client">Terminal client</a> ·
<a href="#automations">Automations</a> ·
<a href="#code-factory">Code factory</a> ·
<a href="#integrations">Integrations</a> ·
<a href="#users-and-security">Users</a> ·
<a href="#statistics">Statistics</a> ·
@@ -219,6 +220,90 @@ read and continue it.
**Webhooks** start an automation from outside, e.g. on every push: the request is checked with a
shared secret or a Gitea/GitHub HMAC signature, and its JSON payload is handed to the agent.
## Code factory
The factory turns issues on your Git forge (Gitea, GitHub or GitLab) into reviewed, built, accepted and
merged changes – with agents doing the work and you deciding at the points that matter. It is
the **Factory** page in the sidebar; all chats it creates live in the sidebar folder *Factory*.
```
issue + label "factory"
│
▼
review ──► question (the agent asks in the issue; you answer, it continues)
│ └──► rejected (not buildable as written)
▼
approved ──► building ──► qa (acceptance) ──► done ──► PR merged ──► version + tag ──► closed
▲ │
└── rework ◄──┘ (up to N rounds, then failed)
```
**Phases.** Each phase is a normal CodeCraft chat in the sandbox, so you can open and read it.
The agent's answer ends with a JSON result that the factory parses; everything else is done by
the server.
1. **Review.** An agent reads the issue and the repository and decides: *approved*, *question*
(it comments in the issue and waits for your reply) or *rejected*. It also writes acceptance
scenarios. The scenarios are stored in the factory database and are **never shown to the
builder**, so the build cannot be tuned to the test.
2. **Build.** The builder works in its own git worktree on the branch `factory/issue-<n>`.
The server – not the agent – commits, pushes (never forced) and restores the spec file.
3. **Acceptance.** A different agent checks the pushed branch in a clean checkout against the
scenarios, using the repository's `.factory/setup.json` to build and start the app. Each
scenario ends as `pass`, `fail`, `unverified` or `out_of_scope`; the verdict comes from these
results, not from the model's opinion, and a run without any pass or fail counts as failed.
On *pass* the factory opens the pull request (if none is open) and comments a result table
in the issue. On *fail* the issue goes back to the build with the findings (*rework*).
4. **Done, merge, version.** You review the pull request in the factory (diff, description) and
merge it there. The factory then pulls the merge, gives the issue its version, commits
`VERSION`, pushes an annotated tag, comments on the issue and closes it.
Issue text is treated as data, never as instructions for the factory itself.
**Scope.** An issue body can contain `Spec: <file>` and `Scope: <deliverable>` lines. Review,
build and acceptance then restrict themselves to that deliverable, so a big specification is
built in small steps instead of one huge run. Without a `Scope:` line the review picks the
first unbuilt milestone of the spec. `Prerequisite:` lines name what must be merged first.
**Planning with a model.** Three chats help you create issues, without the usual review loop:
- **Spec chat** (*New project*): works out a specification with you and creates the repository
with `docs/specs/<name>.md`, the factory setup and the first issues.
- **Plan a feature**: you describe a feature or a bug; the model asks questions and ends with a
list of issues (title, description, scope, prerequisites).
- **Cut a milestone**: the model splits a milestone of the spec into numbered deliverables
(`M2.1 – …`).
*Create issues* shows the proposal for editing and files the issues on the forge. They get the
`factory` label only if you tick *Start right away*; by default you set the label yourself,
one after the other, because later issues build on the merged earlier ones.
**Versions and releases.** Every issue that is merged raises the version of the repository
(starting from the highest `vX.Y.Z` tag): a deliverable of a milestone raises the **patch**
number (0.0.1, 0.0.2, …); the **last** open deliverable of a milestone (`M<k>.<n>`) raises the
**minor** number and resets the patch (M1 complete → 0.1.0). Issues without a milestone
(bugs, features) raise the patch number. The factory writes the `VERSION` file, pushes the tag
`vX.Y.Z` and closes the issue. The **Release** button turns the current version into a
release, e.g. 0.x → 1.0.0: it builds what the repository's `.factory/release.json` describes
(Docker image for amd64 and arm64 pushed to your registry, a source zip, extra files by glob,
shell commands), tags it and creates the release on the forge with notes from the git log and
the files attached (Gitea and GitHub).
**Settings per repository** (*Factory → Repositories*, *New repository*): forge connection and token, label
(default `factory`), parallel runs, allowed issue authors (default: the token's owner), and per
phase the model, agent (CodeCraft or Claude Code), permission mode, timeout and tries on
technical failures, plus the number of rework rounds (default 2). Failed or rejected issues
can be restarted from the board, finished ones are closed with a comment.
**Files in the repository** (all optional, kept in `.factory/`):
| File | Purpose |
|---|---|
| `setup.json` | How acceptance installs and starts the app: `install`, `start`, `url` |
| `release.json` | Recipe for releases: image, platforms, Dockerfile, build args, commands, files |
Repositories are cloned into a separate factory area, not into your workspace, and agents never see the forge API token.
## Integrations
- **Telegram:** connect your own bot (*Settings → Account → Telegram*) and use CodeCraft from
+3
View File
@@ -196,6 +196,9 @@ pub struct Session {
/// Icon of the chat (a name from `SESSION_ICONS`), shown in the list and the top bar.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
/// Skills the user switched on for this chat: their instructions are part of every turn.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub skills: Vec<String>,
}
/// Names of the colour tags: the client draws them with the colours of the active theme.
+79 -5
View File
@@ -72,6 +72,10 @@ pub fn router(app: AppState) -> Router {
.route("/agents/tools", get(agent_tools))
.route("/agents/{name}", delete(delete_agent))
.route("/commands", get(commands))
.route("/skills", get(crate::skills_api::list))
.route("/skills/github/scan", post(crate::skills_api::scan))
.route("/skills/github/import", post(crate::skills_api::import))
.route("/skills/{name}", get(crate::skills_api::get).put(crate::skills_api::put).delete(crate::skills_api::delete))
.route("/transcribe", post(transcribe))
.route("/sessions", get(list_sessions).post(create_session))
.route("/sessions/search", get(search_sessions))
@@ -167,6 +171,9 @@ pub fn router(app: AppState) -> Router {
.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/close", post(factory_close_issue))
.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))
@@ -529,7 +536,7 @@ async fn commands(Extension(user): Extension<User>, State(app): State<AppState>,
let (root, cwd) = scope(&app, &user, q.cwd);
Json(json!({
"commands": prompts::commands(&app, &root, &cwd),
"skills": prompts::skills(&app, &root, &cwd),
"skills": prompts::skills(&app, &root, &cwd, Some(&user.id)),
}))
}
@@ -673,6 +680,7 @@ async fn create_session(Extension(user): Extension<User>, State(app): State<AppS
summary: String::new(),
color: dstr("color").filter(|c| codecraft_core::types::SESSION_COLORS.contains(&c.as_str())),
icon: dstr("icon").filter(|c| codecraft_core::types::SESSION_ICONS.contains(&c.as_str())),
skills: Vec::new(),
};
let s = app.save_session(s)?;
Ok(Json(json!(s)))
@@ -970,6 +978,8 @@ struct UpdateSession {
color: Option<String>,
/// Icon ("" removes it).
icon: Option<String>,
/// Skills switched on for this chat (names).
skills: Option<Vec<String>>,
}
async fn update_session(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>, Json(body): Json<UpdateSession>) -> ApiResult {
@@ -1033,6 +1043,15 @@ async fn update_session(Extension(user): Extension<User>, State(app): State<AppS
if let Some(i) = body.icon {
s.icon = (!i.is_empty()).then_some(i);
}
if let Some(list) = body.skills {
let mut seen = Vec::new();
for n in list.into_iter().map(|n| n.trim().to_string()).filter(|n| !n.is_empty() && n.len() <= 64) {
if !seen.contains(&n) && seen.len() < 20 {
seen.push(n);
}
}
s.skills = seen;
}
})?;
Ok(Json(json!(s)))
}
@@ -1827,8 +1846,13 @@ async fn list_roots(Extension(user): Extension<User>, State(app): State<AppState
.user_roots(Some(&user.id))
.into_iter()
.map(|r| {
let rel = r.strip_prefix(&ws).map(|p| p.display().to_string()).unwrap_or_default();
json!({"path": r, "name": if rel.is_empty() { "/".to_string() } else { rel }})
let name = match r.strip_prefix(&ws) {
Ok(p) if p.as_os_str().is_empty() => "/".to_string(),
Ok(p) => p.display().to_string(),
// Outside the workspace (e.g. the factory area): show where it is, not "workspace".
Err(_) => format!("{} (factory)", r.file_name().and_then(|n| n.to_str()).unwrap_or("")).replace(" ()", ""),
};
json!({"path": r, "name": name})
})
.collect();
Json(json!(roots))
@@ -2428,7 +2452,7 @@ async fn job_assistant(Extension(user): Extension<User>, State(app): State<AppSt
telegram_quiet: true,
summary: String::new(),
color: None,
icon: None,
icon: None, skills: Vec::new(),
};
let s = app.save_session(s)?;
st.assistant_session = Some(s.id.clone());
@@ -2637,12 +2661,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)?,
})))
}
@@ -2658,6 +2683,32 @@ 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,
@@ -2723,6 +2774,29 @@ async fn factory_create_issues(Extension(user): Extension<User>, State(app): Sta
Ok(Json(json!({"created": created})))
}
#[derive(Deserialize)]
struct CloseIssue {
repo: String,
number: i64,
#[serde(default)]
comment: String,
}
/// Close a finished issue: a comment, then the issue on the forge; only then it leaves "done".
async fn factory_close_issue(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<CloseIssue>) -> ApiResult {
let (g, row) = factory_issue_forge(&app, &user, &b.repo, b.number)?;
if row["state"].as_str() != Some("done") {
return Err(ApiError(StatusCode::BAD_REQUEST, "only finished issues can be closed here".into()));
}
let bad = |e: anyhow::Error| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}"));
let text = if b.comment.trim().is_empty() { "Closed.".to_string() } else { b.comment.trim().to_string() };
g.comment(b.number as u64, &format!("{}\n**Closed** by {}: {text}", crate::factory::BOT, user.username)).await.map_err(bad)?;
g.close_issue(b.number as u64).await.map_err(bad)?;
app.store.factory_issue_set(&b.repo, b.number, &[("state", json!("closed"))])?;
app.audit(Some(&user), "factory.issue.close", &format!("{}#{}", b.repo, b.number), &crate::auth::client_ip(&headers));
Ok(Json(json!({"ok": true})))
}
#[derive(Deserialize)]
struct PrQuery {
repo: String,
+2 -2
View File
@@ -36,7 +36,7 @@ pub async fn config(Extension(user): Extension<User>, State(app): State<AppState
.filter(|c| c.description.len() < 400)
.map(|c| json!({"name": c.name, "description": c.description, "body": c.body, "agent": c.agent}))
.collect();
let skills: Vec<Value> = crate::prompts::skills(&app, &root, &root).into_iter().map(|s| json!({"name": s.name, "description": s.description})).collect();
let skills: Vec<Value> = crate::prompts::skills(&app, &root, &root, Some(&user.id)).into_iter().map(|s| json!({"name": s.name, "description": s.description})).collect();
let (direct, deferred) = app.mcp.tools(&cfg, Some(&user));
let mut mcp_tools: Vec<ToolDef> = direct.iter().map(|t| t.def()).collect();
if !deferred.is_empty() {
@@ -69,7 +69,7 @@ pub async fn config(Extension(user): Extension<User>, State(app): State<AppState
/// A server skill with its supporting text files (templates).
pub async fn skill(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>) -> ApiResult {
let root = app.user_roots(Some(&user.id)).into_iter().next().unwrap_or_else(|| app.workspace());
let sk = crate::prompts::skills(&app, &root, &root).into_iter().find(|s| s.name == name).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "skill not found".into()))?;
let sk = crate::prompts::skills(&app, &root, &root, Some(&user.id)).into_iter().find(|s| s.name == name).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "skill not found".into()))?;
let dir = sk.path.parent().map(PathBuf::from).unwrap_or_default();
let content = std::fs::read_to_string(&sk.path)?;
let mut files = Vec::new();
+162 -16
View File
@@ -43,9 +43,15 @@ 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,
/// Skills (names) switched on for the chat of this phase; only the CodeCraft agent uses them.
#[serde(default)]
pub skills: Vec<String>,
}
fn default_agent() -> String {
@@ -57,10 +63,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(), skills: Vec::new() }
}
}
@@ -101,6 +113,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 +162,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 +173,8 @@ 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);
p.skills = p.skills.iter().map(|n| n.trim().to_string()).filter(|n| !n.is_empty() && n.len() <= 64).take(10).collect();
}
Ok(())
}
@@ -504,6 +522,94 @@ 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").map_or(true, |p| p.is_null()) {
continue;
}
out.push((i[key].as_i64().unwrap_or(0), i["title"].as_str().unwrap_or("").to_string()));
}
if n < 50 {
break;
}
}
Ok(out)
}
/// Is the issue still open on the forge?
pub async fn issue_is_open(&self, number: u64) -> Result<bool> {
let v = self.call(reqwest::Method::GET, self.rp(&format!("/issues/{number}")), None).await?;
Ok(!matches!(v["state"].as_str(), Some("closed")))
}
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 {
@@ -634,7 +740,7 @@ fn urlenc(s: &str) -> String {
// --- engine -----------------------------------------------------------------------
/// The marker with which every bot comment starts (the poller ignores these when it looks for answers).
const BOT: &str = "<!-- codecraft-factory -->";
pub(crate) const BOT: &str = "<!-- codecraft-factory -->";
/// Machine-readable result at the end of a phase: the last fenced ```json block, else the last
/// top-level object in the text. Needs a "decision" field.
@@ -655,7 +761,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)
}
@@ -731,6 +837,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)?;
@@ -776,6 +886,7 @@ fn start_phase(app: &Arc<App>, user: &User, cfg: &RepoCfg, issue: i64, phase: &s
summary: String::new(),
color: None,
icon: None,
skills: pc.skills.clone(),
};
let session = app.save_session(session)?;
let run_id = crate::types::new_id();
@@ -801,7 +912,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:#}");
}
@@ -817,6 +928,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) {
@@ -941,7 +1056,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;
@@ -1022,8 +1137,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!(
@@ -1052,7 +1166,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;
@@ -1126,16 +1240,16 @@ 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;
}
@@ -1162,7 +1276,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;
@@ -1171,7 +1285,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;
}
@@ -1231,6 +1345,18 @@ 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));
}
// Accepted issues that were closed on the forge (by hand or by the factory) leave the "done" column.
let open: Vec<i64> = g.issues(&cfg.label).await.unwrap_or_default().iter().map(issue_no).collect();
for row in app.store.factory_issues(&user.id)?.into_iter().filter(|r| r["repo"].as_str() == Some(cfg.url.as_str()) && r["state"].as_str() == Some("done")) {
let n = issue_no(&row);
if !open.contains(&n) && !g.issue_is_open(n as u64).await.unwrap_or(true) {
app.store.factory_issue_set(&cfg.url, n, &[("state", json!("closed"))])?;
}
}
// 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(())
}
@@ -1341,7 +1467,7 @@ pub async fn start_issue_chat(app: &Arc<App>, user: &User, cfg: &RepoCfg, model:
telegram_quiet: true,
summary: String::new(),
color: None,
icon: None,
icon: None, skills: Vec::new(),
};
app.save_session(session)
}
@@ -1422,6 +1548,16 @@ pub fn draft_of(app: &App, user: &User, session: &crate::types::Session) -> Opti
(session.owner_id.as_deref() == Some(&user.id) && cwd.starts_with(&home) && cwd != home).then_some(cwd)
}
/// Is this a planning chat of the factory (spec chat in `_drafts`, issue chat in `_issues`)? They produce
/// text, not code, so the review loop of the agent mode is switched off for them.
pub fn is_planning_chat(app: &App, session: &crate::types::Session) -> bool {
app.factory_dir().is_some_and(|dir| is_planning_path(&dir, std::path::Path::new(&session.cwd)))
}
fn is_planning_path(factory: &std::path::Path, cwd: &std::path::Path) -> bool {
cwd.strip_prefix(factory).map(|rel| rel.components().any(|c| c.as_os_str() == "_drafts" || c.as_os_str() == "_issues")).unwrap_or(false)
}
/// Start a spec chat with the given model.
pub fn start_spec_chat(app: &Arc<App>, user: &User, model: &str) -> Result<crate::types::Session> {
let id = crate::types::new_id();
@@ -1452,7 +1588,7 @@ pub fn start_spec_chat(app: &Arc<App>, user: &User, model: &str) -> Result<crate
telegram_quiet: true,
summary: String::new(),
color: None,
icon: None,
icon: None, skills: Vec::new(),
};
app.save_session(session)
}
@@ -1697,6 +1833,16 @@ mod tests {
assert!(parse_result(t).is_some_and(|v| v["decision"] == "issues"));
}
#[test]
fn planning_chats_are_recognised_by_their_folder() {
let f = std::path::Path::new("/factory");
assert!(is_planning_path(f, std::path::Path::new("/factory/zink/_drafts/abc")));
assert!(is_planning_path(f, std::path::Path::new("/factory/zink/_issues/abc")));
assert!(!is_planning_path(f, std::path::Path::new("/factory/zink/zink/dunkelfeld")));
assert!(!is_planning_path(f, std::path::Path::new("/factory/zink/zink/_work/dunkelfeld-1")));
assert!(!is_planning_path(f, std::path::Path::new("/workspace/_drafts/x")));
}
#[test]
fn encodes_labels() {
assert_eq!(urlenc("factory:qa"), "factory%3Aqa");
+617
View File
@@ -0,0 +1,617 @@
//! 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 {
// The remote is the truth: a local checkout keeps tags that were deleted on the forge.
let remote = git(cfg, dir, &["ls-remote", "--tags", "--refs", "origin", "v[0-9]*"]).await;
let names: Vec<String> = match remote {
Ok(out) => out.lines().filter_map(|l| l.split("refs/tags/").nth(1)).map(str::to_string).collect(),
Err(_) => {
let _ = git(cfg, dir, &["fetch", "--tags", "--force", "origin"]).await;
git(cfg, dir, &["tag", "-l", "v[0-9]*"]).await.unwrap_or_default().lines().map(str::to_string).collect()
}
};
names.iter().filter_map(|t| parse_version(t)).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| matches!(r["state"].as_str(), Some("done") | Some("closed")) && r["version"].as_str() == Some("") && !r["pr_url"].as_str().unwrap_or("").is_empty();
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(|r| matches!(r["state"].as_str(), Some("done") | Some("closed")) && r["version"].as_str() == Some("")) {
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())), ("state", json!("closed"))])?;
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 -1
View File
@@ -335,7 +335,7 @@ pub async fn run_with(app: &Arc<App>, job: &Job, trigger: &str, payload: Option<
telegram_quiet: true,
summary: String::new(),
color: None,
icon: None,
icon: None, skills: Vec::new(),
};
let session = app.save_session(session)?;
app.store.job_started(&job.id, &session.id, now)?;
+2
View File
@@ -14,6 +14,7 @@ mod digest;
mod docs;
mod export;
mod factory;
mod factory_version;
mod files;
mod git;
mod health;
@@ -34,6 +35,7 @@ mod push;
mod provider;
mod reverse;
mod runner;
mod skills_api;
mod sandbox;
mod shells;
mod sshkeys;
+1 -1
View File
@@ -211,7 +211,7 @@ mod tests {
let session = crate::types::Session {
id: crate::types::new_id(), title: String::new(), cwd: dir.join("ws").display().to_string(), model: "x/y".into(), agent: "build".into(), permission_mode: "bypass".into(),
parent_id: None, owner_id: None, created_at: now, updated_at: now, todos: Value::Null, last_usage: None, clean_room: None, phase: None, worktree: None,
pinned: false, archived: false, folder: None, instructions: String::new(), telegram_quiet: true, summary: String::new(), color: None, icon: None,
pinned: false, archived: false, folder: None, instructions: String::new(), telegram_quiet: true, summary: String::new(), color: None, icon: None, skills: Vec::new(),
};
let session = app.save_session(session).unwrap();
let reg = register(&session.id);
+122 -12
View File
@@ -285,11 +285,16 @@ pub fn system_prompt(app: &App, agent: &Agent, root: &Path, cwd: &Path, model: &
s.push_str(&format!("- {server} ({n} tools, e.g. {})\n", names.join(", ")));
}
}
let skills = skills(app, root, cwd);
let skills = skills(app, root, cwd, owner.map(|u| u.id.as_str()));
if !skills.is_empty() {
s.push_str("\n# Skills\nLoad a skill with the skill tool when the task matches its description:\n");
for sk in &skills {
s.push_str(&format!("- {}: {}\n", sk.name, sk.description));
if skills.len() <= SKILL_LIST_MAX {
s.push_str("\n# Skills\nLoad a skill with the skill tool when the task matches its description:\n");
for sk in &skills {
s.push_str(&format!("- {}: {}\n", sk.name, sk.description.chars().take(160).collect::<String>()));
}
} else {
// A large library must not fill the context: only the count; the agent searches on demand.
s.push_str(&format!("\n# Skills\n{} skills (packaged instructions for kinds of task) are available but not listed. Find one with the skill tool (query=<keywords>), then load it with name=<skill>.\n", skills.len()));
}
}
if let Some(u) = owner {
@@ -381,23 +386,91 @@ pub struct Skill {
pub name: String,
pub description: String,
pub path: PathBuf,
/// Further files of the skill (relative paths, without SKILL.md).
pub files: Vec<String>,
/// Created by the user in the UI (editable there).
pub user: bool,
}
pub fn skills(app: &App, root: &Path, cwd: &Path) -> Vec<Skill> {
/// Where a user's own skills live: `<data>/user-skills/<user id>/<name>/SKILL.md` (+ more files).
pub fn user_skills_dir(app: &App, owner_id: &str) -> PathBuf {
app.data_dir().join("user-skills").join(owner_id)
}
/// Relative paths of all files below `dir` (depth <= 5, at most 200), without `SKILL.md` at the top.
pub fn skill_files(dir: &Path) -> Vec<String> {
fn walk(base: &Path, dir: &Path, depth: usize, out: &mut Vec<String>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for e in entries {
if out.len() >= 200 {
return;
}
let p = e.path();
let Ok(ty) = e.file_type() else { continue };
if ty.is_dir() && depth < 5 {
walk(base, &p, depth + 1, out);
} else if ty.is_file() {
if let Ok(rel) = p.strip_prefix(base) {
let rel = rel.to_string_lossy().to_string();
if rel != "SKILL.md" {
out.push(rel);
}
}
}
}
}
let mut out = Vec::new();
walk(dir, dir, 0, &mut out);
out
}
pub fn skills(app: &App, root: &Path, cwd: &Path, owner_id: Option<&str>) -> Vec<Skill> {
let mut map = BTreeMap::new();
for dir in resource_dirs(app, root, cwd, "skills") {
let mut dirs: Vec<(PathBuf, bool)> = resource_dirs(app, root, cwd, "skills").into_iter().map(|d| (d, false)).collect();
if let Some(id) = owner_id {
dirs.push((user_skills_dir(app, id), true));
}
for (dir, user) in dirs {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for e in entries.flatten() {
let p = e.path().join("SKILL.md");
let Ok(text) = std::fs::read_to_string(&p) else { continue };
let (meta, _) = frontmatter(&text);
let name = meta.get("name").cloned().unwrap_or_else(|| e.file_name().to_string_lossy().into());
map.insert(name.clone(), Skill { name, description: meta.get("description").cloned().unwrap_or_default(), path: p });
map.insert(name.clone(), Skill { name, description: meta.get("description").cloned().unwrap_or_default(), files: skill_files(&e.path()), path: p, user });
}
}
map.into_values().collect()
}
/// Adds the skills the user switched on for this chat: their full instructions are part of every turn.
pub fn with_active_skills(app: &App, mut system: String, active: &[String], root: &Path, cwd: &Path, owner_id: Option<&str>) -> String {
if active.is_empty() {
return system;
}
let all = skills(app, root, cwd, owner_id);
let mut block = String::new();
for name in active {
let Some(sk) = all.iter().find(|s| &s.name == name) else { continue };
let Ok(text) = std::fs::read_to_string(&sk.path) else { continue };
let (_, body) = frontmatter(&text);
let body: String = body.chars().take(40_000).collect();
block.push_str(&format!("\n## Skill: {}\n{}\n", sk.name, body.trim()));
if !sk.files.is_empty() {
block.push_str(&format!("\nFurther files of this skill (read them with the skill tool: name=\"{}\", file=<path>): {}\n", sk.name, sk.files.join(", ")));
}
}
if !block.is_empty() {
system.push_str(&format!("\n\n# Active skills\nThe user switched these skills on for this chat. Follow them for every task they cover.\n{block}"));
}
system
}
/// More skills than this are not listed in the system prompt (the agent searches instead).
const SKILL_LIST_MAX: usize = 12;
pub struct SkillTool;
#[async_trait]
@@ -406,23 +479,60 @@ impl Tool for SkillTool {
"skill"
}
fn description(&self) -> String {
"Load a skill (packaged instructions for a kind of task) by name. Follow the returned instructions.".into()
"Load a skill (packaged instructions for a kind of task) by name and follow the returned instructions. `query` (keywords) lists matching skills instead; `file` reads one of the skill's further files.".into()
}
fn schema(&self) -> Value {
json!({"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]})
json!({"type": "object", "properties": {
"name": {"type": "string"},
"file": {"type": "string", "description": "relative path of a further file of the skill"},
"query": {"type": "string", "description": "keywords: lists the matching skills instead of loading one"}
}})
}
fn read_only(&self) -> bool {
true
}
async fn run(&self, input: Value, ctx: &ToolCtx) -> Result<ToolOutput> {
let owner = ctx.app.store.get_session(&ctx.session_id).ok().flatten().and_then(|s| s.owner_id).or_else(|| ctx.owner_id.clone());
let all = skills(&ctx.app, &ctx.root(), &ctx.cwd, owner.as_deref());
if let Some(q) = input.get("query").and_then(|v| v.as_str()).filter(|q| !q.trim().is_empty()) {
let words: Vec<String> = q.to_lowercase().split_whitespace().map(str::to_string).collect();
let mut hits: Vec<(usize, &Skill)> = all
.iter()
.map(|s| {
let hay = format!("{} {}", s.name, s.description).to_lowercase();
(words.iter().filter(|w| hay.contains(w.as_str())).count(), s)
})
.filter(|(n, _)| *n > 0)
.collect();
hits.sort_by_key(|(n, s)| (std::cmp::Reverse(*n), s.name.clone()));
if hits.is_empty() {
return Ok(ToolOutput::text(format!("No skill matches '{q}' ({} skills available).", all.len())));
}
let lines: Vec<String> = hits.iter().take(15).map(|(_, s)| format!("- {}: {}", s.name, s.description.chars().take(200).collect::<String>())).collect();
return Ok(ToolOutput::text(format!("Matching skills (load one with name=<skill>):\n{}", lines.join("\n"))));
}
let name = arg_str(&input, "name")?;
let Some(sk) = skills(&ctx.app, &ctx.root(), &ctx.cwd).into_iter().find(|s| s.name == name) else {
let Some(sk) = all.into_iter().find(|s| s.name == name) else {
return Ok(ToolOutput::error(format!("unknown skill '{name}'")));
};
let dir = sk.path.parent().unwrap_or(Path::new("."));
if let Some(file) = input.get("file").and_then(|v| v.as_str()).filter(|f| !f.trim().is_empty()) {
let rel = Path::new(file.trim());
if rel.is_absolute() || rel.components().any(|c| !matches!(c, std::path::Component::Normal(_))) {
return Ok(ToolOutput::error("file must be a relative path inside the skill"));
}
let Ok(real) = std::fs::canonicalize(dir.join(rel)) else { return Ok(ToolOutput::error(format!("no file '{file}' in skill '{name}'"))) };
if !real.starts_with(std::fs::canonicalize(dir)?) || !real.is_file() {
return Ok(ToolOutput::error(format!("no file '{file}' in skill '{name}'")));
}
let mut text = std::fs::read_to_string(&real).unwrap_or_else(|_| "(binary file)".into());
text.truncate(text.char_indices().nth(100_000).map(|(i, _)| i).unwrap_or(text.len()));
return Ok(ToolOutput::text(text));
}
let text = std::fs::read_to_string(&sk.path)?;
let (_, body) = frontmatter(&text);
let dir = sk.path.parent().unwrap_or(Path::new("."));
Ok(ToolOutput::text(format!("Skill '{name}' (base directory: {}):\n\n{body}", dir.display())))
let files = if sk.files.is_empty() { String::new() } else { format!("\n\nFurther files (read with name=\"{name}\" and file=<path>): {}", sk.files.join(", ")) };
Ok(ToolOutput::text(format!("Skill '{name}' (base directory: {}):\n\n{body}{files}", dir.display())))
}
}
+6 -2
View File
@@ -293,6 +293,10 @@ pub async fn run_session(app: Arc<App>, session_id: &str, cancel: CancellationTo
let roots = app.user_roots(session.owner_id.as_deref());
let root = app.root_for(session.owner_id.as_deref(), &cwd);
let mut agent = prompts::find_agent_for(&app, &root, &cwd, &session.agent, session.owner_id.as_deref());
// Chats that plan (spec chat, issue chat) write no code: the mode's review of the work does not apply.
if crate::factory::is_planning_chat(&app, &session) {
agent.refine = None;
}
let clean_room = session.clean_room(app.config().craft.clean_room);
// The craft prompt follows the session's clean room / deep switch.
if agent.name == "craft" && agent.source == "builtin" {
@@ -331,7 +335,7 @@ pub async fn run_session(app: Arc<App>, session_id: &str, cancel: CancellationTo
let owner = session.owner_id.as_deref().and_then(|id| app.store.user(id).ok().flatten());
let tools = available_tools(&app, &agent, owner.as_ref());
let req = ChatRequest {
system: prompts::with_chat_instructions(prompts::system_prompt(&app, &agent, &root, &cwd, &model_spec, &session.permission_mode, owner.as_ref()), &session.instructions),
system: prompts::with_active_skills(&app, prompts::with_chat_instructions(prompts::system_prompt(&app, &agent, &root, &cwd, &model_spec, &session.permission_mode, owner.as_ref()), &session.instructions), &session.skills, &root, &cwd, session.owner_id.as_deref()),
messages: history,
tools: tools.iter().map(|t| t.def()).collect(),
max_tokens,
@@ -899,7 +903,7 @@ fn create_child(app: &Arc<App>, ctx: &ToolCtx, agent_name: &str, description: &s
telegram_quiet: false,
summary: String::new(),
color: None,
icon: None,
icon: None, skills: Vec::new(),
};
let child = app.save_session(child)?;
let msg = Message::new(Role::User, vec![Part::Text { text: prompt }]);
+326
View File
@@ -0,0 +1,326 @@
//! The user's own skills: a folder per skill with `SKILL.md` and further text files, kept in
//! `<data>/user-skills/<user id>/<name>/`; created in the UI or imported from a GitHub repository.
use crate::api::{ApiError, ApiResult, AppState};
use crate::prompts::{frontmatter, skill_files, user_skills_dir};
use crate::store::User;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::{Extension, Json};
use serde::Deserialize;
use serde_json::{Value, json};
use std::path::PathBuf;
const MAX_FILES: usize = 100;
const MAX_FILE: usize = 200_000;
const MAX_TOTAL: usize = 2_000_000;
fn bad(m: impl Into<String>) -> ApiError {
ApiError(StatusCode::BAD_REQUEST, m.into())
}
/// A skill name is a folder name: lowercase letters, digits, `-` and `_`.
pub fn valid_name(n: &str) -> bool {
!n.is_empty() && n.len() <= 64 && n.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_') && !n.starts_with(['-', '_'])
}
/// Turn any title into a valid skill name.
pub fn slug(s: &str) -> String {
let mut out = String::new();
for c in s.to_lowercase().chars() {
if c.is_ascii_alphanumeric() {
out.push(c);
} else if !out.ends_with('-') && !out.is_empty() {
out.push('-');
}
}
out.trim_matches('-').chars().take(64).collect()
}
fn valid_rel(p: &str) -> bool {
let rel = std::path::Path::new(p);
!p.is_empty() && p.len() <= 200 && !rel.is_absolute() && rel.components().all(|c| matches!(c, std::path::Component::Normal(_)))
}
fn dir_of(app: &AppState, user: &User, name: &str) -> Result<PathBuf, ApiError> {
if !valid_name(name) {
return Err(bad("invalid skill name (lowercase letters, digits, - and _)"));
}
Ok(user_skills_dir(app, &user.id).join(name))
}
#[derive(Deserialize, Clone)]
pub struct FileBody {
path: String,
content: String,
}
/// Replace the files of a skill by `files` (must contain `SKILL.md`).
fn write_skill(dir: &std::path::Path, files: &[FileBody]) -> Result<(), ApiError> {
if !files.iter().any(|f| f.path == "SKILL.md" && !f.content.trim().is_empty()) {
return Err(bad("SKILL.md is required"));
}
if files.len() > MAX_FILES {
return Err(bad(format!("at most {MAX_FILES} files")));
}
let mut total = 0;
for f in files {
if !valid_rel(&f.path) {
return Err(bad(format!("invalid file path '{}'", f.path)));
}
if f.content.len() > MAX_FILE {
return Err(bad(format!("'{}' is too large (max {} KB)", f.path, MAX_FILE / 1000)));
}
total += f.content.len();
}
if total > MAX_TOTAL {
return Err(bad("the skill is too large (max 2 MB)"));
}
let tmp = dir.with_extension("saving");
let _ = std::fs::remove_dir_all(&tmp);
for f in files {
let p = tmp.join(&f.path);
if let Some(parent) = p.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&p, &f.content)?;
}
let _ = std::fs::remove_dir_all(dir);
std::fs::rename(&tmp, dir)?;
Ok(())
}
pub async fn list(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
let base = user_skills_dir(&app, &user.id);
let mut out = Vec::new();
for e in std::fs::read_dir(&base).into_iter().flatten().flatten() {
let Ok(text) = std::fs::read_to_string(e.path().join("SKILL.md")) else { continue };
let (meta, _) = frontmatter(&text);
out.push(json!({
"name": e.file_name().to_string_lossy(),
"description": meta.get("description").cloned().unwrap_or_default(),
"files": skill_files(&e.path()),
}));
}
out.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str()));
Ok(Json(json!({"skills": out})))
}
pub async fn get(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>) -> ApiResult {
let dir = dir_of(&app, &user, &name)?;
let main = std::fs::read_to_string(dir.join("SKILL.md")).map_err(|_| ApiError(StatusCode::NOT_FOUND, "skill not found".into()))?;
let mut files = vec![json!({"path": "SKILL.md", "content": main})];
for f in skill_files(&dir) {
let content = std::fs::read_to_string(dir.join(&f)).unwrap_or_default();
files.push(json!({"path": f, "content": content}));
}
Ok(Json(json!({"name": name, "files": files})))
}
#[derive(Deserialize)]
pub struct PutBody {
files: Vec<FileBody>,
}
pub async fn put(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>, Json(b): Json<PutBody>) -> ApiResult {
let dir = dir_of(&app, &user, &name)?;
std::fs::create_dir_all(user_skills_dir(&app, &user.id))?;
write_skill(&dir, &b.files)?;
app.audit(Some(&user), "skill.save", name, "");
Ok(Json(json!({"ok": true})))
}
pub async fn delete(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>) -> ApiResult {
let dir = dir_of(&app, &user, &name)?;
if !dir.join("SKILL.md").exists() {
return Err(ApiError(StatusCode::NOT_FOUND, "skill not found".into()));
}
std::fs::remove_dir_all(&dir)?;
app.audit(Some(&user), "skill.delete", name, "");
Ok(Json(json!({"ok": true})))
}
// --- GitHub import -------------------------------------------------------------------------
struct Source {
owner: String,
repo: String,
branch: Option<String>,
sub: String,
}
/// `https://github.com/<owner>/<repo>[/tree|blob/<branch>[/<path>]]`
fn parse_github(url: &str) -> Result<Source, ApiError> {
let rest = url.trim().strip_prefix("https://github.com/").ok_or_else(|| bad("only https://github.com/… URLs are supported"))?;
let rest = rest.split(['?', '#']).next().unwrap_or("").trim_end_matches('/');
let mut it = rest.split('/');
let (Some(owner), Some(repo)) = (it.next().filter(|s| !s.is_empty()), it.next().map(|r| r.trim_end_matches(".git")).filter(|s| !s.is_empty())) else {
return Err(bad("not a repository URL"));
};
let (mut branch, mut sub) = (None, String::new());
if matches!(it.next(), Some("tree") | Some("blob")) {
branch = it.next().map(str::to_string);
sub = it.collect::<Vec<_>>().join("/");
if sub.ends_with("SKILL.md") {
sub = sub.trim_end_matches("SKILL.md").trim_end_matches('/').to_string();
}
}
let ok = |s: &str| s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
if !ok(owner) || !ok(repo) {
return Err(bad("not a repository URL"));
}
Ok(Source { owner: owner.into(), repo: repo.into(), branch, sub })
}
fn client() -> Result<reqwest::Client, ApiError> {
reqwest::Client::builder().timeout(std::time::Duration::from_secs(30)).user_agent("codecraft-skill-import").build().map_err(|e| bad(e.to_string()))
}
/// Blobs (path, size) of the repository below `src.sub`, and the resolved branch.
async fn tree(c: &reqwest::Client, src: &Source) -> Result<(String, Vec<(String, u64)>), ApiError> {
let branch = match &src.branch {
Some(b) => b.clone(),
None => {
let v: Value = c.get(format!("https://api.github.com/repos/{}/{}", src.owner, src.repo)).send().await.map_err(|e| bad(e.to_string()))?.json().await.map_err(|e| bad(e.to_string()))?;
v["default_branch"].as_str().ok_or_else(|| bad("repository not found (is it public?)"))?.to_string()
}
};
let r = c.get(format!("https://api.github.com/repos/{}/{}/git/trees/{branch}?recursive=1", src.owner, src.repo)).send().await.map_err(|e| bad(e.to_string()))?;
if !r.status().is_success() {
return Err(bad(format!("GitHub answered {} (repository or branch not found, or rate limit)", r.status())));
}
let v: Value = r.json().await.map_err(|e| bad(e.to_string()))?;
let prefix = if src.sub.is_empty() { String::new() } else { format!("{}/", src.sub) };
let blobs = v["tree"]
.as_array()
.into_iter()
.flatten()
.filter(|e| e["type"] == "blob")
.filter_map(|e| Some((e["path"].as_str()?.to_string(), e["size"].as_u64().unwrap_or(0))))
.filter(|(p, _)| prefix.is_empty() || p.starts_with(&prefix))
.collect();
Ok((branch, blobs))
}
/// Folders that contain a `SKILL.md` (path relative to the repository root; "" = the root itself).
fn skill_dirs(blobs: &[(String, u64)]) -> Vec<String> {
let mut v: Vec<String> = blobs
.iter()
.filter_map(|(p, _)| if p == "SKILL.md" { Some(String::new()) } else { p.strip_suffix("/SKILL.md").map(str::to_string) })
.collect();
v.sort();
v.truncate(1000);
v
}
#[derive(Deserialize)]
pub struct ScanBody {
url: String,
}
/// List the skills found at a GitHub URL (nothing is imported).
pub async fn scan(Extension(_user): Extension<User>, Json(b): Json<ScanBody>) -> ApiResult {
let src = parse_github(&b.url)?;
let c = client()?;
let (branch, blobs) = tree(&c, &src).await?;
let dirs = skill_dirs(&blobs);
let list: Vec<Value> = dirs
.iter()
.map(|d| {
let name = d.rsplit('/').next().filter(|n| !n.is_empty()).unwrap_or(&src.repo);
let n = blobs.iter().filter(|(p, _)| d.is_empty() || p.starts_with(&format!("{d}/"))).count();
json!({"path": d, "name": slug(name), "files": n})
})
.collect();
Ok(Json(json!({"branch": branch, "skills": list})))
}
#[derive(Deserialize)]
pub struct ImportBody {
url: String,
/// Folders (as listed by `scan`).
paths: Vec<String>,
}
const BINARY: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "ico", "pdf", "zip", "gz", "tar", "woff", "woff2", "ttf", "otf", "mp4", "mov", "mp3", "wav", "pyc", "so", "bin", "exe"];
/// Fetch the chosen skills of a GitHub repository and save them as the user's own skills.
pub async fn import(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<ImportBody>) -> ApiResult {
if b.paths.is_empty() || b.paths.len() > 100 {
return Err(bad("choose between 1 and 100 skills"));
}
let src = parse_github(&b.url)?;
let c = client()?;
let (branch, blobs) = tree(&c, &src).await?;
let known = skill_dirs(&blobs);
std::fs::create_dir_all(user_skills_dir(&app, &user.id))?;
let (mut saved, mut skipped) = (Vec::new(), Vec::new());
for d in &b.paths {
if !known.contains(d) {
skipped.push(json!({"path": d, "why": "no SKILL.md there"}));
continue;
}
let name = slug(d.rsplit('/').next().filter(|n| !n.is_empty()).unwrap_or(&src.repo));
if !valid_name(&name) {
skipped.push(json!({"path": d, "why": "no usable name"}));
continue;
}
let prefix = if d.is_empty() { String::new() } else { format!("{d}/") };
let mut files = Vec::new();
let mut dropped = 0;
for (p, size) in blobs.iter().filter(|(p, _)| p.starts_with(&prefix)) {
let rel = &p[prefix.len()..];
let ext = rel.rsplit('.').next().unwrap_or("").to_lowercase();
if rel.is_empty() || !valid_rel(rel) || *size as usize > MAX_FILE || BINARY.contains(&ext.as_str()) || files.len() >= MAX_FILES || rel.starts_with(".git") {
dropped += 1;
continue;
}
// A skill at the repository root: only Markdown files, not the whole repository.
if d.is_empty() && rel != "SKILL.md" && !rel.ends_with(".md") {
dropped += 1;
continue;
}
let url = format!("https://raw.githubusercontent.com/{}/{}/{branch}/{p}", src.owner, src.repo);
let Ok(r) = c.get(&url).send().await else { dropped += 1; continue };
if !r.status().is_success() {
dropped += 1;
continue;
}
match r.text().await {
Ok(content) => files.push(FileBody { path: rel.to_string(), content }),
Err(_) => dropped += 1,
}
}
match write_skill(&user_skills_dir(&app, &user.id).join(&name), &files) {
Ok(()) => saved.push(json!({"name": name, "files": files.len(), "dropped": dropped})),
Err(e) => skipped.push(json!({"path": d, "why": e.1})),
}
}
app.audit(Some(&user), "skill.import", format!("{}/{}: {} skills", src.owner, src.repo, saved.len()), "");
Ok(Json(json!({"saved": saved, "skipped": skipped})))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_and_urls() {
assert!(valid_name("frontend-design"));
assert!(!valid_name("../x") && !valid_name("Front") && !valid_name(""));
assert_eq!(slug("Frontend Design!"), "frontend-design");
let s = parse_github("https://github.com/o/r/blob/main/.claude/skills/frontend/SKILL.md").ok().unwrap();
assert_eq!((s.owner.as_str(), s.repo.as_str(), s.branch.as_deref(), s.sub.as_str()), ("o", "r", Some("main"), ".claude/skills/frontend"));
let s = parse_github("https://github.com/o/r.git").ok().unwrap();
assert!(s.branch.is_none() && s.sub.is_empty());
assert!(parse_github("https://example.org/o/r").is_err());
}
#[test]
fn finds_skill_folders() {
let b = |p: &str| (p.to_string(), 10u64);
let dirs = skill_dirs(&[b("a/SKILL.md"), b("a/ref.md"), b("x/y/SKILL.md"), b("README.md")]);
assert_eq!(dirs, vec!["a".to_string(), "x/y".to_string()]);
assert!(valid_rel("ref/a.md") && !valid_rel("../a") && !valid_rel("/etc/passwd"));
}
}
+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/%')",
+1 -1
View File
@@ -543,7 +543,7 @@ async fn new_session(app: &Arc<App>, u: &User, bot: &Bot, chat: i64, arg: &str,
telegram_quiet: false,
summary: String::new(),
color: None,
icon: None,
icon: None, skills: Vec::new(),
})?;
update(app, &u.id, |st| st.session = Some(s.id.clone()));
bot.send(chat, &format!("{} <b>{}</b> · {} · {}", tr(de, "Neue Sitzung", "New session"), esc(&s.cwd), esc(&s.agent), esc(&s.model)), None).await?;
+80
View File
@@ -0,0 +1,80 @@
import { useState } from "react";
import { patch } from "../api";
import { toast } from "../dialogs";
import { useFetch } from "../hooks";
import { useT } from "../i18n";
import { Spinner } from "./Activity";
import { Icon } from "./Icon";
interface SkillInfo {
name: string;
description: string;
files: string[];
user?: boolean;
}
/** Switch skills on for one chat: their full instructions go into every turn. */
export function ChatSkillsDialog({ sessionId, cwd, active, onClose }: { sessionId: string; cwd: string; active: string[]; onClose: () => void }) {
const t = useT();
const { data } = useFetch<{ skills: SkillInfo[] }>(`/commands?cwd=${encodeURIComponent(cwd)}`);
const [picked, setPicked] = useState<string[]>(active);
const [filter, setFilter] = useState("");
const [busy, setBusy] = useState(false);
const all = data?.skills ?? [];
// Chosen skills first, then the rest.
const shown = all
.filter((s) => !filter.trim() || `${s.name} ${s.description}`.toLowerCase().includes(filter.trim().toLowerCase()))
.sort((a, b) => Number(picked.includes(b.name)) - Number(picked.includes(a.name)) || a.name.localeCompare(b.name));
const toggle = (n: string) => setPicked((p) => (p.includes(n) ? p.filter((x) => x !== n) : [...p, n]));
const save = async () => {
setBusy(true);
try {
await patch(`/sessions/${sessionId}`, { skills: picked });
onClose();
} catch (e: any) {
toast(e.message);
setBusy(false);
}
};
return (
<div className="modal-backdrop" onClick={onClose}>
<div className="modal draft-modal" role="dialog" aria-label={t("skills.chatTitle")} onClick={(e) => e.stopPropagation()}>
<h3>{t("skills.chatTitle")}</h3>
<div className="hint" style={{ marginBottom: 8 }}>
{t("skills.chatHint")}
</div>
{!data ? (
<Spinner />
) : all.length === 0 ? (
<div className="empty">{t("skills.empty")}</div>
) : (
<>
{all.length > 6 && <input autoFocus style={{ width: "100%" }} placeholder={t("skills.filter")} value={filter} onChange={(e) => setFilter(e.target.value)} />}
<div className="issue-list">
{shown.map((s) => (
<label key={s.name} className="row" style={{ gap: 8, alignItems: "flex-start", padding: "2px 0" }}>
<input type="checkbox" checked={picked.includes(s.name)} onChange={() => toggle(s.name)} />
<span>
<code>{s.name}</code>
{s.files.length > 0 && <span className="hint"> · {t("skills.files", { n: s.files.length })}</span>}
<div className="hint">{s.description}</div>
</span>
</label>
))}
</div>
{picked.length > 4 && <div className="notice">{t("skills.manyActive")}</div>}
</>
)}
<div className="row" style={{ marginTop: 10, justifyContent: "flex-end", gap: 6 }}>
<button onClick={onClose} disabled={busy}>
{t("common.cancel")}
</button>
<button className="primary" onClick={() => void save()} disabled={busy}>
{busy ? <Spinner small /> : <Icon name="check" />} {t("common.save")}
</button>
</div>
</div>
</div>
);
}
+18
View File
@@ -15,6 +15,7 @@ import { Composer } from "./Composer";
import { ShareDialog } from "./ShareDialog";
import { RenameDialog } from "./RenameDialog";
import { InstructionsDialog } from "./InstructionsDialog";
import { ChatSkillsDialog } from "./ChatSkills";
import { RegenerateButton } from "./Regenerate";
import { WorktreeChip } from "./WorktreeChip";
import { QueueList } from "./QueueList";
@@ -565,6 +566,7 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
// The Telegram switch in the ⋯ menu only matters with a paired bot.
const telegramPaired = useFetch<{ paired: boolean }>("/account/telegram").data?.paired ?? false;
const [editingInstructions, setEditingInstructions] = useState(false);
const [pickingSkills, setPickingSkills] = useState(false);
const [showApprovals, setShowApprovals] = useState(false);
const [planning, setPlanning] = useState(false);
const models = useModels();
@@ -823,6 +825,11 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
<Icon name="edit" /> {t("instructions.chip")}
</button>
)}
{!!session.skills?.length && (
<button className="chip" style={{ border: "none" }} onClick={() => !readOnly && setPickingSkills(true)} title={session.skills.join(", ")}>
<Icon name="scroll" /> {t("skills.chip", { n: session.skills.length })}
</button>
)}
{readOnly && <span className="chip">{t("chat.readOnly")}</span>}
{!readOnly && (
<>
@@ -886,6 +893,16 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
>
<Icon name="edit" /> {t("instructions.title")}
</a>
<a
href="#"
onClick={(e) => {
e.preventDefault();
(e.currentTarget.closest("details") as HTMLDetailsElement).open = false;
setPickingSkills(true);
}}
>
<Icon name="scroll" /> {t("skills.chatTitle")}
</a>
<ColorSwatches value={session.color} onChange={(color) => void update({ color })} />
<IconPicker value={session.icon} color={session.color} onChange={(icon) => void update({ icon })} />
<a href="#" onClick={(e) => (e.preventDefault(), ((e.currentTarget.closest("details") as HTMLDetailsElement).open = false), void planJob())} title={t("job.planHint")}>
@@ -1086,6 +1103,7 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string
)}
</div>
{showApprovals && <ProjectPermissions sessionId={sessionId} cwd={session.cwd} onClose={() => setShowApprovals(false)} />}
{pickingSkills && <ChatSkillsDialog sessionId={sessionId} cwd={session.cwd} active={session.skills ?? []} onClose={() => setPickingSkills(false)} />}
{editingInstructions && <InstructionsDialog sessionId={sessionId} value={session.instructions ?? ""} onClose={() => setEditingInstructions(false)} />}
{editingTitle && <RenameDialog sessionId={sessionId} title={session.title} onClose={() => setEditingTitle(false)} />}
{sharing && <ShareDialog sessionId={sessionId} onClose={() => setSharing(false)} />}
+97 -3
View File
@@ -6,6 +6,7 @@ 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;
@@ -27,7 +28,9 @@ interface PhaseCfg {
agent: string;
permission_mode: string;
timeout_minutes: number;
max_attempts: number;
extra_prompt: string;
skills: string[];
}
interface RepoCfg {
url: string;
@@ -36,6 +39,7 @@ interface RepoCfg {
token: string;
label: string;
max_parallel: number;
max_rework: number;
allowed_users: string[];
enabled: boolean;
review: PhaseCfg;
@@ -98,12 +102,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. */
@@ -113,8 +119,8 @@ const COLUMNS: { id: string; states: string[] }[] = [
{ id: "approved", states: ["approved"] },
{ id: "build", states: ["building", "rework"] },
{ id: "qa", states: ["qa", "testing"] },
{ id: "done", states: ["done"] },
{ id: "failed", states: ["failed", "rejected"] },
{ id: "done", states: ["done"] },
];
const KIND_NAME: Record<string, string> = { gitea: "Gitea", github: "GitHub", gitlab: "GitLab" };
@@ -192,6 +198,22 @@ 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;
@@ -303,6 +325,22 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
setBusy(false);
}
};
const closeIssue = async () => {
if (!selected) return;
const comment = await promptDialog({ title: t("factory.closeTitle"), message: t("factory.closeMsg", { n: selected.number }), defaultValue: t("factory.closeDefault"), confirmLabel: t("factory.close") });
if (comment === null) return;
setBusy(true);
try {
await post("/factory/issues/close", { repo: selected.repo, number: selected.number, comment });
toast(t("factory.closed"), "success");
setSel("");
await reload();
} catch (e: any) {
toast(e.message);
} finally {
setBusy(false);
}
};
const phaseRunning = !!selected && ["review", "building", "testing"].includes(selected.state);
return (
@@ -349,6 +387,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 })}
@@ -367,6 +406,9 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
<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>
@@ -406,6 +448,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>
@@ -424,6 +469,11 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
</button>
</>
)}
{selected && selected.state === "done" && (
<button className="small" onClick={closeIssue} disabled={busy}>
<Icon name="check" /> {t("factory.close")}
</button>
)}
{selected && (
<>
<a className="small ghost button-link" href={issueUrl(selected.repo, selected.number)} target="_blank" rel="noreferrer">
@@ -526,11 +576,46 @@ 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: "", skills: [] });
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"];
/** Skills switched on for the chat of one phase (the agent follows them in every turn). */
function PhaseSkills({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) {
const t = useT();
const [all, setAll] = useState<{ name: string; description: string }[]>([]);
useEffect(() => {
get<{ skills: { name: string; description: string }[] }>("/commands")
.then((d) => setAll(d.skills))
.catch(() => {});
}, []);
const rest = all.filter((s) => !value.includes(s.name));
return (
<div className="factory-skills">
<span>{t("factory.skills")}</span>
<div className="row" style={{ gap: 4, flexWrap: "wrap" }}>
{value.map((n) => (
<button key={n} type="button" className="chip" style={{ border: "none" }} title={t("factory.skillRemove")} onClick={() => onChange(value.filter((x) => x !== n))}>
{n} ×
</button>
))}
{rest.length > 0 && value.length < 10 && (
<select value="" onChange={(e) => e.target.value && onChange([...value, e.target.value])}>
<option value="">{t("factory.skillAdd")}</option>
{rest.map((s) => (
<option key={s.name} value={s.name} title={s.description}>
{s.name}
</option>
))}
</select>
)}
</div>
<div className="hint">{t("factory.skillsHint")}</div>
</div>
);
}
function PhaseForm({ phase, value, onChange }: { phase: Phase; value: PhaseCfg; onChange: (patch: Partial<PhaseCfg>) => void }) {
const t = useT();
return (
@@ -561,6 +646,11 @@ 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>
<PhaseSkills value={value.skills ?? []} onChange={(skills) => onChange({ skills })} />
<label>
<span>{t("factory.extraPrompt")}</span>
<textarea rows={3} value={value.extra_prompt} onChange={(e) => onChange({ extra_prompt: e.target.value })} />
@@ -780,6 +870,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) })} />
+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>
);
}
+1 -1
View File
@@ -193,7 +193,7 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
if (!model && config?.default_model) setModel(config.default_model);
}, [config, model]);
useEffect(() => {
if (!rootPath && roots.length) setRootPath(roots[roots.length - 1].path);
if (!rootPath && roots.length) setRootPath(roots[0].path);
}, [roots, rootPath]);
// Old software is analysed in deep mode; websites default to clean room.
useEffect(() => {
+5 -2
View File
@@ -18,6 +18,7 @@ import { Folders } from "./settings/Folders";
import { Users } from "./settings/Users";
import { Audit } from "./settings/Audit";
import { Tools } from "./settings/Tools";
import { Skills } from "./settings/Skills";
import { confirmDialog, promptDialog, toast } from "../dialogs";
type Json = any;
@@ -1088,8 +1089,8 @@ function Raw({ reload }: { reload: () => void }) {
// --- page -------------------------------------------------------------------
const ADMIN_TABS = ["general", "providers", "agents", "mcp", "permissions", "users", "folders", "tools", "audit", "templates", "modes", "account", "raw"] as const;
const USER_TABS = ["general", "templates", "modes", "account"] as const;
const ADMIN_TABS = ["general", "providers", "agents", "mcp", "permissions", "users", "folders", "tools", "audit", "templates", "modes", "skills", "account", "raw"] as const;
const USER_TABS = ["general", "templates", "modes", "skills", "account"] as const;
const TAB_ICONS: Record<string, string> = {
general: "gear",
providers: "brain",
@@ -1102,6 +1103,7 @@ const TAB_ICONS: Record<string, string> = {
audit: "scroll",
templates: "template",
modes: "sparkle",
skills: "scroll",
account: "user",
raw: "file-text",
};
@@ -1139,6 +1141,7 @@ export function Settings({ tab, onMenu }: { tab?: string; onMenu: () => void })
{active === "account" && <Account />}
{active === "templates" && <Templates />}
{active === "modes" && <PersonalModes />}
{active === "skills" && <Skills />}
{cfg && active === "users" && <Users />}
{cfg && active === "folders" && <Folders />}
{cfg && active === "audit" && <Audit />}
+290
View File
@@ -0,0 +1,290 @@
import { useState } from "react";
import { del, get, post, put } from "../../api";
import { confirmDialog, promptDialog, toast } from "../../dialogs";
import { useFetch } from "../../hooks";
import { useT } from "../../i18n";
import { Icon } from "../Icon";
import { Spinner } from "../Activity";
interface SkillInfo {
name: string;
description: string;
files: string[];
}
interface SkillFile {
path: string;
content: string;
}
const TEMPLATE = `---
name: my-skill
description: When to use this skill, in one or two sentences
---
# Instructions
Describe what the agent should do.
`;
/** The user's own skills: SKILL.md plus further files; created here or imported from GitHub. */
export function Skills() {
const t = useT();
const { data, reload } = useFetch<{ skills: SkillInfo[] }>("/skills");
const [editing, setEditing] = useState<{ name: string; isNew: boolean }>();
const [importing, setImporting] = useState(false);
const [filter, setFilter] = useState("");
const list = (data?.skills ?? []).filter((s) => !filter.trim() || `${s.name} ${s.description}`.toLowerCase().includes(filter.trim().toLowerCase()));
const remove = async (s: SkillInfo) => {
if (!(await confirmDialog({ message: t("skills.confirmDelete", { name: s.name }), danger: true }))) return;
try {
await del(`/skills/${s.name}`);
reload();
} catch (e: any) {
toast(e.message);
}
};
return (
<div className="panel">
<h3>
<Icon name="sparkle" /> {t("skills.title")}
</h3>
<div className="hint" style={{ marginBottom: 8 }}>
{t("skills.hint")}
</div>
<div className="row" style={{ gap: 6, marginBottom: 8 }}>
<button className="primary" onClick={() => setEditing({ name: "", isNew: true })}>
<Icon name="plus" /> {t("skills.new")}
</button>
<button onClick={() => setImporting(true)}>
<Icon name="git" /> {t("skills.import")}
</button>
<span className="spacer" />
{(data?.skills.length ?? 0) > 8 && <input placeholder={t("skills.filter")} value={filter} onChange={(e) => setFilter(e.target.value)} />}
</div>
{!data ? (
<Spinner />
) : list.length === 0 ? (
<div className="empty">{t("skills.empty")}</div>
) : (
list.map((s) => (
<div key={s.name} className="row" style={{ gap: 8, padding: "6px 0", borderBottom: "1px solid var(--border)" }}>
<div style={{ flex: 1, minWidth: 0 }}>
<code>{s.name}</code>
{s.files.length > 0 && <span className="chip" style={{ marginLeft: 6 }}>{t("skills.files", { n: s.files.length })}</span>}
<div className="hint" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
{s.description}
</div>
</div>
<button className="small" onClick={() => setEditing({ name: s.name, isNew: false })}>
<Icon name="edit" /> {t("common.edit")}
</button>
<button className="small danger" onClick={() => void remove(s)} aria-label={t("common.delete")}>
<Icon name="trash" />
</button>
</div>
))
)}
{editing && (
<SkillEditor
name={editing.name}
isNew={editing.isNew}
onClose={(saved) => {
setEditing(undefined);
if (saved) reload();
}}
/>
)}
{importing && (
<ImportDialog
onClose={(done) => {
setImporting(false);
if (done) reload();
}}
/>
)}
</div>
);
}
function SkillEditor({ name: initial, isNew, onClose }: { name: string; isNew: boolean; onClose: (saved: boolean) => void }) {
const t = useT();
const [name, setName] = useState(initial);
const [files, setFiles] = useState<SkillFile[]>(isNew ? [{ path: "SKILL.md", content: TEMPLATE }] : []);
const [loaded, setLoaded] = useState(isNew);
const [current, setCurrent] = useState("SKILL.md");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string>();
useState(() => {
if (!isNew)
get<{ files: SkillFile[] }>(`/skills/${initial}`)
.then((d) => (setFiles(d.files), setLoaded(true)))
.catch((e) => (setError(e.message), setLoaded(true)));
});
const file = files.find((f) => f.path === current) ?? files[0];
const setContent = (content: string) => setFiles(files.map((f) => (f.path === file?.path ? { ...f, content } : f)));
const addFile = async () => {
const p = await promptDialog({ message: t("skills.addFile"), placeholder: "references/guide.md", confirmLabel: t("common.add") });
const path = p?.trim().replace(/^\/+/, "");
if (!path) return;
if (files.some((f) => f.path === path)) return setCurrent(path);
setFiles([...files, { path, content: "" }]);
setCurrent(path);
};
const removeFile = () => {
if (!file || file.path === "SKILL.md") return;
setFiles(files.filter((f) => f.path !== file.path));
setCurrent("SKILL.md");
};
const save = async () => {
setBusy(true);
setError(undefined);
try {
await put(`/skills/${name.trim()}`, { files });
onClose(true);
} catch (e: any) {
setError(e.message);
setBusy(false);
}
};
return (
<div className="modal-backdrop">
<div className="modal draft-modal" role="dialog" aria-label={t("skills.edit")}>
<h3>{isNew ? t("skills.new") : t("skills.edit")}</h3>
{!loaded ? (
<Spinner />
) : (
<>
<label style={{ display: "block", marginBottom: 8 }}>
<span className="hint">{t("skills.name")}</span>
<input className="mono" style={{ width: "100%" }} value={name} disabled={!isNew} placeholder="frontend" onChange={(e) => setName(e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, "-"))} />
</label>
<div className="row" style={{ gap: 4, flexWrap: "wrap", marginBottom: 6 }}>
{files.map((f) => (
<button key={f.path} className={`small ${f.path === file?.path ? "primary" : ""}`} onClick={() => setCurrent(f.path)}>
{f.path}
</button>
))}
<button className="small ghost" onClick={() => void addFile()}>
<Icon name="plus" /> {t("skills.file")}
</button>
{file && file.path !== "SKILL.md" && (
<button className="small danger" onClick={removeFile} aria-label={t("common.delete")}>
<Icon name="trash" />
</button>
)}
</div>
<textarea className="mono" rows={18} style={{ width: "100%" }} value={file?.content ?? ""} onChange={(e) => setContent(e.target.value)} spellCheck={false} />
<div className="hint">{t("skills.fileHint")}</div>
</>
)}
{error && <div className="notice err">{error}</div>}
<div className="row" style={{ marginTop: 10, justifyContent: "flex-end", gap: 6 }}>
<button onClick={() => onClose(false)} disabled={busy}>
{t("common.cancel")}
</button>
<button className="primary" onClick={() => void save()} disabled={busy || !loaded || !name.trim() || !files.some((f) => f.path === "SKILL.md")}>
{busy ? <Spinner small /> : <Icon name="check" />} {t("common.save")}
</button>
</div>
</div>
</div>
);
}
interface Found {
path: string;
name: string;
files: number;
}
function ImportDialog({ onClose }: { onClose: (done: boolean) => void }) {
const t = useT();
const [url, setUrl] = useState("");
const [found, setFound] = useState<Found[]>();
const [picked, setPicked] = useState<Set<string>>(new Set());
const [filter, setFilter] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string>();
const scan = async () => {
setBusy(true);
setError(undefined);
try {
const r = await post<{ skills: Found[] }>("/skills/github/scan", { url: url.trim() });
setFound(r.skills);
setPicked(new Set());
if (r.skills.length === 0) setError(t("skills.noneFound"));
} catch (e: any) {
setError(e.message);
}
setBusy(false);
};
const shown = (found ?? []).filter((s) => !filter.trim() || s.path.toLowerCase().includes(filter.trim().toLowerCase()));
const toggle = (p: string) => setPicked((s) => (s.has(p) ? new Set([...s].filter((x) => x !== p)) : new Set(s).add(p)));
const run = async () => {
setBusy(true);
setError(undefined);
try {
const r = await post<{ saved: unknown[]; skipped: { path: string; why: string }[] }>("/skills/github/import", { url: url.trim(), paths: [...picked] });
toast(t("skills.imported", { n: r.saved.length }) + (r.skipped.length ? ` (${r.skipped.length} ${t("skills.skipped")})` : ""), "success");
onClose(true);
} catch (e: any) {
setError(e.message);
setBusy(false);
}
};
return (
<div className="modal-backdrop">
<div className="modal draft-modal" role="dialog" aria-label={t("skills.import")}>
<h3>{t("skills.import")}</h3>
<div className="hint" style={{ marginBottom: 8 }}>
{t("skills.importHint")}
</div>
<div className="row" style={{ gap: 6 }}>
<input className="mono" style={{ flex: 1 }} value={url} placeholder="https://github.com/owner/repo/tree/main/skills" onChange={(e) => setUrl(e.target.value)} onKeyDown={(e) => e.key === "Enter" && url.trim() && !busy && void scan()} />
<button onClick={() => void scan()} disabled={busy || !url.trim()}>
{busy && !found ? <Spinner small /> : <Icon name="search" />} {t("skills.scan")}
</button>
</div>
{found && found.length > 0 && (
<>
<div className="row" style={{ gap: 6, margin: "8px 0" }}>
<input style={{ flex: 1 }} placeholder={t("skills.filter")} value={filter} onChange={(e) => setFilter(e.target.value)} />
<button className="small" onClick={() => setPicked(new Set([...picked, ...shown.map((s) => s.path)]))}>
{t("skills.selectShown", { n: shown.length })}
</button>
<button className="small ghost" onClick={() => setPicked(new Set())}>
{t("skills.selectNone")}
</button>
</div>
<div className="issue-list">
{shown.map((s) => (
<label key={s.path} className="row" style={{ gap: 8, padding: "2px 0" }}>
<input type="checkbox" checked={picked.has(s.path)} onChange={() => toggle(s.path)} />
<span>
<code>{s.name}</code> <span className="hint">{s.path} · {t("skills.files", { n: s.files })}</span>
</span>
</label>
))}
</div>
</>
)}
{error && <div className="notice err">{error}</div>}
<div className="row" style={{ marginTop: 10, justifyContent: "flex-end", gap: 6 }}>
<button onClick={() => onClose(false)} disabled={busy}>
{t("common.cancel")}
</button>
<button className="primary" onClick={() => void run()} disabled={busy || picked.size === 0}>
{busy && found ? <Spinner small /> : <Icon name="check" />} {t("skills.importN", { n: picked.size })}
</button>
</div>
</div>
</div>
);
}
+55
View File
@@ -774,6 +774,32 @@ export const de: Messages = {
"instructions.hint": "Gelten für jede Nachricht in diesem Chat, zusätzlich zum Modus – z. B. Sprache, Ton, Regeln oder der Teil des Projekts, um den es geht.",
"instructions.placeholder": "z. B. Antworte immer auf Englisch. Ändere nur Dateien unter api/. Frag, bevor du Abhängigkeiten hinzufügst.",
"instructions.clear": "Entfernen",
"settings.tab.skills": "Skills",
"skills.title": "Skills",
"skills.hint": "Ein Skill ist ein Ordner mit SKILL.md (Anweisungen) und weiteren Dateien. Skills schaltest du pro Chat ein (Menü ⋯ → Skills); ihre Anweisungen gelten dann in jeder Runde, alle anderen kosten keinen Kontext. Agenten können außerdem alle Skills per Stichwort suchen und bei Bedarf laden.",
"skills.new": "Neuer Skill",
"skills.edit": "Skill bearbeiten",
"skills.import": "Von GitHub importieren",
"skills.importHint": "URL eines Repositorys oder eines Ordners darin einfügen. Jeder Ordner mit SKILL.md wird angeboten; die Textdateien des Skills werden mit importiert. Bei großen Repositorys die URL auf einen Ordner eingrenzen (…/tree/main/engineering).",
"skills.scan": "Suchen",
"skills.noneFound": "Unter dieser Adresse wurde keine SKILL.md gefunden.",
"skills.selectShown": "Angezeigte wählen ({n})",
"skills.selectNone": "Keine wählen",
"skills.importN": "{n} importieren",
"skills.imported": "{n} Skills importiert",
"skills.skipped": "übersprungen",
"skills.filter": "Filtern…",
"skills.empty": "Noch keine Skills.",
"skills.files": "Dateien: {n}",
"skills.name": "Name (Ordner, Kleinbuchstaben)",
"skills.file": "Datei",
"skills.addFile": "Pfad der neuen Datei",
"skills.fileHint": "SKILL.md beginnt mit einem Kopfblock (name, description); die Beschreibung sagt dem Agenten, wann der Skill passt.",
"skills.confirmDelete": "Skill {name} löschen?",
"skills.chatTitle": "Skills für diesen Chat",
"skills.chatHint": "Eingeschaltete Skills gelten für jede Nachricht dieses Chats. Schalte nur ein, was du brauchst – jeder belegt Kontext.",
"skills.manyActive": "Viele aktive Skills belegen viel Kontext.",
"skills.chip": "Skills: {n}",
"instructions.chip": "Anweisungen",
"chat.compacted": "Unterhaltung komprimiert – Zusammenfassung",
"chat.context": "Kontext",
@@ -1241,6 +1267,35 @@ export const de: Messages = {
"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.close": "Issue schließen",
"factory.closeTitle": "Issue schließen",
"factory.closeMsg": "Kommentar zum Schließen von Issue #{n}. Er wird im Issue veröffentlicht, danach wird das Issue geschlossen.",
"factory.closeDefault": "Erledigt und abgenommen.",
"factory.closed": "Issue geschlossen",
"factory.skills": "Skills",
"factory.skillAdd": "Skill hinzufügen…",
"factory.skillRemove": "Entfernen",
"factory.skillsHint": "Für jeden Chat dieser Phase eingeschaltet (CodeCraft-Agent). Jeder belegt Kontext – wenige wählen.",
"factory.pr": "Pull Request",
"factory.round": "Runde {n}",
"factory.openChat": "Chat öffnen",
+55
View File
@@ -773,6 +773,32 @@ export const en = {
"instructions.hint": "Apply to every message in this chat, in addition to the mode – e.g. language, tone, rules, the part of the project to work on.",
"instructions.placeholder": "e.g. Always answer in English. Only change files under api/. Ask before adding dependencies.",
"instructions.clear": "Remove",
"settings.tab.skills": "Skills",
"skills.title": "Skills",
"skills.hint": "A skill is a folder with SKILL.md (instructions) and further files. Switch skills on per chat (menu ⋯ → Skills) so their instructions are used in every turn; the others cost no context. Agents can also search all skills by keyword and load one when needed.",
"skills.new": "New skill",
"skills.edit": "Edit skill",
"skills.import": "Import from GitHub",
"skills.importHint": "Paste the URL of a repository or of a folder in it. Every folder with a SKILL.md is offered; text files of the skill are imported with it. For large repositories, narrow the URL to a folder (…/tree/main/engineering).",
"skills.scan": "Search",
"skills.noneFound": "No SKILL.md found at this address.",
"skills.selectShown": "Select shown ({n})",
"skills.selectNone": "Select none",
"skills.importN": "Import {n}",
"skills.imported": "{n} skills imported",
"skills.skipped": "skipped",
"skills.filter": "Filter…",
"skills.empty": "No skills yet.",
"skills.files": "Files: {n}",
"skills.name": "Name (folder, lowercase)",
"skills.file": "File",
"skills.addFile": "Path of the new file",
"skills.fileHint": "SKILL.md starts with a front matter block (name, description); the description tells the agent when to use the skill.",
"skills.confirmDelete": "Delete the skill {name}?",
"skills.chatTitle": "Skills for this chat",
"skills.chatHint": "Switched-on skills are part of every message of this chat. Switch on only what you need – each one uses context.",
"skills.manyActive": "Many active skills use a lot of context.",
"skills.chip": "Skills: {n}",
"instructions.chip": "Instructions",
"chat.compacted": "Conversation compacted – summary",
"chat.context": "Context",
@@ -1240,6 +1266,35 @@ export const en = {
"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.close": "Close issue",
"factory.closeTitle": "Close issue",
"factory.closeMsg": "Comment for closing issue #{n}. It is posted on the issue, then the issue is closed.",
"factory.closeDefault": "Done and accepted.",
"factory.closed": "Issue closed",
"factory.skills": "Skills",
"factory.skillAdd": "Add skill…",
"factory.skillRemove": "Remove",
"factory.skillsHint": "Switched on for every chat of this phase (CodeCraft agent). Each one uses context – choose few.",
"factory.pr": "Pull request",
"factory.round": "round {n}",
"factory.openChat": "Open chat",
+5
View File
@@ -5195,3 +5195,8 @@ td.fold-indent {
.issue-item textarea {
width: 100%;
}
.release-row {
border-top: 1px solid var(--border);
padding: 6px 0;
}
+2
View File
@@ -82,6 +82,8 @@ export interface Session {
folder?: string | null;
/** Instructions for this chat (added to the system prompt). */
instructions?: string;
/** Skills switched on for this chat. */
skills?: string[];
/** Approvals and questions of this chat are not sent to Telegram. */
telegram_quiet?: boolean;
}
+36
View File
@@ -3,6 +3,42 @@
* under "unreleased"; scripts/release.sh renames the key to the release version.
*/
export const WHATS_NEW: Record<string, { en: string[]; de: string[] }> = {
"202611-00058": {
en: ["README and screenshots updated"],
de: ["README und Screenshots aktualisiert"],
},
"202611-00057": {
en: ["Factory: choose skills for each phase (review, build, acceptance)"],
de: ["Factory: Skills für jede Phase wählbar (Review, Build, Abnahme)"],
},
"202611-00056": {
en: ["Skills: create or import them from GitHub (Settings → Skills) and switch them on per chat; large libraries do not fill the context"],
de: ["Skills: selbst anlegen oder von GitHub importieren (Einstellungen → Skills) und pro Chat einschalten; große Bibliotheken füllen den Kontext nicht"],
},
"202611-00055": {
en: ["Fixed: cloning a repository for a new project no longer ends up in the factory area"],
de: ["Behoben: Klonen eines Repositorys für ein neues Projekt landet nicht mehr in der Factory-Ablage"],
},
"202611-00054": {
en: ["README: new section explaining the code factory"],
de: ["README: neuer Abschnitt zur Code-Factory"],
},
"202611-00053": {
en: ["Factory: the current version is read from the tags on the forge"],
de: ["Factory: die aktuelle Version wird aus den Tags im Forge gelesen"],
},
"202611-00052": {
en: ["Factory: fixed versioning – deliverables raise the patch version, only the last one of a milestone raises the minor version"],
de: ["Factory: Versionierung korrigiert – Deliverables erhöhen die Patch-Version, nur das letzte eines Meilensteins die Minor-Version"],
},
"202611-00051": {
en: ["Factory: close finished issues with a comment; the Done column moved to the right"],
de: ["Factory: fertige Issues mit Kommentar schließen; die Spalte Fertig steht jetzt ganz rechts"],
},
"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"],