Skip to content

Commit e807448

Browse files
sahrizviclaude
andcommitted
fix(workspace): publish the whole bundle as a replacement, and tell the update path's conflicts apart
Sarav's review. `files` replaces the bundle server-side, and a path it omits is a deletion the server refuses unless the caller says so — so deleting a file locally and publishing again 409'd, forever, and the 409 was reported as a name conflict: "it was published from somewhere else, rename this one". The name was never the problem, renaming does not help, and the real cause was never mentioned. - The PATCH sends `replace_bundle: true`. `collectBundle` walks the whole directory, so what it sends IS the bundle and a missing path is the user's own deletion — which is the case the flag exists for. - The update path's 409s are told apart by the server's detail: a name collision stays `SkillNameConflictError`, a lost compare-and-swap (the skill was edited in the workspace mid-upload) is the new `SkillChangedElsewhereError` — "publish again", not "rename" — and anything unrecognised keeps the server's own words rather than being relabelled. - `collectBundle` skips what a working directory accumulates: `.env` and `.env.*`, `.DS_Store`, editor backups and swap files, and never walks `.git`, `node_modules` or `__pycache__`. A public skill's bundle is readable tenant-wide and a secret that reaches it cannot be recalled by deleting the local file. - The file-count ceiling is checked before the read, so file 201 is no longer read and decoded before being rejected. Verified: 505 pass across the workspace + plugin suites, typecheck clean. Mutation-checked: dropping `replace_bundle`, collapsing the 409s, and skipping either junk guard each fail a test. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012Q51zFUmPg1WwtS5CrGJE6
1 parent d412091 commit e807448

2 files changed

Lines changed: 120 additions & 9 deletions

File tree

‎packages/opencode/src/altimate/workspace/skill-publish.ts‎

Lines changed: 67 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,28 @@ const MANAGED_DIR = path.join(".altimate-code", "skill", "_workspace")
5454
* usable message, instead of after a long upload. */
5555
const MAX_BUNDLE_BYTES = 10 * 1024 * 1024
5656
const MAX_BUNDLE_FILES = 200
57+
58+
/** Never published, whatever is in the directory.
59+
*
60+
* A skill directory is a folder the user works in, so it accumulates things
61+
* that are not the skill: an editor's swap file, macOS's `.DS_Store`, a `.git`
62+
* from a skill installed by clone — and `.env`, which is the one that matters.
63+
* Publishing is a share: a public skill's bundle is readable tenant-wide, and
64+
* a secret that reaches it cannot be recalled by deleting the file locally.
65+
* Skipped silently, where a named refusal would be noise about files the user
66+
* did not mean to publish either. */
67+
const NEVER_PUBLISH_DIRS = new Set([".git", "node_modules", "__pycache__"])
68+
function isJunkFile(name: string): boolean {
69+
return (
70+
name === ".DS_Store" ||
71+
name === "Thumbs.db" ||
72+
name === ".env" ||
73+
name.startsWith(".env.") ||
74+
name.endsWith("~") ||
75+
name.endsWith(".swp") ||
76+
name.endsWith(".swo")
77+
)
78+
}
5779
/** The shared request budget is 15s and covers the upload itself; a legal 10MB
5880
* bundle needs ~5.5 Mbps sustained just to fit inside it. Uploads get their
5981
* own. */
@@ -146,6 +168,21 @@ export class AttachFailedError extends Error {
146168
}
147169
}
148170

