formist-cli 0.1.0__tar.gz → 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. {formist_cli-0.1.0 → formist_cli-0.1.1}/PKG-INFO +1 -1
  2. {formist_cli-0.1.0 → formist_cli-0.1.1}/pyproject.toml +1 -1
  3. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/context.py +8 -1
  4. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/skills.py +68 -12
  5. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/uploads.py +59 -0
  6. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_context.py +63 -0
  7. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_skills.py +119 -0
  8. {formist_cli-0.1.0 → formist_cli-0.1.1}/uv.lock +1 -1
  9. {formist_cli-0.1.0 → formist_cli-0.1.1}/.github/workflows/release.yml +0 -0
  10. {formist_cli-0.1.0 → formist_cli-0.1.1}/.github/workflows/test.yml +0 -0
  11. {formist_cli-0.1.0 → formist_cli-0.1.1}/.gitignore +0 -0
  12. {formist_cli-0.1.0 → formist_cli-0.1.1}/LICENSE +0 -0
  13. {formist_cli-0.1.0 → formist_cli-0.1.1}/README.ar.md +0 -0
  14. {formist_cli-0.1.0 → formist_cli-0.1.1}/README.fr.md +0 -0
  15. {formist_cli-0.1.0 → formist_cli-0.1.1}/README.md +0 -0
  16. {formist_cli-0.1.0 → formist_cli-0.1.1}/README.zh-CN.md +0 -0
  17. {formist_cli-0.1.0 → formist_cli-0.1.1}/docs/screenshot.png +0 -0
  18. {formist_cli-0.1.0 → formist_cli-0.1.1}/docs/screenshot.svg +0 -0
  19. {formist_cli-0.1.0 → formist_cli-0.1.1}/scripts/render_screenshot.py +0 -0
  20. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/__init__.py +0 -0
  21. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/__main__.py +0 -0
  22. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/airtable.py +0 -0
  23. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/alerts.py +0 -0
  24. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/api.py +0 -0
  25. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/chat.py +0 -0
  26. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/chats.py +0 -0
  27. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/cli.py +0 -0
  28. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/cli_support.py +0 -0
  29. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/connectors.py +0 -0
  30. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/diff.py +0 -0
  31. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/doctor.py +0 -0
  32. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/export.py +0 -0
  33. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/files.py +0 -0
  34. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/importer.py +0 -0
  35. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/kb.py +0 -0
  36. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/login.py +0 -0
  37. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/logs.py +0 -0
  38. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/meetings.py +0 -0
  39. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/messages.py +0 -0
  40. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/participants.py +0 -0
  41. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/prefs.py +0 -0
  42. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/privileges.py +0 -0
  43. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/projects.py +0 -0
  44. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/resolve.py +0 -0
  45. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/settings.py +0 -0
  46. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/skill_library.py +0 -0
  47. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/space_plan.py +0 -0
  48. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/spaces.py +0 -0
  49. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/targets.py +0 -0
  50. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/textnorm.py +0 -0
  51. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/tokens.py +0 -0
  52. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/update.py +0 -0
  53. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/usage_tokens.py +0 -0
  54. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/users.py +0 -0
  55. {formist_cli-0.1.0 → formist_cli-0.1.1}/src/formist_cli/whatsapp.py +0 -0
  56. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_admin_flag_gate.py +0 -0
  57. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_airtable.py +0 -0
  58. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_alerts.py +0 -0
  59. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_api_and_tokens.py +0 -0
  60. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_api_uploads_transport.py +0 -0
  61. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_audit_log_shows_the_newest.py +0 -0
  62. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_chat.py +0 -0
  63. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_chat_message.py +0 -0
  64. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_chats.py +0 -0
  65. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_cli_registration_is_unique.py +0 -0
  66. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_connector_ops.py +0 -0
  67. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_connectors.py +0 -0
  68. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_diff.py +0 -0
  69. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_doctor.py +0 -0
  70. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_export.py +0 -0
  71. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_files.py +0 -0
  72. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_files_download.py +0 -0
  73. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_files_merge.py +0 -0
  74. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_grants_render.py +0 -0
  75. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_help_matches_the_write_guard.py +0 -0
  76. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_importer.py +0 -0
  77. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_kb.py +0 -0
  78. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_login.py +0 -0
  79. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_logs.py +0 -0
  80. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_meetings.py +0 -0
  81. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_messages.py +0 -0
  82. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_participants.py +0 -0
  83. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_prefs.py +0 -0
  84. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_privileges.py +0 -0
  85. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_projects.py +0 -0
  86. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_proposals.py +0 -0
  87. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_render_screenshot.py +0 -0
  88. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_report_provenance.py +0 -0
  89. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_resolve.py +0 -0
  90. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_settings.py +0 -0
  91. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_skill_library_install.py +0 -0
  92. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_space_plan.py +0 -0
  93. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_spaces.py +0 -0
  94. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_stream_transport.py +0 -0
  95. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_targets.py +0 -0
  96. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_update.py +0 -0
  97. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_upload_dir.py +0 -0
  98. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_uploads.py +0 -0
  99. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_usage_tokens.py +0 -0
  100. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_users.py +0 -0
  101. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_users_writes.py +0 -0
  102. {formist_cli-0.1.0 → formist_cli-0.1.1}/tests/test_whatsapp.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: formist-cli
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Command-line client for Formist and Evane deployments
5
5
  Project-URL: Homepage, https://formist.ai
