Skip to content

Commit b8b6a24

Browse files
committed
Merge branch 'feat/workspace-skill-publish' into feat/workspace-skill-publish-command
# Conflicts: # packages/opencode/src/altimate/workspace/skill-publish.ts
2 parents 30ba5c3 + e807448 commit b8b6a24

2 files changed

Lines changed: 121 additions & 9 deletions

File tree

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

Lines changed: 68 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
@@ -594,12 +642,24 @@ export function explainPublishError(err: unknown): string | null {
594642
err instanceof EmptyBundleError ||
595643
err instanceof BundleTooLargeError ||
596644
err instanceof SkillNameConflictError ||
645+
err instanceof SkillChangedElsewhereError ||
597646
err instanceof AttachFailedError
598647
)
599648
return err.message
600649
return null
601650
}
602651

652+
/** Which of the update path's conflicts this is. The server distinguishes them
653+
* in its detail; this module's typed errors then carry advice that fits.
654+
* Anything unrecognised keeps the server's own words rather than being
655+
* relabelled — a wrong explanation is worse than a bare one. */
656+
function updateConflict(err: ConflictError, skillName: string): Error {
657+
const detail = err.detail.message ?? ""
658+
if (/already have a skill named/i.test(detail)) return new SkillNameConflictError(skillName)
659+
if (/changed while you were editing/i.test(detail)) return new SkillChangedElsewhereError(skillName)
660+
return err
661+
}
662+
603663
/** Accepts the documented `{public_id}` and a `{skill: {public_id}}` envelope, so
604664
* a compat wrapper on either side does not strand the id — the same tolerance
605665
* `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,
@@ -77,6 +78,10 @@ let statuses: Record<string, number> = {}
7778
/** What `GET /skills/{id}` reports as the skill's current workspaces. The attach
7879
* endpoint REPLACES the set, so tests that care about merging seed this. */
7980
let attached: number[] = []
81+
/** The `detail` an error response carries. The update path answers 409 for a
82+
* name collision, a refused bundle deletion and a lost compare-and-swap, and
83+
* the client tells them apart by this string. */
84+
let conflictDetail = "You already have a skill named 'deploy'"
8085

8186
let project = ""
8287
let skillDir = ""
@@ -85,6 +90,7 @@ beforeEach(async () => {
8590
requests = []
8691
statuses = {}
8792
attached = []
93+
conflictDetail = "You already have a skill named 'deploy'"
8894
project = mkdtempSync(path.join(SANDBOX, "proj-"))
8995
skillDir = path.join(project, "skills", "deploy")
9096
mkdirSync(skillDir, { recursive: true })
@@ -102,7 +108,7 @@ beforeEach(async () => {
102108
requests.push({ method, url, body })
103109
const status = statuses[method] ?? (method === "POST" ? 201 : 200)
104110
if (status >= 400)
105-
return new Response(JSON.stringify({ detail: "nope" }), {
111+
return new Response(JSON.stringify({ detail: conflictDetail }), {
106112
status,
107113
headers: { "content-type": "application/json" },
108114
})
@@ -255,6 +261,7 @@ describe("publishSkill", () => {
255261

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

259266
const err = await publish().catch((e) => e)
260267

@@ -378,6 +385,51 @@ describe("the bundle size guard", () => {
378385
expect(isManagedSkill(proj, link)).toBe(true)
379386
})
380387

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

0 commit comments

Comments
 (0)