skills: a new version may name its base (base_n); the console's editor saves on the version it shows

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqJYwbXKWMeNZfrFuXq
This commit is contained in:
tobayah
2026-11-19 16:41:07 +01:00
co-authored by Claude Opus 5.5
parent a67bb5fde3
commit 43a4dbd82d
7 changed files with 166 additions and 18 deletions
+2
View File
@@ -341,6 +341,8 @@ class SkillVersionIn(BaseModel):
files: SkillFiles = Field(default=None, max_length=200)
# path -> base64: the previous version's files with these replaced or added. Not with `files`.
file_updates: SkillFiles = Field(default=None, max_length=200)
# The version this one is made on (the one the person was looking at); None = the default base.
base_n: int | None = Field(default=None, ge=1)
class SkillCreateIn(SkillVersionIn):
+16 -3
View File
@@ -373,10 +373,22 @@ def _base_version(db: DbSession, actor: AppUser, skill: Skill) -> SkillVersion:
return owners
def _named_base(db: DbSession, actor: AppUser, skill: Skill, n: int) -> SkillVersion:
"""Version `n` as the base, when the caller names the one it was looking at (the console's
editor always does): an explicit choice, so Ruling 9's worry (inheriting a stranger's proposal
unseen) does not apply. It must still be a version this person may read, with the same 404."""
version = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
SkillVersion.n == n))
if version is None or not readable_version_ids(actor, skill, [version]):
raise NotFoundError("Version not found.")
return version
def new_version(db: DbSession, actor: AppUser, skill_id: uuid.UUID, fields: Mapping, *,
ip: str | None) -> dict:
"""Version `n + 1`. A field that is None is carried over from the base version (`_base_version`:
the actor's own newer one, else the current one — never a stranger's proposal; `files`
"""Version `n + 1`. A field that is None is carried over from the base version: `base_n` when
given (`_named_base`), else `_base_version` (the actor's own newer one, else the current one —
never a stranger's proposal); `files`
included — `{}` is how to remove them all). `file_updates` (path -> bytes) instead replaces or
adds just those files and carries every other one over byte for byte, so a caller that holds
one file need not hold the rest. An imported licence is the author's: it stays. On a firm skill
@@ -388,7 +400,8 @@ def new_version(db: DbSession, actor: AppUser, skill_id: uuid.UUID, fields: Mapp
raise ValidationError("Send files or file_updates, not both.")
latest = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id)
.order_by(SkillVersion.n.desc()).limit(1))
base = _base_version(db, actor, skill)
base = (_named_base(db, actor, skill, fields["base_n"]) if fields.get("base_n") is not None
else _base_version(db, actor, skill))
license = fields.get("license") or base.license
if skill.origin == SkillOrigin.imported:
license = base.license
+10
View File
@@ -127,6 +127,16 @@ def test_a_new_version_decodes_files_and_leaves_absent_fields_none(api):
assert fields["description"] is None and fields["metadata"] is None # None = carry over
def test_a_new_version_passes_base_n_and_refuses_one_below_1(api):
r = api.client.post(f"{API}/skills/{SKILL_ID}/versions", json={"base_n": 3})
assert r.status_code == 201, r.text
(_, fields), _ = api.calls["new_version"]
assert fields["base_n"] == 3
del api.calls["new_version"]
assert api.client.post(f"{API}/skills/{SKILL_ID}/versions", json={"base_n": 0}).status_code == 422
assert "new_version" not in api.calls
@pytest.mark.parametrize("files", [
{"a.txt": "not base64!"},
["a.txt"],
+17
View File
@@ -279,6 +279,9 @@ def test_the_editor_saves_with_file_updates_not_files(console, plan_editor):
assert "file_updates: { 'sprawdzanie.yaml': utf8Base64(" in save
assert not re.search(r"\bfiles:", save)
assert "JSON.stringify({ wersja_formatu: 1, kroki: " in save
# Ruling 15: the new version is made on the version the draft was loaded from, not on the
# server's default base, which may be a newer proposal the draft never saw.
assert "base_n: state._planBase.n, file_updates:" in save
# The bytes are UTF-8 (TextEncoder), base64'd in slices: fromCharCode(...all) overflows the stack.
enc_fn = _section(console, "function utf8Base64(", "\n}\n")
assert "new TextEncoder().encode(" in enc_fn
@@ -293,6 +296,20 @@ def test_the_draft_is_kept_until_saved_or_left_on_purpose(console, plan_editor):
assert "beforeunload" in console
def test_the_draft_is_keyed_to_the_version_it_was_loaded_from(console, plan_editor):
"""A draft belongs to one version (`state._planBase`), set where it is loaded and where a new
procedure is started, and a re-render never shows it under another version."""
load = _section(console, "async function loadPlan(", "\n}\n")
assert "state._planBase = { id: shown.id, n: shown.n };" in load
start = _section(console, "function startPlan(", "\n}\n")
assert "state._planBase = { id: shown.id, n: shown.n };" in start
view = _section(console, "async function viewSkill(", "\n}\n")
assert "state._planBase.id !== shown.id" in view
# "Nowa wersja" asks before it could leave a dirty draft behind.
editor = _section(console, "function openSkillEditor(", "\n}\n")
assert "if (id && state._planDirty) { askLeavingDraft(() => openSkillEditor(id)); return; }" in editor
def test_plan_values_are_escaped(screen, plan_editor):
"""`test_dynamic_values_are_escaped` reads the whole screen, the editor's lines included."""
assert plan_editor in screen
+38
View File
@@ -134,6 +134,44 @@ def test_other_user_proposes_on_a_firm_skill(admin_client, client, owner, other,
_approve(admin_client, sid)
def skill_v1(client, owner, sid) -> dict:
return client.get(f"{SKILLS}/{sid}/versions/1", headers=bearer(owner["token"])).json()
def test_base_n_builds_on_the_version_shown(admin_client, client, owner, other):
"""Ruling 15: a save names the version it was made on. A proposer looking at the firm's current
version builds on it, not on their own newer proposal; a version they cannot read is a 404."""
with settings_set(admin_client, skills_firm_publish="approval"):
skill = _create(client, bearer(owner["token"]), body="# Approved\n")
sid = skill["id"]
assert client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"])).status_code == 200
_approve(admin_client, sid)
me = bearer(other["token"])
mine = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Mine\n"}, headers=me)
assert mine.status_code == 201 and mine.json()["n"] == 2, mine.text
# Without base_n the default stays (Ruling 9): the proposer's own newest version.
default = client.post(f"{SKILLS}/{sid}/versions", json={"description": "Next."}, headers=me)
assert default.status_code == 201 and default.json()["body"] == "# Mine\n", default.text
shown = client.post(f"{SKILLS}/{sid}/versions", headers=me,
json={"base_n": 1, "file_updates": {"sprawdzanie.yaml": "eA=="}})
assert shown.status_code == 201, shown.text
assert shown.json()["n"] == 4 and shown.json()["body"] == "# Approved\n"
assert shown.json()["description"] == skill_v1(client, owner, sid)["description"]
assert [f["path"] for f in shown.json()["files"]] == ["sprawdzanie.yaml"]
owners = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Owner draft\n"},
headers=bearer(owner["token"]))
assert owners.status_code == 201, owners.text
before = len(client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()["versions"])
for n in (owners.json()["n"], 99):
r = client.post(f"{SKILLS}/{sid}/versions", json={"base_n": n, "body": "# x\n"}, headers=me)
assert r.status_code == 404, (n, r.text)
after = len(client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()["versions"])
assert after == before
def test_a_missing_skill_is_404(client, owner):
assert client.get(f"{SKILLS}/{uuid.uuid4()}", headers=bearer(owner["token"])).status_code == 404
+40
View File
@@ -206,6 +206,46 @@ def test_a_proposers_save_after_a_newer_approval_builds_on_the_approved_one(audi
assert _sha(out) == {"notatka.md": _h(b"approved")}
def test_base_n_builds_on_the_version_shown_even_over_a_newer_own_proposal(audited):
"""Ruling 15: the editor saves on top of the version the person was looking at. Without
`base_n` this save would take the proposer's own v2 as its base and silently revert it."""
approved, mine = _ver(OWNER, 1), _ver(OTHER, 2)
skill = _skill("firm", current=approved.id)
db = _VersionDb(skill, [approved, mine], {
approved.id: [_stored("notatka.md", b"approved")],
mine.id: [_stored("notatka.md", b"mine")]})
out = skills.new_version(db, OTHER, skill.id,
{"base_n": 1, "file_updates": {"sprawdzanie.yaml": b"y"}}, ip=None)
assert out["n"] == 3
assert _sha(out) == {"notatka.md": _h(b"approved"), "sprawdzanie.yaml": _h(b"y")}
@pytest.mark.parametrize("base_n", [2, 9])
def test_base_n_on_a_version_the_actor_cannot_read_is_a_404_and_adds_nothing(base_n):
"""v2 is the owner's unpublished version of a firm skill: a proposer may not read it, so they
may not build on it either (9: no such version). Same 404 as reading it."""
approved, owners_draft = _ver(OWNER, 1), _ver(OWNER, 2)
skill = _skill("firm", current=approved.id)
db = _VersionDb(skill, [approved, owners_draft])
with pytest.raises(NotFoundError) as err:
skills.new_version(db, OTHER, skill.id, {"base_n": base_n, "file_updates": {"a.md": b"x"}},
ip=None)
assert str(err.value) == "Version not found."
assert db.added == []
def test_an_absent_base_n_keeps_the_default_base(audited):
"""`base_n: None` is what the router passes when the field is left out: Ruling 9 applies."""
approved, first = _ver(OWNER, 1), _ver(OTHER, 2)
skill = _skill("firm", current=approved.id)
db = _VersionDb(skill, [approved, first], {
approved.id: [_stored("notatka.md", b"approved")],
first.id: [_stored("notatka.md", b"mine")]})
out = skills.new_version(db, OTHER, skill.id, {"base_n": None, "file_updates": {"b.md": b"b"}},
ip=None)
assert _sha(out) == {"notatka.md": _h(b"mine"), "b.md": _h(b"b")}
def test_files_and_file_updates_together_are_refused():
v1 = _ver(OWNER, 1)
skill = _skill("firm", current=v1.id)
+43 -15
View File
@@ -4914,11 +4914,19 @@ async function viewSkill(C, id) {
setCrumb([{ label: 'Skille i agenci', href: '#/skills' }, { label: s.name, data: true }]);
// `?v=N` opens one version (the editor saves and lands on its new one); else the current one.
const want = parseHash().q.v;
const shown = (want && vs.find((v) => String(v.n) === want)) || s.current || vs[0];
let shown = (want && vs.find((v) => String(v.n) === want)) || s.current || vs[0];
const active = s.status !== 'archived';
// A draft and the open tab belong to one view; arriving at another one starts clean (router()
// has already asked before a dirty draft could be left).
if (state._planView !== location.hash) {
// A dirty draft holds the page on the version it was loaded from: a publish or a new version can
// move "current" under a link without ?v, and the draft must never sit under another version.
const held = state._planDirty && state._planBase && vs.find((v) => v.id === state._planBase.id);
if (held && state._planView === location.hash && (!shown || held.id !== shown.id)) {
shown = held;
history.replaceState(null, '', '#/skills/skill/' + enc(s.id) + '?v=' + held.n);
state._planView = location.hash;
}
// A draft and the open tab belong to one version and one view; arriving at another one starts
// clean (router(), "Nowa wersja" and the hold above have asked or kept a dirty draft before this).
if (state._planView !== location.hash || (state._planBase && shown && state._planBase.id !== shown.id)) {
const tab = state._planNextTab; // a save lands on its new version in the tab it was made in
dropPlan();
state._planView = location.hash;
@@ -4973,6 +4981,7 @@ function skillFilesNote() {
}
function openSkillEditor(id) {
if (id && state._planDirty) { askLeavingDraft(() => openSkillEditor(id)); return; }
const s = id ? state._skill : null;
const v = id ? state._skillLatest : null;
modal(id ? 'Nowa wersja' : 'Nowy skill', s ? s.name : '',
@@ -5019,8 +5028,10 @@ function archiveSkill(id) {
writes YAML: Arbiter's `skill-check/normalize` turns the file into a plan for the forms and the
plan back into the canonical text to store, so the format lives in one place. The draft is
`state._plan`, bound to one view (`state._planView`, the hash of the version shown); it is kept
in memory only, so leaving it dirty asks first (`leavingDraft`, called by router()). Saving makes
a new version with just this file replaced (`file_updates`); the others carry over server-side. */
in memory only, so leaving it dirty asks first (`leavingDraft`, called by router()). It is also
keyed to the version it was loaded from (`state._planBase`), and a save names that version as
`base_n`: the new version is that one with just this file replaced (`file_updates`), never the
server's default base, which may be a newer proposal the draft never saw (Ruling 15). */
const PLAN_FILE = 'sprawdzanie.yaml';
const SEVERITY = { blokujaca: 'blokująca', istotna: 'istotna', informacyjna: 'informacyjna' };
const SEVERITY_CHIP = { blokujaca: 'err', istotna: 'warn', informacyjna: '' };
@@ -5036,7 +5047,8 @@ const planOpt = (v, label, cur) => `<option value="${esc(v)}"${v === cur ? ' sel
function dropPlan() {
Object.assign(state, { _plan: null, _planDirty: false, _planErr: null, _planSaveErr: null,
_planLoading: false, _planView: null, _skillTab: 'opis', _leaveTo: null, _planNextTab: null });
_planLoading: false, _planView: null, _skillTab: 'opis', _leaveTo: null, _leaveThen: null,
_planNextTab: null, _planBase: null });
}
// A reload or a closed tab would lose the draft too: the browser asks its own question.
@@ -5051,17 +5063,27 @@ function leavingDraft() {
if (!state._planDirty) { dropPlan(); return false; }
state._leaveTo = location.hash;
history.replaceState(null, '', state._planView);
modal('Niezapisane zmiany', '', '<div>Masz niezapisane zmiany w procedurze sprawdzania.</div>',
`<button class="btn" onclick="closeModal()">Zostań</button>
<button class="btn danger" onclick="leaveDraft()">Wyjdź bez zapisywania</button>`);
askLeavingDraft(null);
return true;
}
/* `then` is what to do after "Wyjdź bez zapisywania" when the person stays on this page (a new
version); without it the page goes to `state._leaveTo`. */
function askLeavingDraft(then) {
state._leaveThen = then;
modal('Niezapisane zmiany', '', '<div>Masz niezapisane zmiany w procedurze sprawdzania.</div>',
`<button class="btn" onclick="closeModal()">Zostań</button>
<button class="btn danger" onclick="leaveDraft()">Wyjdź bez zapisywania</button>`);
}
function leaveDraft() {
const to = state._leaveTo;
const { _leaveTo: to, _leaveThen: then, _planView: view } = state;
dropPlan();
closeModal();
location.hash = to;
if (!then) { location.hash = to; return; }
state._planView = view;
renderSkillBody();
then();
}
async function clauseTypes() {
@@ -5088,8 +5110,12 @@ async function loadPlan() {
if (state._planView !== view) return; // the person moved on meanwhile
state._planLoading = false;
if (err && err.status === 401 && text === undefined) { showLogin(); return; }
if (err) state._planErr = err;
else state._plan = reply.plan;
if (err) {
state._planErr = err;
} else {
state._plan = reply.plan;
state._planBase = { id: shown.id, n: shown.n };
}
renderSkillBody();
}
@@ -5202,6 +5228,8 @@ function planSlug(text, taken, fallback) {
}
function startPlan(btn) {
const { shown } = state._skillView;
state._planBase = { id: shown.id, n: shown.n };
state._plan = { wersja_formatu: 1, kroki: [{ id: '', nazwa: '', standardy: [] }] };
state._skillTab = 'mapa';
btn.remove();
@@ -5352,7 +5380,7 @@ function savePlan() {
return;
}
const current = s.versions.find((v) => v.id === s.current_version_id);
await mutate('POST', '/skills/' + enc(s.id) + '/versions', { file_updates: { 'sprawdzanie.yaml': utf8Base64(reply.yaml) } }, {
await mutate('POST', '/skills/' + enc(s.id) + '/versions', { base_n: state._planBase.n, file_updates: { 'sprawdzanie.yaml': utf8Base64(reply.yaml) } }, {
// A firm skill's new version is a proposal: the firm keeps checking with the current one.
done: (v) => (s.scope === 'firm' && current
? _tr(FIRM_PROPOSAL).replace('{n}', v.n).replace('{m}', current.n) : 'Zapisano nową wersję.'),