6
6
  Project-URL: Repository, https://github.com/WeCarbon/formist-cli
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "formist-cli"
7
- version = "0.1.0"
7
+ version = "0.1.1"
8
8
  description = "Command-line client for Formist and Evane deployments"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -80,7 +80,14 @@ def resolve(
80
80
  file=sys.stderr,
81
81
  )
82
82
  else:
83
- token = _refresh_if_stale(eff.target.name, token)
83
+ # Refresh against ORIGIN, not ``eff.target.name``: when borrowing
84
+ # (origin != eff.target.name), the refresh token and its metadata
85
+ # live in origin's file, not in a file for eff.target.name, which
86
+ # may not even exist on disk. Refreshing against the wrong file
87
+ # reads an empty `load_meta`, finds no `expires_at`, and silently
88
+ # returns the stale token unchanged, which is exactly the bug a
89
+ # borrowed, expired token used to hit (401, never refreshed).
90
+ token = _refresh_if_stale(origin or eff.target.name, token)
84
91
  if origin and origin != eff.target.name:
85
92
  # Borrowing a credential from another region's file is said
86
93
  # out loud rather than left as invisible state.
@@ -14,10 +14,13 @@ stdlib only).
14
14
  existing one (resolved by id or exact name, the same resolver ``fm get SKILL``
15
15
  uses) and never creates a second. Deliberately no bulk "seed every space" verb.
16
16
 
17
- Attachments (any file in SOURCE besides ``SKILL.md``) are registered the same
18
- way ``fm skill-attach`` already does: this module calls that mechanism
19
- directly (``formist_cli.uploads.upload_file`` + ``attach_file_to_skill``) rather
20
- than re-implementing it.
17
+ Attachments (any file in SOURCE besides ``SKILL.md``) are registered through
18
+ the same primitives ``fm skill-attach`` already uses
19
+ (``formist_cli.uploads.upload_file`` / ``attach_file_to_skill`` /
20
+ ``find_existing_attachment``) rather than a second copy of them, PLUS a
21
+ name-then-content dedupe (see ``_attach_all``) that is the whole reason
22
+ ``skills-update`` can be re-run on the same SOURCE without its attachment
23
+ count growing by one every time.
21
24
 
22
25
  Dry run by default, same contract as every other write command here
23
26
  (``fm upload``, ``fm skill-attach``); ``--apply`` performs the write.
@@ -103,20 +106,51 @@ def _attach_all(
103
106
  token: str | None,
104
107
  upload_file=None,
105
108
  attach_file_to_skill=None,
109
+ find_existing_attachment=None,
110
+ download_file_bytes=None,
111
+ replace_file_in_skill=None,
106
112
  ) -> dict:
