Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

perf(skills): batch install verification and live installer progress (#2960)

nullptr-error940799a74db7
diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yaml
index 6bdf87f1e..b9c8ed5dc 100644
--- a/config/prompt_templates/agent_system_prompt.yaml
+++ b/config/prompt_templates/agent_system_prompt.yaml
@@ -508,15 +508,15 @@ templates:
The user message gives you:
- the skill directory (absolute path, already seeded with the skill's source files)
- the full text of that skill's SKILL.md
- - whether `uv` is available in this image
+ - the absolute paths of the package managers present in this image
+ (uv, npm, pnpm, pip, python3, node), and which are missing
</inputs>
<workflow>
1. Read the SKILL.md text in the user message and work out what has to be installed. Dependencies are often described in prose rather than a requirements file — read carefully.
2. Inspect the skill directory with `ls -la` before installing, so you know which of requirements.txt / pyproject.toml / package.json actually exist.
3. Install dependencies INTO THE SKILL DIRECTORY (see <isolation>), including on-demand extras (see <on_demand_dependencies>).
- 4. Verify by actually running the skill's entry point (for example `--help`). Do not declare success until a real command exits 0.
- 5. Reply with a short summary: what you installed, where it went, and what you ran to verify.
+ 4. Reply with a short summary: what you installed, where it went.
</workflow>
<on_demand_dependencies>
@@ -539,8 +539,7 @@ templates:
<tool_guidelines>
* **shell_exec:** your only tool. `write_sandbox_file` / `edit_sandbox_file` / `list_sandbox_files` / `read_sandbox_file` are not registered. You may set `work_dir` to the skill directory (it is allowed for this session) and then use relative paths, or leave `work_dir` unset and use absolute paths. Both work.
* Write `.weknora/requirements.json` with a short `mkdir -p .weknora && cat > .weknora/requirements.json <<'EOF'` redirect. Do not call `write_sandbox_file` — it only accepts `/workspace`, which is wiped before the snapshot.
- * Prefer one command per call so a failure is easy to attribute.
- * If a command fails, read the error and adapt — do not repeat the identical command.
+ * If a command fails, read the error and adapt.
</tool_guidelines>
<constraints>
@@ -548,7 +547,7 @@ templates:
2. Do not modify or delete other skills' directories.
3. Do not touch /workspace: it is wiped before the snapshot is taken.
4. Do not attempt to snapshot, restart or shut down the sandbox — the server does that after you finish.
- 5. Your last message must be the summary described in step 5, with no further tool calls.
+ 5. Your last message must be the summary described in step 4, with no further tool calls.
</constraints>
<system_status>
diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.go
index 420685fc5..abccf068b 100644
--- a/internal/application/service/tenant_skill_install.go
+++ b/internal/application/service/tenant_skill_install.go
@@ -676,8 +676,18 @@ func (s *TenantSkillService) beginInstallTranscript(
sess *types.Session, mgr sandbox.Manager, skillDir string, bundle *SkillBundle,
) (*installTranscript, string) {
assistantMessageID := uuid.NewString()
- prompt := buildInstallPrompt(skillDir, bundle, s.probeUv(ctx, mgr, sess.ID))
- transcript := newInstallTranscript(ctx, event.NewEventBus(), s.streams, s.messages, sess.ID, assistantMessageID)
+ prompt := buildInstallPrompt(skillDir, bundle, s.probeInstallTools(ctx, mgr, sess.ID))
+ transcript := newInstallTranscript(ctx, event.NewEventBus(), s.streams, s.messages, sess.ID, assistantMessageID,
+ // Asymptotic activity progress: every installer command advances the
+ // bar within the 35→79 span, so the number the admin watches moves
+ // while the agent works instead of sitting at seeded until agent_done.
+ func(steps int, lastCmd string) {
+ s.publishProgress(ctx, tenantID, sess.SandboxConfigID, skillID, SkillProgress{
+ Percent: asymptoticInstallPercent(steps),
+ Stage: "agent",
+ Log: lastCmd,
+ })
+ })
if err := transcript.Create(ctx, prompt); err != nil {
logger.Warnf(ctx, "[skill] seed install transcript for %s failed: %v", skillID, err)
}
@@ -741,6 +751,11 @@ func (s *TenantSkillService) installDependenciesAndVerify(
}
s.publishProgress(ctx, job.tenantID, job.configID, job.skillID,
SkillProgress{Percent: 80, Stage: "agent_done"})
+ // The agent's part of this round is over: mute the asymptotic activity
+ // progress so verification and any repair round — which publish their
+ // own stage anchors (80 / 82) — cannot be dragged back below them by
+ // the next round's tool calls.
+ job.transcript.muteActivityProgress()
// The tree is handed to the execution user BEFORE it is verified. The
// agent created these files as root, and the language passes
@@ -946,59 +961,114 @@ The same verification runs again as soon as you finish.
func (s *TenantSkillService) normalizeSkillPermissions(
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string,
) error {
- cmds := []string{
- fmt.Sprintf("chmod -R 555 %s", sandbox.ShellQuote(skillDir)),
- fmt.Sprintf("chown -R root:root %s", sandbox.ShellQuote(skillDir)),
- }
- for _, cmd := range cmds {
- if _, err := s.execInstall(ctx, mgr, sessionID, cmd); err != nil {
- return fmt.Errorf("normalize skill permissions (%s): %w", cmd, err)
- }
+ dir := sandbox.ShellQuote(skillDir)
+ cmd := fmt.Sprintf("chmod -R 555 %s && chown -R root:root %s", dir, dir)
+ if _, err := s.execInstall(ctx, mgr, sessionID, cmd); err != nil {
+ return fmt.Errorf("normalize skill permissions (%s): %w", cmd, err)
}
return nil
}
-// cleanImageScratch wipes the state that must not reach the snapshot: the
-// per-session workspace and the package download caches.
+// skillCacheBudgetMB caps the package download caches one image carries into
+// its next generation, as one total across both accounts. Retaining the caches
+// lets a future install resolve a package a previous install already fetched
+// without touching the network — minutes of the agent phase. Letting them grow
+// unbounded would bake every version ever downloaded into every future
+// snapshot, so the total is measured and anything over the budget is wiped
+// whole.
+const skillCacheBudgetMB = 256
+
+// cleanImageScratch resets the state that must not reach the snapshot and
+// trims what may. The per-session workspace is wiped unconditionally: a
+// snapshot carrying it would hand every future session this run's scratch
+// files, and the wipe takes the base image's own input/output directories with
+// it, so the same command restores them with the ownership the session account
+// needs — the only step of an install that runs with the privileges to do it.
+// That half is strict; failing it fails the install.
+//
+// The package download caches are the other half, and they are retained rather
+// than wiped: pip, uv, npm and pnpm caches are first trimmed with the tools'
+// own collectors, then measured as one total across both accounts and wiped
+// whole when they exceed skillCacheBudgetMB. That half is best-effort by
+// construction — every statement in it is guarded, and a prune that failed or
+// a size that could not be measured only means a larger image, never a failed
+// install.
func (s *TenantSkillService) cleanImageScratch(
ctx context.Context, mgr sandbox.Manager, sessionID string,
) error {
+ res, err := s.execInstall(ctx, mgr, sessionID, cleanImageScratchCommand())
+ if err != nil {
+ return fmt.Errorf("clean image scratch: %w", err)
+ }
+ // The retention half reports what the image will actually carry. Logged so
+ // the budget constant is tuned from data rather than guesses.
+ if res != nil && strings.TrimSpace(res.Stdout) != "" {
+ logger.Infof(ctx, "[skill] cache retention: %s", strings.TrimSpace(res.Stdout))
+ }
+ return nil
+}
+
+// cleanImageScratchCommand folds the workspace reset and the cache retention
+// into one command, one round trip. The workspace half decides the exit code:
+// its status is captured right after it runs and is what the command exits
+// with, so merging cannot soften the old semantics. The retention half follows
+// and cannot change that code — it is written to always succeed, and the shell
+// it lands in has no set -e to turn a swallowed prune failure into an abort.
+func cleanImageScratchCommand() string {
user := sandbox.DefaultSandboxExecUser
inputRoot := sandbox.ShellQuote(sandbox.SessionInputRoot)
outputRoot := sandbox.ShellQuote(sandbox.SessionOutputRoot)
- cmds := []string{
- "rm -rf /workspace/* /workspace/.[!.]* || true",
- // The wipe above takes the base image's own input/output directories
- // with it, so every session booting from this snapshot would start on
- // a bare /workspace. Restoring them here is the only place with root:
- // a provider whose filesystem API runs as root would otherwise
- // recreate them root-owned, and the session account can neither write
- // them nor take them over.
- fmt.Sprintf(
- "mkdir -p %s %s && chown %s:%s %s %s && chmod 775 %s %s",
- inputRoot, outputRoot,
- user, user, inputRoot, outputRoot,
- inputRoot, outputRoot,
- ),
- // Spelled out for both accounts on purpose: this runs as root, so "~"
- // would only ever clear root's caches, while the agent's own installs
- // populate the exec user's caches and those are what reach the image.
- "rm -rf " + strings.Join(append(
- packageCachePaths("/root"),
- packageCachePaths(path.Join("/home", sandbox.DefaultSandboxExecUser))...,
- ), " ") + " || true",
- }
- for _, cmd := range cmds {
- if _, err := s.execInstall(ctx, mgr, sessionID, cmd); err != nil {
- return fmt.Errorf("clean image scratch (%s): %w", cmd, err)
- }
- }
- return nil
+ var b strings.Builder
+ b.WriteString("rm -rf /workspace/* /workspace/.[!.]* || true")
+ fmt.Fprintf(&b, "; mkdir -p %s %s && chown %s:%s %s %s && chmod 775 %s %s; status=$?",
+ inputRoot, outputRoot,
+ user, user, inputRoot, outputRoot,
+ inputRoot, outputRoot,
+ )
+ // The prunes run as root, so they only ever trim root's caches. The budget
+ // guard below covers both accounts on purpose — it needs nothing but du and
+ // rm, and this runs as root.
+ for _, prune := range []struct{ tool, subcommand string }{
+ {"uv", "cache prune"},
+ {"npm", "cache verify"},
+ {"pnpm", "store prune"},
+ } {
+ fmt.Fprintf(&b, "; command -v %s >/dev/null 2>&1 && %s %s >/dev/null 2>&1 || true",
+ prune.tool, prune.tool, prune.subcommand)
+ }
+ paths := append(
+ packageCachePaths("/root"),
+ packageCachePaths(path.Join("/home", sandbox.DefaultSandboxExecUser))...,
+ )
+ b.WriteString("; ")
+ b.WriteString(cacheBudgetGuardCommand(paths, skillCacheBudgetMB*1024))
+ b.WriteString("; exit $status")
+ return b.String()
+}
+
+// cacheBudgetGuardCommand emits the shell that measures the given cache
+// directories as one total and wipes them whole when they exceed budgetKB.
+// Keeping the caches is the point, so every way the measurement can fail keeps
+// them: no du, no directories, an unreadable size — all leave the caches in
+// place. The total is echoed in both cases so the install log records what the
+// image carries, which is the data the budget is tuned from.
+func cacheBudgetGuardCommand(paths []string, budgetKB int) string {
+ quoted := make([]string, 0, len(paths))
+ for _, p := range paths {
+ quoted = append(quoted, sandbox.ShellQuote(p))
+ }
+ list := strings.Join(quoted, " ")
+ return fmt.Sprintf(
+ "total=$(du -skc %s 2>/dev/null | tail -n1 | cut -f1); "+
+ "echo \"cache total: ${total:-0}KB\"; "+
+ "[ \"${total:-0}\" -gt %d ] && { rm -rf %s; echo 'cache wiped: over budget'; }; true",
+ list, budgetKB, list)
}
// packageCachePaths lists the download caches the three package managers we
-// support keep under a home directory. They are scratch by definition and
-// would otherwise be snapshotted into every future session's image.
+// support keep under a home directory. Retained up to the budget these days,
+// but still capped: a cache is a means to a faster install, never the payload
+// of the image.
func packageCachePaths(home string) []string {
return []string{
path.Join(home, ".cache", "pip"),
@@ -1656,7 +1726,7 @@ func snapshotBelongsToOtherConfig(snap sandbox.RemoteSnapshotRef, prefix string)
return sawForeign
}
-func buildInstallPrompt(skillDir string, bundle *SkillBundle, uvAvailable bool) string {
+func buildInstallPrompt(skillDir string, bundle *SkillBundle, tools map[string]string) string {
skillMD := ""
requirementsPath := ""
if bundle != nil {
@@ -1666,7 +1736,7 @@ func buildInstallPrompt(skillDir string, bundle *SkillBundle, uvAvailable bool)
return fmt.Sprintf(`Install this WeKnora skill into the sandbox image.
Skill directory: %s
-uv available: %t
+%s
Hard requirements:
- Install dependencies for exactly this one skill.
@@ -1677,9 +1747,9 @@ Hard requirements:
with a short shell redirect after mkdir -p.
- Each command has a 10-minute budget; you do not need to set timeout_sec.
- When finished, report what you installed and any global/system packages you changed.
-- Declare the environment variables this skill reads AT RUN TIME. Read its scripts to decide;
- ignore anything only the installation itself needed. Run mkdir -p on the directory first, then
- write the declaration to %s as JSON of this exact shape:
+- Declare the environment variables this skill needs AT RUN TIME. Decide from the SKILL.md text
+ at the end of this message: declare what it documents as needed to run the skill. Ignore
+ anything only the installation itself needed. Run mkdir -p on the directory first, then write the declaration to %s as JSON of this exact shape:
{"env":[{"name":"TAVILY_API_KEY","description":"what the skill uses it for","required":true}]}
Each name must be UPPER_SNAKE_CASE and must appear literally somewhere in the skill's own files.
Never write any value, placeholder or example credential: this file declares what is needed, and
@@ -1706,20 +1776,13 @@ The server verifies the result itself before the image is kept, so report what
you did rather than whether it passed. Verification parses every script with
the interpreter that would run it, resolves the imports each one executes on
load, and checks every distribution named in requirements.txt is present in the
-venv. It never runs the skill's code, so nothing is expected to answer --help.
+venv. It never runs the skill's code.
Lazy imports and install_deps.py extras are invisible to that check — you still
have to install them.
-SKILL.md is not the dependency list. What the check resolves is the set of
-top-level imports the skill's files actually execute, and a library module
-routinely imports something the documentation never mentions. Read every .py in
-the tree (grep '^import\|^from' over it) and install what those lines need, not
-only what the Dependencies section names. If verification does fail on a missing
-package, you get its exact findings back and one round to install them.
-
SKILL.md:
%s
-`, skillDir, uvAvailable, skillDir, skillDir, skillDir,
+`, skillDir, formatToolchainSection(tools), skillDir, skillDir, skillDir,
requirementsPath, skillDir, formatOnDemandInstallers(bundle),
formatFrontmatterRepairNote(bundle), skillMD)
}
@@ -1763,9 +1826,79 @@ func formatFrontmatterRepairNote(bundle *SkillBundle) string {
"can fix the file.\n"
}
-func (s *TenantSkillService) probeUv(ctx context.Context, mgr sandbox.Manager, sessionID string) bool {
- _, err := s.execInstall(ctx, mgr, sessionID, "uv --version")
- return err == nil
+// installProbeTools are the executables the installer agent reaches for. The
+// probe resolves each one's absolute path so the prompt can hand them over
+// instead of leaving the agent to burn a turn on `which` — or to gamble that
+// the shell_exec PATH contains, say, /root/.local/bin.
+var installProbeTools = []string{"uv", "npm", "pnpm", "pip3", "pip", "python3", "node"}
+
+// installToolsProbeCommand locates every probe tool in one shell pass. The if
+// guards the not-found case so the loop exits 0 whatever is missing: a tool
+// that is absent is a fact for the prompt, not an error.
+func installToolsProbeCommand() string {
+ var b strings.Builder
+ b.WriteString("for t in")
+ for _, t := range installProbeTools {
+ b.WriteByte(' ')
+ b.WriteString(t)
+ }
+ b.WriteString(`; do if p=$(command -v "$t" 2>/dev/null); then printf '%s=%s\n' "$t" "$p"; fi; done`)
+ return b.String()
+}
+
+// parseToolProbeOutput reads the probe's `name=path` lines. Anything else on
+// stdout is ignored: a tool line is the only thing the command emits, but the
+// prompt is better served by dropping noise than by failing the probe over it.
+func parseToolProbeOutput(stdout string) map[string]string {
+ tools := make(map[string]string)
+ for _, line := range strings.Split(stdout, "\n") {
+ name, p, found := strings.Cut(strings.TrimSpace(line), "=")
+ if found && name != "" && p != "" {
+ tools[name] = p
+ }
+ }
+ return tools
+}
+
+// probeInstallTools resolves the absolute paths of the package managers the
+// installer may reach for. One command, one round trip — the same probe
+// `uv available` used to cost, carrying every tool instead of one bit. A
+// failed probe is not an install failure: the prompt falls back to telling
+// the agent to discover the toolchain itself.
+func (s *TenantSkillService) probeInstallTools(
+ ctx context.Context, mgr sandbox.Manager, sessionID string,
+) map[string]string {
+ res, err := s.execInstall(ctx, mgr, sessionID, installToolsProbeCommand())
+ if err != nil || res == nil {
+ return nil
+ }
+ return parseToolProbeOutput(res.Stdout)
+}
+
+// formatToolchainSection renders the probe result for the prompt: one line
+// per tool with its absolute path, one line grouping whatever is missing.
+// An empty result — a probe that failed, or an image with none of the tools —
+// reads the same to the agent: locate them yourself before relying on PATH.
+func formatToolchainSection(tools map[string]string) string {
+ if len(tools) == 0 {
+ return "Toolchain: could not be probed in advance; " +
+ "locate tools with `command -v <tool>` before relying on PATH."
+ }
+ var b strings.Builder
+ b.WriteString("Toolchain (absolute paths as resolved in this image; prefer them over PATH):")
+ var missing []string
+ for _, t := range installProbeTools {
+ if p, ok := tools[t]; ok {
+ fmt.Fprintf(&b, "\n- %s: %s", t, p)
+ } else {
+ missing = append(missing, t)
+ }
+ }
+ if len(missing) > 0 {
+ b.WriteString("\nnot found: ")
+ b.WriteString(strings.Join(missing, ", "))
+ }
+ return b.String()
}
// installerAgentDefaults returns the platform's own definition of the installer
@@ -1793,6 +1926,7 @@ func installerAgentDefaults(ctx context.Context, tenantID uint64) *types.CustomA
// resolveInstallerModel.
func installerAgentConfig(defaults *types.CustomAgent, configID string) *types.AgentConfig {
memoryOff := false
+ thinkingOff := false
cfg := &types.AgentConfig{
MaxIterations: 30,
AllowedTools: []string{tools.ToolShellExec},
@@ -1801,6 +1935,10 @@ func installerAgentConfig(defaults *types.CustomAgent, configID string) *types.A
MCPSelectionMode: "none",
MemoryEnabled: &memoryOff,
SandboxConfigID: configID,
+ // Installs are short shell-command rounds, not reasoning tasks: pin
+ // thinking off instead of deferring to the model's own default, which
+ // burns latency and completion tokens on every ReAct round.
+ Thinking: &thinkingOff,
}
if defaults == nil {
return cfg
diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.go
index f5f470979..319c0f500 100644
--- a/internal/application/service/tenant_skill_install_test.go
+++ b/internal/application/service/tenant_skill_install_test.go
@@ -10,6 +10,7 @@ import (
"io"
"mime/multipart"
"os"
+ "os/exec"
"path"
"path/filepath"
"sort"
@@ -123,16 +124,12 @@ func TestRunInstallIssuesExactlyTheseCommands(t *testing.T) {
require.Equal(t, []string{
installPrepareCommand,
- "uv --version",
+ installToolsProbeCommand(),
seedExtractCommand(installSkillDir),
- "chmod -R 555 " + installSkillDir,
- "chown -R root:root " + installSkillDir,
- "test -f " + installSkillDir + "/SKILL.md",
- "test -f " + installSkillDir + "/scripts/extract.py",
+ "chmod -R 555 " + installSkillDir + " && chown -R root:root " + installSkillDir,
+ skillTreeVerifyCommand(installSkillDir, []string{"scripts/extract.py"}),
installPythonVerifyCommand,
- "rm -rf /workspace/* /workspace/.[!.]* || true",
- installWorkspaceRestoreCommand,
- installCacheCleanupCommand,
+ cleanImageScratchCommand(),
}, fx.commands)
}
@@ -165,7 +162,7 @@ func TestRunInstallReportsTransportFailureCause(t *testing.T) {
// Scoped to the command whose failure this test is about. An unscoped
// result failed the very first install command instead, so the structural
// verification this names was never reached.
- fx.execResultCommand = "test -f " + installSkillDir + "/SKILL.md"
+ fx.execResultCommand = skillTreeVerifyCommand(installSkillDir, []string{"scripts/extract.py"})
fx.execResult = &sandbox.ExecuteResult{
ExitCode: -1,
Killed: true,
@@ -175,7 +172,7 @@ func TestRunInstallReportsTransportFailureCause(t *testing.T) {
err := fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle)
require.Error(t, err)
- require.ErrorContains(t, err, "skill directory is incomplete after install",
+ require.ErrorContains(t, err, "skill tree verification failed",
"this is the structural verification's own failure path")
require.ErrorContains(t, err, "context deadline exceeded")
require.ErrorContains(t, err, "killed")
@@ -185,6 +182,173 @@ func TestRunInstallReportsTransportFailureCause(t *testing.T) {
"the admin's only diagnostic is this row")
}
+// The tree check's exit 1 is a protocol, not a crash: the findings travel as
+// stderr lines and are the whole message. The exec wrapper's generic
+// "command failed (...)" text must not shadow them.
+func TestRunInstallReportsTheMissingScriptByPath(t *testing.T) {
+ fx := newInstallFixture(t)
+ fx.execResultCommand = skillTreeVerifyCommand(installSkillDir, []string{"scripts/extract.py"})
+ fx.execResult = &sandbox.ExecuteResult{
+ ExitCode: 1,
+ Stderr: "script scripts/extract.py is missing after install",
+ }
+
+ err := fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle)
+
+ require.Error(t, err)
+ require.ErrorContains(t, err, "script scripts/extract.py is missing after install")
+ require.NotContains(t, err.Error(), "command failed",
+ "protocol exits speak for themselves")
+}
+
+// One round trip reports every missing file, not just the first: an install
+// that fails anyway may as well fail completely.
+func TestRunInstallCollectsEveryMissingFile(t *testing.T) {
+ fx := newInstallFixture(t)
+ fx.execResultCommand = skillTreeVerifyCommand(installSkillDir, []string{"scripts/extract.py"})
+ fx.execResult = &sandbox.ExecuteResult{
+ ExitCode: 1,
+ Stderr: "SKILL.md is missing after install\n" +
+ "script scripts/extract.py is missing after install",
+ }
+
+ err := fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle)
+
+ require.Error(t, err)
+ require.ErrorContains(t, err, "SKILL.md is missing after install")
+ require.ErrorContains(t, err, "script scripts/extract.py is missing after install")
+}
+
+// File names come from an uploaded archive; a metacharacter in one must stay
+// a literal, so every path reaches the command only through ShellQuote.
+func TestSkillTreeVerifyCommandQuotesPaths(t *testing.T) {
+ cmd := skillTreeVerifyCommand("/skills/de mo", []string{"scripts/a b.py", "it's.sh"})
+
+ require.Contains(t, cmd, sandbox.ShellQuote("/skills/de mo"))
+ require.Contains(t, cmd, sandbox.ShellQuote("scripts/a b.py"))
+ require.Contains(t, cmd, sandbox.ShellQuote("it's.sh"))
+}
+
+// The tree check costs one round trip however many scripts the bundle carries.
+func TestVerifySkillTreeIssuesOneCommandRegardlessOfScriptCount(t *testing.T) {
+ fx := newInstallFixture(t)
+ files := map[string][]byte{"SKILL.md": []byte(validSkillMD)}
+ rels := []string{"run.sh", "scripts/a.py", "scripts/b.py",
+ "scripts/c.py", "scripts/d.py", "scripts/e.py"}
+ for _, rel := range rels {
+ files[rel] = []byte("pass\n")
+ }
+
+ require.NoError(t, fx.svc.verifySkillTree(context.Background(),
+ fx.sandboxMgr, "sess-1", installSkillDir, &SkillBundle{Name: "pdf-tools", Files: files}))
+
+ require.Len(t, fx.commands, 1,
+ "one command for six scripts, not one command per script")
+ require.Equal(t, skillTreeVerifyCommand(installSkillDir, rels), fx.commands[0])
+}
+
+// The retention half of the cleanup runs for real inside the sandbox, so its
+// guard is tested against an actual shell: a cache under the budget survives,
+// an over-budget one is wiped whole, and the total is reported either way —
+// that report is the data the budget constant is tuned from.
+func TestCacheBudgetGuardKeepsSmallWipesBig(t *testing.T) {
+ dir := t.TempDir()
+ small := filepath.Join(dir, "small")
+ big := filepath.Join(dir, "big")
+ require.NoError(t, os.MkdirAll(small, 0o755))
+ require.NoError(t, os.MkdirAll(big, 0o755))
+ require.NoError(t, os.WriteFile(
+ filepath.Join(small, "tiny.whl"), bytes.Repeat([]byte("x"), 1024), 0o644))
+ require.NoError(t, os.WriteFile(
+ filepath.Join(big, "huge.whl"), bytes.Repeat([]byte("x"), 2<<20), 0o644))
+
+ kept, err := exec.Command("sh", "-c",
+ cacheBudgetGuardCommand([]string{small}, 1024)).CombinedOutput()
+ require.NoError(t, err, "the guard must always succeed: %s", kept)
+ require.DirExists(t, small, "a cache under the budget is kept")
+ require.Contains(t, string(kept), "cache total:")
+
+ wiped, err := exec.Command("sh", "-c",
+ cacheBudgetGuardCommand([]string{big}, 1024)).CombinedOutput()
+ require.NoError(t, err, "the guard must always succeed: %s", wiped)
+ require.NoDirExists(t, big, "a cache over the budget is wiped whole")
+ require.Contains(t, string(wiped), "wiped")
+}
+
+// The retention command is one opaque string to the sandbox; pinning its
+// structure here keeps the shell contract from drifting silently — in
+// particular that the workspace half still owns the exit code and the
+// retention half can only ever keep or lose caches.
+func TestCleanImageScratchCommandShape(t *testing.T) {
+ cmd := cleanImageScratchCommand()
+
+ require.Contains(t, cmd, "rm -rf /workspace/* /workspace/.[!.]* || true")
+ require.Contains(t, cmd, "mkdir -p")
+ require.Contains(t, cmd, "status=$?")
+ require.Contains(t, cmd, "exit $status")
+ require.Contains(t, cmd, "uv cache prune")
+ require.Contains(t, cmd, "npm cache verify")
+ require.Contains(t, cmd, "pnpm store prune")
+ require.Contains(t, cmd, "du -skc")
+ require.Contains(t, cmd, fmt.Sprintf("%d", skillCacheBudgetMB*1024))
+ require.Contains(t, cmd, "/root/.cache/uv")
+ require.Contains(t, cmd, "/home/"+sandbox.DefaultSandboxExecUser+"/.npm")
+
+ // And it must parse: the command is one opaque string to the sandbox, so a
+ // quoting mistake would only surface as a runtime failure there.
+ require.NoError(t, exec.Command("sh", "-n", "-c", cmd).Run(),
+ "the emitted command must parse under /bin/sh")
+}
+
+// The workspace half of the cleanup keeps its old failure semantics across the
+// merge: if the session account's input/output directories cannot be restored,
+// every session booting from the snapshot lands on a bare /workspace, and that
+// fails the install.
+func TestRunInstallFailsWhenTheWorkspaceRestoreFails(t *testing.T) {
+ fx := newInstallFixture(t)
+ fx.execResultCommand = cleanImageScratchCommand()
+ fx.execResult = &sandbox.ExecuteResult{
+ ExitCode: 1,
+ Stderr: "chown: cannot access '/workspace/input': No such file or directory",
+ }
+
+ err := fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle)
+
+ require.Error(t, err)
+ require.ErrorContains(t, err, "clean image scratch")
+}
+
+// The probe's stdout is the prompt's toolchain section; the parse keeps
+// exactly the `name=path` lines and drops everything else rather than
+// failing the install over noise.
+func TestParseToolProbeOutput(t *testing.T) {
+ tools := parseToolProbeOutput(
+ "uv=/root/.local/bin/uv\n" +
+ "not a tool line\n" +
+ "npm=\n" + // cut leaves an empty path: dropped
+ "python3=/usr/bin/python3\n" +
+ "\n")
+ require.Equal(t, map[string]string{
+ "uv": "/root/.local/bin/uv",
+ "python3": "/usr/bin/python3",
+ }, tools)
+}
+
+// The prompt section must name the present tools with their paths and group
+// the missing ones, so the agent neither re-discovers nor gambles on PATH.
+func TestFormatToolchainSection(t *testing.T) {
+ section := formatToolchainSection(map[string]string{
+ "uv": "/root/.local/bin/uv",
+ "python3": "/usr/bin/python3",
+ })
+ require.Contains(t, section, "- uv: /root/.local/bin/uv")
+ require.Contains(t, section, "- python3: /usr/bin/python3")
+ require.Contains(t, section, "not found: npm, pnpm, pip3, pip, node")
+
+ require.Contains(t, formatToolchainSection(nil),
+ "locate tools with `command -v <tool>`")
+}
+
func TestRunInstallReportsVerificationFailureCause(t *testing.T) {
fx := newInstallFixture(t)
fx.loadCheckResult = &sandbox.ExecuteResult{ExitCode: -1, Killed: true, Error: "sandbox unreachable"}
@@ -444,7 +608,9 @@ func storedAdminEnv() types.SkillEnvVars {
func TestBuildInstallPromptAsksForADeclarationWithoutValues(t *testing.T) {
fx := newInstallFixture(t)
- prompt := buildInstallPrompt(installSkillDir, fx.bundle, true)
+ prompt := buildInstallPrompt(installSkillDir, fx.bundle, map[string]string{
+ "uv": "/root/.local/bin/uv", "python3": "/usr/bin/python3",
+ })
require.Contains(t, prompt, sandbox.SkillRequirementsPath(fx.bundle.Name))
require.Contains(t, prompt, ".weknora/requirements.json")
@@ -458,13 +624,17 @@ func TestBuildInstallPromptAsksForADeclarationWithoutValues(t *testing.T) {
require.Contains(t, prompt, "install_deps.py")
require.Contains(t, prompt, "write_sandbox_file is not available")
require.Contains(t, prompt, "short shell redirect")
+ require.Contains(t, prompt, "- uv: /root/.local/bin/uv",
+ "the prompt hands over absolute paths instead of a PATH gamble")
}
func TestBuildInstallPromptNamesOnDemandInstallerInTheArchive(t *testing.T) {
fx := newInstallFixture(t)
fx.bundle.Files["scripts/install_deps.py"] = []byte("print(1)\n")
- prompt := buildInstallPrompt(installSkillDir, fx.bundle, true)
+ prompt := buildInstallPrompt(installSkillDir, fx.bundle, map[string]string{
+ "uv": "/root/.local/bin/uv", "python3": "/usr/bin/python3",
+ })
require.Contains(t, prompt, "This archive ships on-demand installer(s)")
require.Contains(t, prompt, "scripts/install_deps.py")
@@ -474,7 +644,9 @@ func TestBuildInstallPromptMentionsRepairedFrontmatter(t *testing.T) {
fx := newInstallFixture(t)
fx.bundle.FrontmatterRepaired = true
- prompt := buildInstallPrompt(installSkillDir, fx.bundle, true)
+ prompt := buildInstallPrompt(installSkillDir, fx.bundle, map[string]string{
+ "uv": "/root/.local/bin/uv", "python3": "/usr/bin/python3",
+ })
require.Contains(t, prompt, "YAML frontmatter was automatically repaired")
require.Contains(t, prompt, "Mention this in your summary")
@@ -1678,19 +1850,6 @@ const (
" && mkdir -p /opt/weknora/tenant/skills " + installSkillDir +
" && chown user:user /opt/weknora/tenant/skills " + installSkillDir +
" && chmod 755 /opt/weknora/tenant/skills " + installSkillDir
-
- // The scratch wipe removes the base image's own input/output directories,
- // so the snapshot must carry them back with the ownership the session
- // account needs. This is the only step of an install that runs with the
- // privileges required to set that ownership.
- installWorkspaceRestoreCommand = "mkdir -p /workspace/input /workspace/output" +
- " && chown user:user /workspace/input /workspace/output" +
- " && chmod 775 /workspace/input /workspace/output"
-
- installCacheCleanupCommand = "rm -rf " +
- "/root/.cache/pip /root/.cache/uv /root/.npm /root/.local/share/pnpm/store " +
- "/home/user/.cache/pip /home/user/.cache/uv /home/user/.npm " +
- "/home/user/.local/share/pnpm/store || true"
)
// installPythonVerifyCommand is built from the same helper the install path
@@ -2740,7 +2899,7 @@ func (m *installSandboxManager) ExecShellCommandWithOptions(
m.fx.record("prepare-skill-dir")
case strings.HasPrefix(command, "tar -xf "):
m.extractSeedArchive(command)
- case strings.HasPrefix(command, "test -f "):
+ case command == skillTreeVerifyCommand(installSkillDir, []string{"scripts/extract.py"}):
if !m.structureSeen {
m.fx.record("verify-structure")
m.structureSeen = true
@@ -2772,7 +2931,7 @@ func (m *installSandboxManager) ExecShellCommandWithOptions(
return &sandbox.ExecuteResult{
ExitCode: m.fx.rmExitCode, Stderr: "rm: cannot remove",
}, nil
- case command == "rm -rf /workspace/* /workspace/.[!.]* || true":
+ case command == cleanImageScratchCommand():
m.fx.record("cleanup-workspace")
case strings.HasPrefix(command, "chmod -R 555 "):
m.fx.record("chmod")
diff --git a/internal/application/service/tenant_skill_transcript.go b/internal/application/service/tenant_skill_transcript.go
index ed34d02ae..c08a070f3 100644
--- a/internal/application/service/tenant_skill_transcript.go
+++ b/internal/application/service/tenant_skill_transcript.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"fmt"
+ "math"
"strings"
"sync"
"time"
@@ -49,6 +50,16 @@ type installTranscript struct {
// terminal event Finish emits.
totalSteps int
totalDurationMs int64
+
+ // Activity progress fills the long stretch between the seeded anchor (35%)
+ // and agent_done (80%) while the installer is actually working. Every tool
+ // call the bus already delivers advances an asymptotic percent, so the bar
+ // moves without knowing how many rounds the agent will run. onActivity is
+ // wired only by the install path; the remove path and most tests leave it
+ // nil and nothing publishes.
+ onActivity func(steps int, lastCmd string)
+ toolCalls int
+ progressMuted bool
}
// installAnswerSegment accumulates the prose streamed under one final-answer
@@ -73,6 +84,7 @@ func newInstallTranscript(
streams interfaces.StreamManager,
messages interfaces.MessageRepository,
sessionID, assistantMessageID string,
+ onActivity func(steps int, lastCmd string),
) *installTranscript {
return &installTranscript{
ctx: ctx,
@@ -82,6 +94,7 @@ func newInstallTranscript(
sessionID: sessionID,
assistantMessageID: assistantMessageID,
starts: map[string]time.Time{},
+ onActivity: onActivity,
}
}
@@ -251,6 +264,14 @@ func (tr *installTranscript) onToolCall(_ context.Context, evt event.Event) erro
seg.superseded = true
}
}
+ // One command is one step of the asymptotic progress. Muted runs (after
+ // the first round ends) stop counting so a repair round cannot drag the
+ // bar back under the stage anchors that govern it by then.
+ steps, lastCmd := 0, ""
+ if !tr.progressMuted {
+ tr.toolCalls++
+ steps, lastCmd = tr.toolCalls, installToolCallSummary(data)
+ }
tr.mu.Unlock()
tr.append(interfaces.StreamEvent{
@@ -264,6 +285,9 @@ func (tr *installTranscript) onToolCall(_ context.Context, evt event.Event) erro
"tool_call_id": data.ToolCallID,
},
})
+ if steps > 0 && tr.onActivity != nil {
+ tr.onActivity(steps, lastCmd)
+ }
return nil
}
@@ -475,3 +499,59 @@ func (tr *installTranscript) save(ctx context.Context) {
logger.Warnf(ctx, "[skill] persist install transcript %s failed: %v", tr.sessionID, err)
}
}
+
+// progressLogMaxRunes caps the one-line command summary the progress card
+// shows. The card is one line tall; a heredoc would flatten it.
+const progressLogMaxRunes = 80
+
+// installToolCallSummary condenses one tool call into the one-line log the
+// progress card shows. The engine's own hint (e.g. `shell_exec: uv venv
+// .venv`) is preferred when it has one; otherwise the shell command is used.
+func installToolCallSummary(data event.AgentToolCallData) string {
+ summary := strings.TrimSpace(data.Hint)
+ if summary == "" {
+ if cmd, ok := data.Arguments["command"].(string); ok && strings.TrimSpace(cmd) != "" {
+ summary = fmt.Sprintf("%s: %s", data.ToolName, strings.TrimSpace(cmd))
+ } else {
+ summary = data.ToolName
+ }
+ }
+ summary = strings.ReplaceAll(summary, "\n", " ")
+ if runes := []rune(summary); len(runes) > progressLogMaxRunes {
+ summary = string(runes[:progressLogMaxRunes]) + "…"
+ }
+ return summary
+}
+
+// muteActivityProgress stops the asymptotic progress wherever it has reached.
+// Called once the first installer round ends: everything after it —
+// verification and any repair rounds — is covered by the explicit stage
+// anchors (agent_done 80, repairing 82), and tool calls from a repair round
+// publishing again would drag the bar back below those anchors.
+func (tr *installTranscript) muteActivityProgress() {
+ if tr == nil {
+ return
+ }
+ tr.mu.Lock()
+ tr.progressMuted = true
+ tr.mu.Unlock()
+}
+
+// asymptoticInstallPercent fills the 35→79 span with no knowledge of the
+// total: each command advances the bar by a shrinking share of what is left,
+// so the curve is monotonic for any round count and converges below the
+// agent_done anchor at 80 — never past it, never stalls on the way.
+//
+// The shape is 35 + 44·(1 − e^(−k/12)): the first command moves ~4 points, the
+// tenth ~60%, the twentieth ~71%, and even a run that exhausts
+// max_iterations=30 only reaches ~75, still short of the 79 ceiling.
+func asymptoticInstallPercent(k int) int {
+ if k <= 0 {
+ return 35
+ }
+ p := 35 + int(math.Round(44*(1-math.Exp(-float64(k)/12.0))))
+ if p > 79 {
+ return 79
+ }
+ return p
+}
diff --git a/internal/application/service/tenant_skill_transcript_test.go b/internal/application/service/tenant_skill_transcript_test.go
index ddce68585..7883b435d 100644
--- a/internal/application/service/tenant_skill_transcript_test.go
+++ b/internal/application/service/tenant_skill_transcript_test.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"errors"
+ "strings"
"testing"
"github.com/stretchr/testify/require"
@@ -69,7 +70,7 @@ func newTranscriptForTest(t *testing.T) (
bus := event.NewEventBus()
streams := &transcriptStreams{}
messages := &transcriptMessages{}
- tr := newInstallTranscript(context.Background(), bus, streams, messages, "sess-1", "msg-1")
+ tr := newInstallTranscript(context.Background(), bus, streams, messages, "sess-1", "msg-1", nil)
tr.Subscribe()
return tr, bus, streams, messages
}
@@ -225,7 +226,7 @@ func TestInstallTranscriptSwallowsItsOwnFailures(t *testing.T) {
bus := event.NewEventBus()
streams := &transcriptStreams{err: errors.New("redis down")}
messages := &transcriptMessages{err: errors.New("db down")}
- tr := newInstallTranscript(context.Background(), bus, streams, messages, "sess-1", "msg-1")
+ tr := newInstallTranscript(context.Background(), bus, streams, messages, "sess-1", "msg-1", nil)
tr.Subscribe()
require.NoError(t, bus.Emit(context.Background(), event.Event{
@@ -239,7 +240,7 @@ func TestInstallTranscriptCreateSeedsTheAssistantRow(t *testing.T) {
streams := &transcriptStreams{}
messages := &transcriptMessages{}
tr := newInstallTranscript(
- context.Background(), event.NewEventBus(), streams, messages, "sess-1", "msg-1",
+ context.Background(), event.NewEventBus(), streams, messages, "sess-1", "msg-1", nil,
)
require.NoError(t, tr.Create(context.Background(), "install pdf-tools"))
@@ -257,7 +258,7 @@ func TestInstallTranscriptCreateSeedsTheAssistantRow(t *testing.T) {
func TestInstallTranscriptCreateOpensTheLogWithThePrompt(t *testing.T) {
streams := &transcriptStreams{}
tr := newInstallTranscript(
- context.Background(), event.NewEventBus(), streams, &transcriptMessages{}, "sess-1", "msg-1",
+ context.Background(), event.NewEventBus(), streams, &transcriptMessages{}, "sess-1", "msg-1", nil,
)
require.NoError(t, tr.Create(context.Background(), "install pdf-tools"))
@@ -318,3 +319,97 @@ func TestInstallTranscriptFinishIsIdempotent(t *testing.T) {
}, streams.types())
require.Len(t, messages.updated, 1)
}
+
+func TestAsymptoticInstallPercent(t *testing.T) {
+ require.Equal(t, 35, asymptoticInstallPercent(0))
+ require.Equal(t, 35, asymptoticInstallPercent(-3), "no commands yet means the seeded anchor")
+
+ // The first command lifts the bar visibly; the exact value pins the curve.
+ require.Equal(t, 39, asymptoticInstallPercent(1))
+ require.Equal(t, 42, asymptoticInstallPercent(2))
+
+ // Monotonic for any round count, always below the agent_done anchor at 80,
+ // and converged to the ceiling once a run exhausts max_iterations.
+ prev := 0
+ for k := 1; k <= 200; k++ {
+ p := asymptoticInstallPercent(k)
+ require.GreaterOrEqual(t, p, prev)
+ require.LessOrEqual(t, p, 79)
+ prev = p
+ }
+ require.Equal(t, 79, asymptoticInstallPercent(200))
+ // A run that exhausts max_iterations=30 tops out around 75 — the ceiling
+ // belongs to the stage anchor, not to any finite command count.
+ require.Equal(t, 75, asymptoticInstallPercent(30))
+}
+
+// The progress card watches the same bus the transcript does, so every command
+// the installer runs is one step forward — with a one-line summary of what it
+// was — and muting after the first round stops the flow entirely.
+func TestInstallTranscriptPublishesActivityProgressOnToolCalls(t *testing.T) {
+ bus := event.NewEventBus()
+ streams := &transcriptStreams{}
+ messages := &transcriptMessages{}
+ type activity struct {
+ steps int
+ lastCmd string
+ }
+ var got []activity
+ tr := newInstallTranscript(context.Background(), bus, streams, messages, "sess-1", "msg-1",
+ func(steps int, lastCmd string) { got = append(got, activity{steps, lastCmd}) })
+ tr.Subscribe()
+ ctx := context.Background()
+
+ emitCall := func(id string, data event.AgentToolCallData) {
+ data.ToolCallID = id
+ require.NoError(t, bus.Emit(ctx, event.Event{
+ ID: id, Type: event.EventAgentToolCall, Data: data,
+ }))
+ }
+ emitCall("c-1", event.AgentToolCallData{
+ ToolName: "shell_exec", Arguments: map[string]any{"command": "uv venv .venv"},
+ })
+ emitCall("c-2", event.AgentToolCallData{
+ ToolName: "shell_exec", Hint: `shell_exec: apt-get install -y libgl1`,
+ })
+ emitCall("c-3", event.AgentToolCallData{
+ ToolName: "shell_exec",
+ Arguments: map[string]any{"command": "uv pip install --python .venv/bin/python " +
+ strings.Repeat("very-long-package-name-", 12)},
+ })
+
+ require.Len(t, got, 3)
+ require.Equal(t, 1, got[0].steps)
+ require.Equal(t, "shell_exec: uv venv .venv", got[0].lastCmd)
+ require.Equal(t, `shell_exec: apt-get install -y libgl1`, got[1].lastCmd,
+ "the engine's hint is preferred when it has one")
+ require.Equal(t, 3, got[2].steps)
+ require.Less(t, len([]rune(got[2].lastCmd)), 90, "a long command is truncated to one line")
+
+ // A repair round must not drag the bar back below the stage anchors, so
+ // muting after the first round ends the activity publishes for good.
+ tr.muteActivityProgress()
+ emitCall("c-4", event.AgentToolCallData{
+ ToolName: "shell_exec", Arguments: map[string]any{"command": "uv pip install defusedxml"},
+ })
+ require.Len(t, got, 3)
+}
+
+// A transcript without a publisher (remove path, most tests) counts nothing
+// and calls nothing.
+func TestInstallTranscriptWithoutActivityPublisherStaysSilent(t *testing.T) {
+ tr, bus, streams, _ := newTranscriptForTest(t)
+
+ require.NoError(t, bus.Emit(context.Background(), event.Event{
+ ID: "c-1", Type: event.EventAgentToolCall,
+ Data: event.AgentToolCallData{
+ ToolName: "shell_exec", ToolCallID: "call-1",
+ Arguments: map[string]any{"command": "uv venv .venv"},
+ },
+ }))
+ tr.muteActivityProgress()
+
+ require.NotPanics(t, func() { tr.Finish(context.Background(), nil) })
+ require.Equal(t, []types.ResponseType{types.ResponseTypeToolCall, types.ResponseTypeComplete},
+ streams.types(), "the transcript itself is unchanged by progress being unwired")
+}
diff --git a/internal/application/service/tenant_skill_verify.go b/internal/application/service/tenant_skill_verify.go
index 1e63645ff..c7b8d0033 100644
--- a/internal/application/service/tenant_skill_verify.go
+++ b/internal/application/service/tenant_skill_verify.go
@@ -5,6 +5,7 @@ import (
_ "embed"
"encoding/base64"
"encoding/json"
+ "errors"
"fmt"
"path"
"sort"
@@ -26,6 +27,12 @@ var skillPythonVerifier string
// is the only distinction that decides what the install flow does next.
const skillVerifyRepairableExit = 2
+// skillTreeVerifyDirExit is the exit code the tree check uses when the skill
+// directory itself is gone, so no file inside it can be probed. Exit 1 is the
+// shared "every finding is one stderr line" code; exit 0 means everything the
+// bundle names is still in place.
+const skillTreeVerifyDirExit = 3
+
// skillVerifyNotePrefix marks a line the checker reports without refusing the
// install. Notes travel on stdout so a non-zero exit stays unambiguous.
const skillVerifyNotePrefix = "note: "
@@ -87,21 +94,64 @@ func (s *TenantSkillService) verifySkill(
// verifySkillTree confirms the files the agent was given are still the files
// the image carries. The agent has a root shell in this directory, so "we
// wrote it before the agent ran" is not evidence that it survived.
+//
+// The whole check is one command and one round trip, however many files the
+// bundle carries: a missing file costs one remote exec per call otherwise, and
+// a skill with dozens of scripts was spending minutes on that round-trip tax.
+// Every missing file is reported on its own stderr line and the check keeps
+// going, so one round trip returns every finding instead of stopping at the
+// first — an install that fails anyway may as well fail completely.
func (s *TenantSkillService) verifySkillTree(
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, bundle *SkillBundle,
) error {
- if _, err := s.execInstall(ctx, mgr, sessionID,
- fmt.Sprintf("test -f %s", sandbox.ShellQuote(path.Join(skillDir, "SKILL.md")))); err != nil {
- return fmt.Errorf("skill directory is incomplete after install: %w", err)
+ res, err := s.execInstall(ctx, mgr, sessionID,
+ skillTreeVerifyCommand(skillDir, sortedScriptPaths(bundle, allScriptExtensions...)))
+ if err == nil {
+ return nil
}
- for _, rel := range sortedScriptPaths(bundle, allScriptExtensions...) {
- target := path.Join(skillDir, rel)
- if _, err := s.execInstall(ctx, mgr, sessionID,
- fmt.Sprintf("test -f %s", sandbox.ShellQuote(target))); err != nil {
- return fmt.Errorf("script %s is missing after install: %w", rel, err)
+ if res != nil {
+ switch res.ExitCode {
+ case skillTreeVerifyDirExit:
+ // The directory itself is gone; nothing inside it could be probed
+ // and the command already said exactly that.
+ return errors.New("skill directory is incomplete after install")
+ case 1:
+ // The command's own protocol: exit 1 means every finding is one
+ // stderr line, and those lines are the final message. Any other
+ // non-zero exit has no protocol behind it and falls through to
+ // the transport wrapping below rather than promoting arbitrary
+ // stderr noise to a verdict.
+ if lines := verificationProblems(res.Stderr); len(lines) > 0 {
+ return errors.New(strings.Join(lines, "; "))
+ }
}
}
- return nil
+ return fmt.Errorf("skill tree verification failed: %w", err)
+}
+
+// skillTreeVerifyCommand folds the structural check into one command: the
+// SKILL.md probe plus one test per bundled script, each missing file reported
+// without stopping the rest. It cds into the skill directory and iterates
+// relative paths, which makes every stderr line the final user-facing message
+// — the Go side never has to reassemble one. Paths reach the command only
+// through ShellQuote: a file name comes from an uploaded archive, and a
+// metacharacter in one must stay a literal.
+func skillTreeVerifyCommand(skillDir string, scripts []string) string {
+ var b strings.Builder
+ fmt.Fprintf(&b, "cd %s || { echo 'skill directory is incomplete after install' >&2; exit %d; }",
+ sandbox.ShellQuote(skillDir), skillTreeVerifyDirExit)
+ b.WriteString("; status=0")
+ b.WriteString("; [ -f 'SKILL.md' ] || { echo 'SKILL.md is missing after install' >&2; status=1; }")
+ if len(scripts) > 0 {
+ b.WriteString("; for f in")
+ for _, rel := range scripts {
+ b.WriteByte(' ')
+ b.WriteString(sandbox.ShellQuote(rel))
+ }
+ b.WriteString(`; do [ -f "$f" ] || { echo "script $f is missing after install" >&2; status=1; }; done`)
+ }
+ b.WriteString("; exit $status")
+ return b.String()
}
// verifyDeclaredDependencies checks that the isolated trees the installer was
diff --git a/internal/application/service/tenant_skill_verify.py b/internal/application/service/tenant_skill_verify.py
index 78d6264dd..7e95daed3 100644
--- a/internal/application/service/tenant_skill_verify.py
+++ b/internal/application/service/tenant_skill_verify.py
@@ -26,7 +26,7 @@ minutes of dependency work and leaves the previous image serving.
exit 0 the image may be kept
exit 1 a problem no installer round can fix: a syntax error, a file the
execution user cannot read, a relative import that can never
- resolve
+ resolve, a shipped module the import cannot reach
exit 2 every problem is a dependency missing from this image, so handing
these lines back to the installer is worth a round
@@ -72,6 +72,40 @@ unrepairable = False
# a file there; any other prefix is only on sys.path if the skill puts it there.
script_dirs = {os.path.dirname(os.path.join(root, rel)) for rel in all_scripts}
+# ---------------------------------------------------------------------------
+# Third resolution tier: modules the tree itself ships, reached by the
+# script's own sys.path bootstrap.
+#
+# A sibling subtree is never an ancestor, so static resolution cannot see
+# lib/image_video.py from scripts/generate.py - and that is the runtime truth
+# too, until the script puts lib/ on sys.path itself. The scan below records
+# what the tree ships; the evaluator further down decides whether the
+# bootstrap provably reaches it. Only a proven bridge turns a missing import
+# into a note; anything unprovable stays a problem, which is what keeps
+# vendor/requests.py from satisfying `import requests` for a script that
+# never bridges to it.
+
+skip_tree_dirs = {".venv", "node_modules", "__pycache__", ".weknora"}
+
+# name -> root-relative paths of the files providing it ("lib/image_video.py",
+# "scripts/__init__.py"). Built from the uploaded sources only: .venv and the
+# other install-created directories are pruned, because packages pip placed
+# there are not the skill's own code and must not count as shipped.
+shipped_modules = {}
+for _dirpath, _dirnames, _filenames in os.walk(root):
+ _dirnames[:] = sorted(
+ d for d in _dirnames if d not in skip_tree_dirs and not d.startswith(".")
+ )
+ for _filename in _filenames:
+ _stem, _ext = os.path.splitext(_filename)
+ if _ext != ".py":
+ continue
+ _rel = os.path.relpath(os.path.join(_dirpath, _filename), root).replace(os.sep, "/")
+ if _stem == "__init__":
+ shipped_modules.setdefault(os.path.basename(_dirpath), []).append(_rel)
+ else:
+ shipped_modules.setdefault(_stem, []).append(_rel)
+
def add_problem(message, repairable=False):
global unrepairable
@@ -184,6 +218,103 @@ def resolve_top_level(name, script_path):
return ""
+def dotted_name(node):
+ """'os.path.join' for a Name/Attribute chain, else None."""
+ parts = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if isinstance(node, ast.Name):
+ parts.append(node.id)
+ return ".".join(reversed(parts))
+ return None
+
+
+def static_path_of(node, script_path, env):
+ """Evaluate an expression that is supposed to name a directory.
+
+ Accepts only the shapes a sys.path bootstrap is written with in practice:
+ string literals, __file__, os.path.dirname/abspath/realpath/join, pathlib
+ Path(...).resolve()/absolute()/parent chains with / joins, str(...), and
+ plain names previously assigned one of those. A relative literal is fine
+ as a join component ('..', 'lib'); only the final sys.path entry must be
+ absolute, which bootstrap_push enforces. Everything else - variables the
+ scan cannot see, os.environ, any other call - returns None. The evaluator
+ must never guess: a wrong guess turns a broken import into a passing
+ install.
+ """
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
+ return os.path.normpath(node.value)
+ if isinstance(node, ast.Name):
+ if node.id == "__file__":
+ return os.path.normpath(os.path.abspath(script_path))
+ return env.get(node.id)
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Div):
+ left = static_path_of(node.left, script_path, env)
+ right = static_path_of(node.right, script_path, env)
+ if left is None or right is None:
+ return None
+ return os.path.normpath(os.path.join(left, right))
+ if isinstance(node, ast.Call):
+ if node.keywords:
+ return None
+ name = dotted_name(node.func)
+ args = node.args
+ if name == "os.path.join" and args:
+ parts = [static_path_of(a, script_path, env) for a in args]
+ if any(part is None for part in parts):
+ return None
+ return os.path.normpath(os.path.join(*parts))
+ if name in ("os.path.dirname", "os.path.abspath", "os.path.realpath") and len(args) == 1:
+ base = static_path_of(args[0], script_path, env)
+ if base is None:
+ return None
+ return os.path.dirname(base) if name == "os.path.dirname" else base
+ if name in ("str", "Path", "pathlib.Path") and len(args) == 1:
+ return static_path_of(args[0], script_path, env)
+ if (
+ isinstance(node.func, ast.Attribute)
+ and not args
+ and node.func.attr in ("resolve", "absolute")
+ ):
+ return static_path_of(node.func.value, script_path, env)
+ return None
+ if isinstance(node, ast.Attribute) and node.attr == "parent":
+ base = static_path_of(node.value, script_path, env)
+ return None if base is None else os.path.dirname(base)
+ return None
+
+
+def bootstrap_push(node, script_path, env, out):
+ """Record the directory a top-level sys.path.insert/append call adds.
+
+ append(path) and insert(index, path) both push args[-1]. A call whose
+ argument cannot be evaluated records None - an unverified bridge, which
+ the caller must treat as reaching nothing.
+ """
+ if not isinstance(node, ast.Expr) or not isinstance(node.value, ast.Call):
+ return
+ call = node.value
+ func = call.func
+ if not (isinstance(func, ast.Attribute) and func.attr in ("insert", "append")):
+ return
+ target = func.value
+ if not (
+ isinstance(target, ast.Attribute)
+ and target.attr == "path"
+ and isinstance(target.value, ast.Name)
+ and target.value.id == "sys"
+ ):
+ return
+ if call.keywords or not call.args:
+ out.append(None)
+ return
+ path = static_path_of(call.args[-1], script_path, env)
+ # A relative result would resolve against the runtime's cwd, which the
+ # scan cannot know - as unknowable as an unevaluable expression.
+ out.append(path if path is not None and os.path.isabs(path) else None)
+
+
def check_imports(rel, tree, script_path, report):
"""Check the imports that loading this file is guaranteed to execute.
@@ -191,20 +322,38 @@ def check_imports(rel, tree, script_path, report):
import nested in try/except, in an `if`, or inside a function is how a
skill declares an optional or lazily loaded dependency, and failing an
install over one would reject a working skill.
+
+ The single ordered pass matters: a sys.path bootstrap only helps imports
+ that come after it, so each import is checked against the bridges the
+ statements before it have raised. Plain string assignments are tracked
+ too, because the idiomatic bootstrap names its path in a variable first
+ (script_dir = ...; lib_dir = ...; sys.path.insert(0, lib_dir)).
"""
script_dir = os.path.dirname(script_path)
+ env = {}
+ bootstraps = []
for node in tree.body:
+ if (
+ isinstance(node, ast.Assign)
+ and len(node.targets) == 1
+ and isinstance(node.targets[0], ast.Name)
+ ):
+ value = static_path_of(node.value, script_path, env)
+ if value is not None:
+ env[node.targets[0].id] = value
+ continue
+ bootstrap_push(node, script_path, env, bootstraps)
if isinstance(node, ast.Import):
for alias in node.names:
- check_absolute_import(rel, alias.name, script_path, report)
+ check_absolute_import(rel, alias.name, script_path, bootstraps, report)
elif isinstance(node, ast.ImportFrom):
if node.level:
check_relative_import(rel, node, script_dir, report)
elif node.module:
- check_absolute_import(rel, node.module, script_path, report)
+ check_absolute_import(rel, node.module, script_path, bootstraps, report)
-def check_absolute_import(rel, dotted, script_path, report):
+def check_absolute_import(rel, dotted, script_path, bootstraps, report):
name = dotted.split(".")[0]
origin = resolve_top_level(name, script_path)
if origin == "image":
@@ -216,9 +365,45 @@ def check_absolute_import(rel, dotted, script_path, report):
"directory on sys.path itself" % (rel, name)
)
return
+ providers = shipped_modules.get(name)
+ if not providers:
+ report(
+ "%s imports %s, which is not available in this image" % (rel, name),
+ repairable=True,
+ )
+ return
+ # The tree itself provides the module; whether the import resolves at
+ # runtime depends solely on the script's own bootstrap. Only a bootstrap
+ # proven to raise one of the providing directories counts.
+ bridged_dirs = {
+ os.path.relpath(b, root).replace(os.sep, "/")
+ for b in bootstraps
+ if b is not None
+ }
+ reached = [p for p in providers if os.path.dirname(p) in bridged_dirs]
+ if reached:
+ add_note(
+ "%s imports %s, which the skill ships at %s and reaches via its "
+ "own sys.path bootstrap" % (rel, name, ", ".join(reached))
+ )
+ return
+ if not bootstraps:
+ why = "the file puts no directory on sys.path"
+ elif any(b is None for b in bootstraps):
+ why = "its sys.path bootstrap cannot be verified statically"
+ else:
+ why = "its sys.path bootstrap reaches elsewhere"
+ # Unrepairable on purpose. The repair round installs packages and is
+ # forbidden from editing the skill's own files, so neither of its moves
+ # can fix a shipped module the import cannot reach - installing a
+ # same-named distribution would only shadow the skill's own code, and a
+ # source edit would diverge the installed tree from the uploaded archive.
+ # The bundle has to change, and this line says exactly where.
report(
- "%s imports %s, which is not available in this image" % (rel, name),
- repairable=True,
+ "%s imports %s, which the skill ships at %s, but the import cannot "
+ "resolve at runtime (%s); no package install provides a skill's own "
+ "module - fix the import's reachability in the archive and re-upload"
+ % (rel, name, ", ".join(providers), why),
)
diff --git a/internal/application/service/tenant_skill_verify_python_test.go b/internal/application/service/tenant_skill_verify_python_test.go
index 1bfbf26a5..4d419bba0 100644
--- a/internal/application/service/tenant_skill_verify_python_test.go
+++ b/internal/application/service/tenant_skill_verify_python_test.go
@@ -180,14 +180,17 @@ func TestSkillPythonVerifier(t *testing.T) {
"scripts/run.py": "x = 1\n",
},
}, {
+ // The vendor guarantee: a sibling module sharing an import's name does
+ // not make the import resolve. The wording names the shipped file so a
+ // repair round knows no package install will help.
name: "a nested file name is not treated as a first-party import",
files: map[string]string{
"vendor/totally_absent_package.py": "x = 1\n",
"scripts/run.py": "import totally_absent_package\n",
},
wantProblem: "scripts/run.py imports totally_absent_package, " +
- "which is not available in this image",
- wantExit: 2,
+ "which the skill ships at vendor/totally_absent_package.py",
+ wantExit: 1,
}, {
// The official Anthropic office toolkit (xlsx/docx/pptx): a non-package
// directory holds entry scripts plus sibling packages. Library modules
@@ -267,6 +270,92 @@ func TestSkillPythonVerifier(t *testing.T) {
"--index-url https://example.com/simple\n",
"scripts/run.py": "x = 1\n",
},
+ }, {
+ // The lib/ + sys.path bootstrap layout - the shape that failed a real
+ // install. Static resolution cannot see the bridge, but the script's
+ // own bootstrap provably raises the directory that ships the module,
+ // so the install passes with a note instead of a missing dependency.
+ name: "a script that bootstraps a sibling lib directory and imports from it",
+ files: map[string]string{
+ "lib/image_video.py": "def generate_image():\n pass\n",
+ "scripts/generate.py": "import sys\nimport os\n" +
+ "script_dir = os.path.dirname(os.path.abspath(__file__))\n" +
+ "lib_dir = os.path.join(script_dir, '..', 'lib')\n" +
+ "sys.path.insert(0, lib_dir)\n" +
+ "from image_video import generate_image\n",
+ },
+ wantNote: "which the skill ships at lib/image_video.py",
+ }, {
+ // The pathlib idiom must evaluate to the same bridge.
+ name: "a pathlib bootstrap reaching a sibling module",
+ files: map[string]string{
+ "lib/helper.py": "x = 1\n",
+ "scripts/runner.py": "import sys\n" +
+ "from pathlib import Path\n" +
+ "sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'lib'))\n" +
+ "import helper\n",
+ },
+ wantNote: "which the skill ships at lib/helper.py",
+ }, {
+ // The same shape without the bridge cannot resolve at runtime, and no
+ // package install provides a skill's own module - the finding names
+ // the shipped file instead of pretending a dependency is missing, and
+ // fails the install outright: a repair round can neither install a
+ // fix nor edit the tree.
+ name: "a script importing a lib module without a sys.path bootstrap",
+ files: map[string]string{
+ "lib/image_video.py": "def generate_image():\n pass\n",
+ "scripts/generate.py": "from image_video import generate_image\n",
+ },
+ wantProblem: "which the skill ships at lib/image_video.py",
+ wantExit: 1,
+ }, {
+ // The vendor guarantee holds inside the new tier: a sibling module
+ // sharing a dependency's name is still unresolvable unless the
+ // script's own bootstrap provably reaches it. (A neutral name keeps
+ // the case immune to whatever happens to be importable in the
+ // environment running the tests.)
+ name: "a vendored module must not satisfy an import without a bootstrap",
+ files: map[string]string{
+ "vendor/bridge_helper.py": "x = 1\n",
+ "scripts/run.py": "import bridge_helper\n",
+ },
+ wantProblem: "which the skill ships at vendor/bridge_helper.py",
+ wantExit: 1,
+ }, {
+ // ...and when the bootstrap does reach the vendored copy, the script
+ // genuinely works: reported, not refused.
+ name: "a bootstrap that reaches the vendored copy is a note",
+ files: map[string]string{
+ "vendor/bridge_helper.py": "x = 1\n",
+ "scripts/run.py": "import sys, os\n" +
+ "sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'vendor'))\n" +
+ "import bridge_helper\n",
+ },
+ wantNote: "which the skill ships at vendor/bridge_helper.py",
+ }, {
+ // A bridge the evaluator cannot prove stays a problem: guessing would
+ // be exactly the false pass the vendor rule exists to prevent.
+ name: "an unprovable bootstrap stays a problem",
+ files: map[string]string{
+ "lib/image_video.py": "def generate_image():\n pass\n",
+ "scripts/generate.py": "import sys, os\n" +
+ "sys.path.insert(0, os.environ['LIB_DIR'])\n" +
+ "from image_video import generate_image\n",
+ },
+ wantProblem: "cannot be verified statically",
+ wantExit: 1,
+ }, {
+ // Packages pip placed under .venv are not the skill's own code; the
+ // scan must not turn a genuinely missing dependency into a shipped
+ // note.
+ name: "a module that only exists under .venv is still missing",
+ files: map[string]string{
+ ".venv/lib/python3.11/site-packages/ghost_mod.py": "x = 1\n",
+ "scripts/run.py": "import ghost_mod\n",
+ },
+ wantProblem: "not available in this image",
+ wantExit: 2,
}}
for _, tc := range cases {