171+
/** The skill changed in the workspace between this publish reading it and
172+
* writing it — someone edited it in the web UI mid-upload. The server's
173+
* compare-and-swap refused, nothing was written, and publishing again picks up
174+
* their version. A distinct type because the advice is "try again", where a
175+
* name conflict's is "rename". */
176+
export class SkillChangedElsewhereError extends Error {
177+
constructor(readonly skillName: string) {
178+
super(
179+
`"${skillName}" was edited in the workspace while this publish was uploading, ` +
180+
`so nothing was changed. Publish again to apply your version on top of theirs.`,
181+
)
182+
this.name = "SkillChangedElsewhereError"
183+
}
184+
}
185+
149186
export class SkillNameConflictError extends Error {
150187
constructor(readonly skillName: string) {
151188
super(
@@ -186,9 +223,11 @@ export async function collectBundle(dir: string): Promise<BundleFile[]> {
186223
const full = path.join(current, entry.name)
187224
const relative = path.relative(root, full).split(path.sep).join("/")
188225
if (entry.isDirectory()) {
226+
if (NEVER_PUBLISH_DIRS.has(entry.name)) continue
189227
await walk(full)
190228
continue
191229
}
230+
if (isJunkFile(entry.name)) continue
192231
// Named, not skipped. `readdir` reports a link as neither file nor
193232
// directory, and a bare `continue` here dropped it from the bundle with
194233
// nothing said.
@@ -201,6 +240,10 @@ export async function collectBundle(dir: string): Promise<BundleFile[]> {
201240
// stat is kept as the cheap refusal; the read itself goes through a
202241
// handle in chunks and stops the moment the budget is exceeded, so
203242
// what is held in memory never passes the limit by more than a chunk.
243+
// Before the read, like the byte ceiling: file 201 was read and decoded
244+
// in full before being rejected.
245+
if (files.length >= MAX_BUNDLE_FILES)
246+
throw new BundleTooLargeError(`This skill has more than ${MAX_BUNDLE_FILES} files.`)
204247
const allowed = MAX_BUNDLE_BYTES - bytes
205248
const handle = await fs.open(full, "r")
206249
let raw: Buffer
@@ -229,8 +272,6 @@ export async function collectBundle(dir: string): Promise<BundleFile[]> {
229272
}
230273
bytes += raw.byteLength
231274
files.push({ path: relative, content })
232-
if (files.length > MAX_BUNDLE_FILES)
233-
throw new BundleTooLargeError(`This skill has more than ${MAX_BUNDLE_FILES} files.`)
234275
}
235276
}
236277

@@ -500,7 +541,14 @@ async function publishSkillUnlocked(input: {
500541
try {
501542
await altimateRequest<unknown>("PATCH", `/${encodeURIComponent(existing)}`, {
502543
base: SKILLS_BASE,
503-
body: { name: input.name, description: input.description, files },
544+
// `replace_bundle` because `files` is the WHOLE bundle every time —
545+
// `collectBundle` walks the directory, so a path missing from it is a
546+
// file the user deleted. Without the flag the server refuses any
547+
// publish that drops a path (409, by design: a partial `files` array
548+
// from a REST-conventional client used to delete the rest silently).
549+
// For this client the deletion IS the intent, and saying so is what
550+
// makes "delete a file, publish again" work at all.
551+
body: { name: input.name, description: input.description, files, replace_bundle: true },
504552
allowEmptyBody: true,
505553
timeoutMs: UPLOAD_TIMEOUT_MS,
506554
})
@@ -524,11 +572,11 @@ async function publishSkillUnlocked(input: {
524572
// The skill was deleted in the workspace since we published it. Falling
525573
// through to create is the useful answer; failing would strand the user
526574
// with a local id they cannot see or clear.
527-
// A PATCH that renames onto a name this creator already uses answers 409.
528-
// Without this the raw server envelope reaches the caller — the exact
529-
// thing the typed errors in this module exist to prevent — and only on
530-
// the update path, so the create path looked correct in isolation.
531-
if (err instanceof ConflictError) throw new SkillNameConflictError(input.name)
575+
// The update path answers 409 for three different things, and calling
576+
// all of them a name conflict told the user to rename a skill whose name
577+
// was never the problem — with no way forward, since renaming does not
578+
// help. Told apart by the server's own message.
579+
if (err instanceof ConflictError) throw updateConflict(err, input.name)
532580
// 403: the id is someone else's. Reachable through the legacy ledger
533581
// keys, which predate creator scoping — on a shared machine a row
534582
// written by another user of the same tenant is found and the server
@@ -574,6 +622,17 @@ async function publishSkillUnlocked(input: {
574622
return { action: "created", publicId, name: input.name, files: files.length, bytes, datamateId: binding.datamateId }
575623
}
576624

625+
/** Which of the update path's conflicts this is. The server distinguishes them
626+
* in its detail; this module's typed errors then carry advice that fits.
627+
* Anything unrecognised keeps the server's own words rather than being
628+
* relabelled — a wrong explanation is worse than a bare one. */
629+
function updateConflict(err: ConflictError, skillName: string): Error {
630+
const detail = err.detail.message ?? ""
631+
if (/already have a skill named/i.test(detail)) return new SkillNameConflictError(skillName)
632+
if (/changed while you were editing/i.test(detail)) return new SkillChangedElsewhereError(skillName)
633+
return err
634+
}
635+
577636
/** Accepts the documented `{public_id}` and a `{skill: {public_id}}` envelope, so
578637
* a compat wrapper on either side does not strand the id — the same tolerance
579638
* `skill-sync` applies to the list and detail shapes. */

‎packages/opencode/test/altimate/workspace/skill-publish.test.ts‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ const { AltimateApi } = await import("../../../src/altimate/api/client")
3939
const {
4040
BinaryFileError,
4141
EmptyBundleError,
42+
SkillChangedElsewhereError,
4243
ManagedSkillError,
4344
NotLinkedError,
4445
SkillNameConflictError,
@@ -75,6 +76,10 @@ let statuses: Record<string, number> = {}
7576
/** What `GET /skills/{id}` reports as the skill's current workspaces. The attach
7677
* endpoint REPLACES the set, so tests that care about merging seed this. */
7778
let attached: number[] = []
79+
/** The `detail` an error response carries. The update path answers 409 for a
80+
* name collision, a refused bundle deletion and a lost compare-and-swap, and
81+
* the client tells them apart by this string. */
82+
let conflictDetail = "You already have a skill named 'deploy'"
7883

7984
let project = ""
8085
let skillDir = ""
@@ -83,6 +88,7 @@ beforeEach(async () => {
8388
requests = []
8489
statuses = {}
8590
attached = []
91+
conflictDetail = "You already have a skill named 'deploy'"
8692
project = mkdtempSync(path.join(SANDBOX, "proj-"))
8793
skillDir = path.join(project, "skills", "deploy")
8894
mkdirSync(skillDir, { recursive: true })
@@ -100,7 +106,7 @@ beforeEach(async () => {
100106
requests.push({ method, url, body })
101107
const status = statuses[method] ?? (method === "POST" ? 201 : 200)
102108
if (status >= 400)
103-
return new Response(JSON.stringify({ detail: "nope" }), {
109+
return new Response(JSON.stringify({ detail: conflictDetail }), {
104110
status,
105111
headers: { "content-type": "application/json" },
106112
})
@@ -253,6 +259,7 @@ describe("publishSkill", () => {
253259

254260
test("reports a name conflict as its own error, not a raw API conflict", async () => {
255261
statuses.POST = 409
262+
conflictDetail = "You already have a skill named 'deploy'"
256263

257264
const err = await publish().catch((e) => e)
258265

@@ -376,6 +383,51 @@ describe("the bundle size guard", () => {
376383
expect(isManagedSkill(proj, link)).toBe(true)
377384
})
378385

386+
test("republishing after deleting a file succeeds", async () => {
387+
// `files` replaces the bundle server-side, and a path it omits is a
388+
// deletion the server refuses unless the caller says so. Without
389+
// `replace_bundle` this 409'd forever, and the user was told to rename a
390+
// skill whose name was never the problem.
391+
writeFileSync(path.join(skillDir, "extra.md"), "notes")
392+
await publish()
393+
rmSync(path.join(skillDir, "extra.md"))
394+
requests = []
395+
396+
const report = await publish()
397+
398+
expect(report.action).toBe("updated")
399+
const patch = requests.find((r) => r.method === "PATCH")!
400+
expect(patch.body.replace_bundle).toBe(true)
401+
expect(patch.body.files.map((f: any) => f.path)).toEqual(["SKILL.md"])
402+
})
403+
404+
test("a skill edited in the workspace mid-upload says so, rather than blaming the name", async () => {
405+
// The server's compare-and-swap refuses and nothing is written. Renaming
406+
// does not help; publishing again does.
407+
await publish()
408+
statuses.PATCH = 409
409+
conflictDetail = "This skill changed while you were editing it, please reload"
410+
411+
const err = await publish().catch((e) => e)
412+
413+
expect(err).toBeInstanceOf(SkillChangedElsewhereError)
414+
expect(String(err)).toContain("Publish again")
415+
})
416+
417+
test("junk a skill directory accumulates never leaves the machine", async () => {
418+
// A public skill's bundle is readable tenant-wide, and a secret that
419+
// reaches it cannot be recalled by deleting the local file.
420+
writeFileSync(path.join(skillDir, ".env"), "ALTIMATE_API_KEY=secret")
421+
writeFileSync(path.join(skillDir, ".DS_Store"), "junk")
422+
writeFileSync(path.join(skillDir, "SKILL.md~"), "editor backup")
423+
mkdirSync(path.join(skillDir, ".git"), { recursive: true })
424+
writeFileSync(path.join(skillDir, ".git", "config"), "[core]")
425+
426+
const files = await collectBundle(skillDir)
427+
428+
expect(files.map((f) => f.path)).toEqual(["SKILL.md"])
429+
})
430+
379431
test("a rename that collides on the update path is a typed conflict", async () => {
380432
// The create path mapped 409 to SkillNameConflictError; the update path did
381433
// not, so a PATCH that renames onto an existing name surfaced the raw

0 commit comments

Comments
 (0)