107
113
  """Upload + register every attachment on the just-created/updated skill,
108
114
  reusing ``fm skill-attach``'s own functions rather than a second copy.
109
115
 
110
- ``upload_file``/``attach_file_to_skill`` are injectable (default: the real
111
- ``formist_cli.uploads`` functions), the same dependency-injection shape those
112
- two functions themselves already accept, so a test can pass a fake
113
- transport all the way through without patching module globals.
116
+ DEDUPES BY NAME, the same match rule ``fm skill-attach`` uses
117
+ (:func:`formist_cli.uploads.find_existing_attachment`): a same-named
118
+ attachment already on ``item`` is never re-attached under a second
119
+ entry. A no-op for ``fm skills-add`` (a brand-new skill starts with no
120
+ attachments, so nothing here ever matches); it is what stops ``fm
121
+ skills-update`` re-attaching its template file on every run.
122
+
123
+ A name match is then settled by CONTENT, not just the name: identical
124
+ bytes (sha256, after an equal-size fast path) are left alone; changed
125
+ bytes are uploaded and swapped into the SAME slot
126
+ (:func:`formist_cli.uploads.replace_file_in_skill`), never appended
127
+ as a second attachment under the name a human already recognises.
128
+
129
+ Every injectable here defaults to the real ``formist_cli.uploads``
130
+ function, the same dependency-injection shape those functions
131
+ themselves already accept, so a test can pass a fake transport all the
132
+ way through without patching module globals.
114
133
  """
115
134
  from formist_cli import uploads as uploads_mod
116
135
 
117
136
  upload_file = upload_file or uploads_mod.upload_file
118
137
  attach_file_to_skill = attach_file_to_skill or uploads_mod.attach_file_to_skill
138
+ find_existing_attachment = find_existing_attachment or uploads_mod.find_existing_attachment
139
+ download_file_bytes = download_file_bytes or uploads_mod.download_file_bytes
140
+ replace_file_in_skill = replace_file_in_skill or uploads_mod.replace_file_in_skill
141
+
119
142
  for att in attachments:
143
+ existing = find_existing_attachment(target, space, item, att.name, token=token)
144
+ if existing is not None:
145
+ local_bytes = att.read_bytes()
146
+ if existing.get("size") == len(local_bytes):
147
+ remote_bytes = download_file_bytes(target, space, existing["id"], token=token)
148
+ if uploads_mod.sha256_hex(remote_bytes) == uploads_mod.sha256_hex(local_bytes):
149
+ continue # identical content already attached: nothing to do
150
+ uploaded = upload_file(target, space, att, token=token)
151
+ file_id = uploaded["item"]["id"]
152
+ item = replace_file_in_skill(target, space, item, existing["id"], file_id, token=token)
153
+ continue
120
154
  uploaded = upload_file(target, space, att, token=token)
121
155
  file_id = uploaded["item"]["id"]
122
156
  item = attach_file_to_skill(target, space, item, file_id, token=token)
@@ -132,6 +166,9 @@ def add_skill_from_source(
132
166
  post=None,
133
167
  upload_file=None,
134
168
  attach_file_to_skill=None,
169
+ find_existing_attachment=None,
170
+ download_file_bytes=None,
171
+ replace_file_in_skill=None,
135
172
  ) -> dict:
136
173
  """The testable core of ``fm skills-add``: read SOURCE, POST it, attach
137
174
  whatever else SOURCE held. ``post`` is injectable (default:
@@ -151,6 +188,9 @@ def add_skill_from_source(
151
188
  token=token,
152
189
  upload_file=upload_file,
153
190
  attach_file_to_skill=attach_file_to_skill,
191
+ find_existing_attachment=find_existing_attachment,
192
+ download_file_bytes=download_file_bytes,
193
+ replace_file_in_skill=replace_file_in_skill,
154
194
  )
155
195
  finally:
156
196
  if tmp is not None:
@@ -167,12 +207,21 @@ def update_skill_from_source(
167
207
  patch=None,
168
208
  upload_file=None,
169
209
  attach_file_to_skill=None,
210
+ find_existing_attachment=None,
211
+ download_file_bytes=None,
212
+ replace_file_in_skill=None,
170
213
  ) -> dict:
171
214
  """The testable core of ``fm skills-update``: read SOURCE, PATCH the
172
215
  already-resolved ``skill`` dict (see ``formist_cli.uploads.resolve_skill``),
173
216
  attach whatever else SOURCE held. Never resolves ``skill`` itself: same
174
217
  split ``formist_cli.uploads.attach_file_to_skill`` uses, so a caller controls
175
- exactly when the resolve-by-name network round trip happens."""
218
+ exactly when the resolve-by-name network round trip happens.
219
+
220
+ Attachments are DEDUPED BY NAME then settled by content (see
221
+ :func:`_attach_all`): a re-run with an unchanged template file leaves
222
+ ``skill["files"]`` exactly as it was, rather than growing by one every
223
+ time.
224
+ """
176
225
  patch = patch or api.patch
177
226
  markdown, attachments, tmp = resolve_source(source)
178
227
  try:
@@ -190,6 +239,9 @@ def update_skill_from_source(
190
239
  item,
191
240
  attachments,
192
241
  token=token,
242
+ find_existing_attachment=find_existing_attachment,
243
+ download_file_bytes=download_file_bytes,
244
+ replace_file_in_skill=replace_file_in_skill,
193
245
  upload_file=upload_file,
194
246
  attach_file_to_skill=attach_file_to_skill,
195
247
  )
@@ -232,9 +284,13 @@ def add_parser(sub) -> None:
232
284
  "in place (PATCH .../skills/{id}/import), never creates a second "
233
285
  "row. --skill is a skill id (UUID) or its exact name (resolved the "
234
286
  "same way `fm get SKILL --name ...` does; refuses on more than one "
235
- "match). Attachments under SOURCE are uploaded and registered "
236
- "additively (existing ones are never removed), same as "
237
- "`fm skill-attach`.\n\n"
287
+ "match). Attachments under SOURCE are DEDUPED BY NAME, the same "
288
+ "match rule `fm skill-attach` uses: a same-named attachment that "
289
+ "already holds this exact content is left alone (a re-run is a "
290
+ "no-op), one whose content changed is uploaded and swapped into "
291
+ "the same slot, and a name with no existing match is uploaded "
292
+ "and added. Existing attachments under OTHER names are never "
293
+ "removed.\n\n"
238
294
  "SOURCE is a local directory holding SKILL.md, or a .zip of one.\n\n"
239
295
  "DRY RUN by default: prints what would change and touches nothing. "
240
296
  "--apply performs the write."
@@ -28,6 +28,7 @@ Stdlib only: this module must not add a runtime dependency.
28
28
 
29
29
  from __future__ import annotations
30
30
 
31
+ import hashlib
31
32
  import mimetypes
32
33
  import re
33
34
  import sys
@@ -450,6 +451,64 @@ def attach_file_to_skill(
450
451
  return item
451
452
 
452
453
 
454
+ def download_file_bytes(
455
+ target: Target,
456
+ space: str,
457
+ file_id: str,
458
+ *,
459
+ token: str | None,
460
+ download: Caller | None = None,
461
+ ) -> bytes:
462
+ """The raw bytes of an already-uploaded File, through the same per-file
463
+ download route the product's own file preview uses (see ``fm files
464
+ download``). Used to decide whether a same-named skill attachment
465
+ already holds this exact content, never to render or save anything.
466
+ """
467
+ download = download or _api().download
468
+ data, _disposition = download(target, f"/projects/{space}/files/{file_id}/download", token=token)
469
+ return data
470
+
471
+
472
+ def sha256_hex(data: bytes) -> str:
473
+ return hashlib.sha256(data).hexdigest()
474
+
475
+
476
+ def replace_file_in_skill(
477
+ target: Target,
478
+ space: str,
479
+ skill: dict,
480
+ old_file_id: str,
481
+ new_file_id: str,
482
+ *,
483
+ token: str | None,
484
+ patch: Caller | None = None,
485
+ ) -> dict:
486
+ """Swap ``old_file_id`` for ``new_file_id`` IN PLACE within ``skill["files"]``,
487
+ preserving position and every other entry.
488
+
489
+ The sibling of :func:`attach_file_to_skill`, for when a same-named
490
+ attachment already exists and its content changed: the stale copy must
491
+ be replaced, never left in the list alongside a second, newer upload of
492
+ the same template under the same name.
493
+
494
+ If ``old_file_id`` is not actually present (stale caller state), this
495
+ appends ``new_file_id`` rather than silently dropping the just-uploaded
496
+ file; the same "this is additive, not idempotent-by-accident" shape
497
+ :func:`attach_file_to_skill` already has.
498
+ """
499
+ patch = patch or _api().patch
500
+ current = [str(f) for f in (skill.get("files") or [])]
501
+ updated = [new_file_id if f == old_file_id else f for f in current]
502
+ if old_file_id not in current:
503
+ updated.append(new_file_id)
504
+ body = {"files": updated}
505
+ result = patch(target, f"/projects/{space}/skills/{skill['id']}", body, token=token)
506
+ item = result.get("item") if isinstance(result, dict) else None
507
+ if not isinstance(item, dict):
508
+ raise UploadError(f"replacing the skill's attachment returned an unexpected shape: {result!r}")
509
+ return item
510
+
511
+
453
512
  def resolve_skill(
454
513
  name_or_id: str,
455
514
  *,
@@ -128,6 +128,69 @@ class TestItResolvesAndRefusesInOnePlace:
128
128
  context.resolve(_Args(host="ae"))
129
129
  assert "using the global token" in capsys.readouterr().err
130
130
 
131
+ def test_a_borrowed_token_is_refreshed_against_its_ORIGIN_not_the_borrowing_host(
132
+ self, monkeypatch
133
+ ):
134
+ """Regression: a borrowed, expired token was never refreshed.
135
+
136
+ ``_refresh_if_stale`` reads its metadata (``expires_at``, the
137
+ refresh token, ``client_id``) from ORIGIN's file; evane-ae has none
138
+ of its own. Refreshing against ``eff.target.name`` instead of
139
+ ``origin`` reads an empty file, finds no ``expires_at``, and
140
+ silently returns the stale token unchanged, so a borrowed, expired
141
+ token stayed 401 forever and only a direct ``--host evane`` call
142
+ ever refreshed anything.
143
+ """
144
+ monkeypatch.setattr(
145
+ prefs, "effective", lambda **k: _Eff(resolve_target("evane-ae"), "sp", "flag")
146
+ )
147
+ monkeypatch.setattr(tokens, "load_for", lambda env: ("stale-tok", "evane"))
148
+ calls: list[str] = []
149
+ monkeypatch.setattr(
150
+ context, "_refresh_if_stale",
151
+ lambda env, token: calls.append(env) or "fresh-tok",
152
+ )
153
+ ctx = context.resolve(_Args(host="ae"))
154
+ assert calls == ["evane"], f"refreshed against {calls}, not the token's real origin"
155
+ assert ctx.token == "fresh-tok"
156
+
157
+ def test_a_borrowed_expired_tokens_failed_refresh_names_the_ORIGIN_host(
158
+ self, monkeypatch, capsys, tmp_path
159
+ ):
160
+ """An expired evane-ae request borrowing evane's token, with nothing
161
+ left to refresh it, must point at `fm login --host evane` (where the
162
+ credential actually lives), never `--host evane-ae` (which has never
163
+ stored one of its own).
164
+ """
165
+ from datetime import datetime, timedelta, timezone
166
+
167
+ from formist_cli import login
168
+
169
+ monkeypatch.setenv(tokens.CONFIG_DIR_VAR, str(tmp_path / "fm-config"))
170
+ monkeypatch.delenv(tokens.ENV_TOKEN_VAR, raising=False)
171
+ # A credential for "evane" with no refresh_token at all: the "nothing
172
+ # to refresh it with" branch, not a network failure.
173
+ login.store_payload(
174
+ "evane",
175
+ {"access_token": "crst_at_old", "scope": "evane:kb", "expires_in": 3600},
176
+ client_id="cid-1",
177
+ )
178
+ path = tokens.token_path("evane")
179
+ import json as json_mod
180
+
181
+ data = json_mod.loads(path.read_text())
182
+ data["expires_at"] = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
183
+ path.write_text(json_mod.dumps(data))
184
+
185
+ monkeypatch.setattr(
186
+ prefs, "effective", lambda **k: _Eff(resolve_target("evane-ae"), "sp", "flag")
187
+ )
188
+ ctx = context.resolve(_Args(host="ae"))
189
+ err = capsys.readouterr().err
190
+ assert "fm login --host evane" in err
191
+ assert "fm login --host evane-ae" not in err
192
+ assert ctx.token == "crst_at_old" # unrefreshed, but the real stale one, not lost
193
+
131
194
  def test_the_banner_is_printed_to_STDERR_so_stdout_stays_pipeable(
132
195
  self, monkeypatch, capsys
133
196
  ):
@@ -227,6 +227,125 @@ class TestAddSkillFromSource:
227
227
  assert not seen["dir"].exists(), "the tempdir must be cleaned up after use"
228
228
 
229
229
 
230
+ class _FakeSkillStore:
231
+ """A tiny in-memory stand-in for the server's File rows + one Skill's
232
+ ``files`` list: just enough to run ``update_skill_from_source`` more
233
+ than once against the SAME skill and watch whether attachments
234
+ accumulate, which a fixed canned response (``_fake_patch``/
235
+ ``_fake_attachment_pair``) cannot do across calls.
236
+ """
237
+
238
+ def __init__(self, skill: dict):
239
+ self.skill = dict(skill)
240
+ self.files: dict[str, dict] = {} # file_id -> {"name": ..., "data": ...}
241
+
242
+ def patch_import(self, target, path, body, *, token=None, **kw):
243
+ """Simulates PATCH .../skills/{id}/import: changes markdown-derived
244
+ fields, leaves ``files`` exactly as the skill currently holds it."""
245
+ return {**self.skill, "name": "Probe Skill"}
246
+
247
+ def upload_file(self, target, space, path, *, token=None, **kw):
248
+ data = Path(path).read_bytes()
249
+ file_id = str(uuid4())
250
+ self.files[file_id] = {"name": path.name, "data": data}
251
+ return {"item": {"id": file_id, "name": path.name, "size": len(data)}}
252
+
253
+ def attach_file_to_skill(self, target, space, item, file_id, *, token=None, **kw):
254
+ current = list(item.get("files") or [])
255
+ if file_id not in current:
256
+ current.append(file_id)
257
+ item = {**item, "files": current}
258
+ self.skill = item
259
+ return item
260
+
261
+ def find_existing_attachment(self, target, space, item, filename, *, token=None, **kw):
262
+ for fid in item.get("files") or []:
263
+ f = self.files.get(fid)
264
+ if f and f["name"] == filename:
265
+ return {"id": fid, "name": f["name"], "size": len(f["data"])}
266
+ return None
267
+
268
+ def download_file_bytes(self, target, space, file_id, *, token=None, **kw):
269
+ return self.files[file_id]["data"]
270
+
271
+ def replace_file_in_skill(self, target, space, item, old_file_id, new_file_id, *, token=None, **kw):
272
+ current = [new_file_id if f == old_file_id else f for f in (item.get("files") or [])]
273
+ if old_file_id not in (item.get("files") or []):
274
+ current.append(new_file_id)
275
+ item = {**item, "files": current}
276
+ self.skill = item
277
+ return item
278
+
279
+ def _update(self, source):
280
+ from formist_cli.skills import update_skill_from_source
281
+
282
+ return update_skill_from_source(
283
+ LOCAL,
284
+ SPACE,
285
+ self.skill,
286
+ source,
287
+ token="t",
288
+ patch=self.patch_import,
289
+ upload_file=self.upload_file,
290
+ attach_file_to_skill=self.attach_file_to_skill,
291
+ find_existing_attachment=self.find_existing_attachment,
292
+ download_file_bytes=self.download_file_bytes,
293
+ replace_file_in_skill=self.replace_file_in_skill,
294
+ )
295
+
296
+
297
+ class TestUpdateSkillAttachmentsAreDeduped:
298
+ """The bug: re-running `fm skills-update` on an unchanged SOURCE used to
299
+ re-attach the same template file every time (`_attach_all` uploaded and
300
+ appended unconditionally). These pin the fix at the level
301
+ `update_skill_from_source` actually runs at, not just `find_existing_attachment`
302
+ in isolation.
303
+ """
304
+
305
+ def test_running_it_twice_with_identical_content_leaves_the_count_unchanged(
306
+ self, tmp_path
307
+ ):
308
+ d = _write_dir(tmp_path, extra_files={"template.pptx": b"same bytes every run"})
309
+ store = _FakeSkillStore({"id": str(uuid4()), "name": "Old Name", "files": []})
310
+
311
+ first = store._update(str(d))
312
+ assert len(first["files"]) == 1
313
+ second = store._update(str(d))
314
+ assert len(second["files"]) == 1, "a second run with unchanged content must not grow the list"
315
+ assert second["files"] == first["files"], "the same File row must still be the one attached"
316
+
317
+ def test_changed_content_replaces_the_same_slot_rather_than_appending(self, tmp_path):
318
+ store = _FakeSkillStore({"id": str(uuid4()), "name": "Old Name", "files": []})
319
+ d1 = _write_dir(tmp_path, extra_files={"template.pptx": b"version one"})
320
+ first = store._update(str(d1))
321
+ assert len(first["files"]) == 1
322
+ old_file_id = first["files"][0]
323
+
324
+ d2 = tmp_path / "v2"
325
+ d2.mkdir()
326
+ (d2 / "SKILL.md").write_text(MARKDOWN, encoding="utf-8")
327
+ (d2 / "template.pptx").write_bytes(b"version two, different bytes")
328
+
329
+ second = store._update(str(d2))
330
+ assert len(second["files"]) == 1, "a changed attachment must replace, never append, its old slot"
331
+ assert second["files"][0] != old_file_id, "the stale File id must be gone, a fresh one in its place"
332
+
333
+ def test_a_genuinely_new_name_is_still_appended(self, tmp_path):
334
+ store = _FakeSkillStore({"id": str(uuid4()), "name": "Old Name", "files": []})
335
+ d1 = _write_dir(tmp_path, extra_files={"a.pptx": b"first attachment"})
336
+ first = store._update(str(d1))
337
+ assert len(first["files"]) == 1
338
+
339
+ d2 = tmp_path / "v2"
340
+ d2.mkdir()
341
+ (d2 / "SKILL.md").write_text(MARKDOWN, encoding="utf-8")
342
+ (d2 / "a.pptx").write_bytes(b"first attachment") # unchanged, deduped
343
+ (d2 / "b.docx").write_bytes(b"a second, different attachment")
344
+
345
+ second = store._update(str(d2))
346
+ assert len(second["files"]) == 2, "a new name is additive; the existing one is still deduped"
347
+
348
+
230
349
  class TestUpdateSkillFromSource:
231
350
  def test_patches_the_resolved_skills_own_id_never_re_resolving(self, tmp_path):
232
351
  d = _write_dir(tmp_path)
@@ -25,7 +25,7 @@ wheels = [
25
25
 
26
26
  [[package]]
27
27
  name = "formist-cli"
28
- version = "0.1.0"
28
+ version = "0.1.1"
29
29
  source = { editable = "." }
30
30
 
31
31
  [package.dev-dependencies]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes