claude-dev-env 8.122.0 → 8.124.0
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.
- package/bin/ever-registered-hooks.mjs +2 -0
- package/bin/ever-registered-hooks.test.mjs +5 -0
- package/docs/templates/artifact-page/README.md +14 -1
- package/docs/templates/artifact-page/review-rounds.md +1 -1
- package/docs/templates/artifact-page/template.html +26 -18
- package/docs/templates/html-plan/README.md +4 -0
- package/hooks/blocking/artifact_current_page_fixtures/piled_review_page.html +399 -0
- package/hooks/blocking/artifact_current_page_fixtures/rebuilt_review_page.html +403 -0
- package/hooks/blocking/artifact_current_page_gate.py +418 -0
- package/hooks/blocking/artifact_repeated_item_render.cjs +112 -0
- package/hooks/blocking/closing_question_round_gate.py +387 -0
- package/hooks/blocking/closing_question_round_lines.py +109 -0
- package/hooks/blocking/closing_question_round_open_items.py +348 -0
- package/hooks/blocking/closing_question_round_transcript.py +344 -0
- package/hooks/blocking/open_tasks_stop_gate.py +12 -1
- package/hooks/blocking/open_tasks_transcript.py +30 -0
- package/hooks/blocking/open_tasks_transcript_records.py +57 -1
- package/hooks/blocking/test_artifact_current_page_gate.py +415 -0
- package/hooks/blocking/test_closing_question_round_gate.py +983 -0
- package/hooks/blocking/test_closing_question_round_gate_declaration.py +307 -0
- package/hooks/blocking/test_closing_question_round_gate_work.py +349 -0
- package/hooks/blocking/test_closing_question_round_lines.py +70 -0
- package/hooks/blocking/test_closing_question_round_open_items.py +238 -0
- package/hooks/blocking/test_closing_question_round_transcript.py +236 -0
- package/hooks/blocking/test_open_tasks_stop_gate.py +64 -0
- package/hooks/blocking/test_open_tasks_transcript.py +34 -0
- package/hooks/blocking/test_open_tasks_transcript_records.py +34 -0
- package/hooks/features/conduct-gates.md +6 -0
- package/hooks/hooks.json +15 -0
- package/hooks/hooks_constants/artifact_current_page_gate_constants.py +91 -0
- package/hooks/hooks_constants/artifact_dark_mode_gate_constants.py +3 -3
- package/hooks/hooks_constants/closing_question_round_gate_constants.py +167 -0
- package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +8 -0
- package/hooks/hooks_constants/test_artifact_current_page_gate_constants.py +53 -0
- package/hooks/hooks_constants/test_artifact_dark_mode_gate_constants.py +6 -0
- package/hooks/hooks_constants/test_closing_question_round_gate_constants.py +92 -0
- package/hooks/session/artifact_link_record.py +109 -0
- package/hooks/session/test_artifact_link_record.py +101 -0
- package/hooks/test_context_budget_hooks.py +2 -0
- package/package.json +1 -1
- package/scripts/policy_lint/adapter_configuration.py +6 -0
- package/scripts/policy_lint/config/constants.py +1 -0
- package/scripts/tests/test_adapter_configuration.py +8 -0
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""PreToolUse hook that keeps a published page at one link with each item drawn once.
|
|
3
|
+
|
|
4
|
+
A page a person reviews more than once goes wrong in two ways. An agent adds a
|
|
5
|
+
section on each round, so one screen is drawn in three places. Or a publish
|
|
6
|
+
with no link opens a second copy. This gate reads the page as the publish
|
|
7
|
+
would send it and refuses both::
|
|
8
|
+
|
|
9
|
+
Artifact {"file_path": "page.html"} first publish, each item once -> allowed
|
|
10
|
+
Artifact {"file_path": "page.html"} the page has a recorded link -> denied, names the link
|
|
11
|
+
Artifact {"file_path": "page.html", "url": "<link>"} one image drawn three times -> denied, names the image
|
|
12
|
+
Artifact {"file_path": "page.html", "url": "<link>"} each item once -> allowed, with a note
|
|
13
|
+
Artifact {"action": "read", ...} -> allowed
|
|
14
|
+
|
|
15
|
+
An item is an image larger than an icon, counted by the file its
|
|
16
|
+
``src`` names in the rendered page, or an element with a ``data-item``
|
|
17
|
+
key. The link record is a ``<meta name="artifact-link">`` tag in the
|
|
18
|
+
page, or the record file that ``session/artifact_link_record.py``
|
|
19
|
+
writes beside the page.
|
|
20
|
+
|
|
21
|
+
A host without Playwright or Chromium is denied with the install command,
|
|
22
|
+
because an unrendered page is the case this gate exists to stop.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import json
|
|
28
|
+
import subprocess
|
|
29
|
+
import sys
|
|
30
|
+
import tempfile
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import NamedTuple
|
|
33
|
+
|
|
34
|
+
hooks_root_directory = str(Path(__file__).resolve().parent.parent)
|
|
35
|
+
if hooks_root_directory not in sys.path:
|
|
36
|
+
sys.path.insert(0, hooks_root_directory)
|
|
37
|
+
|
|
38
|
+
from blocking.artifact_dark_mode_gate import published_page_path, wrap_in_publish_skeleton
|
|
39
|
+
from hooks_constants.artifact_current_page_gate_constants import (
|
|
40
|
+
ARTIFACT_EDITS_INPUT_KEY,
|
|
41
|
+
ARTIFACT_LINK_PATTERN,
|
|
42
|
+
ARTIFACT_URL_INPUT_KEY,
|
|
43
|
+
EDIT_NEW_TEXT_KEY,
|
|
44
|
+
EDIT_OLD_TEXT_KEY,
|
|
45
|
+
FULL_RULE_POINTER_TEMPLATE,
|
|
46
|
+
LINK_META_NAME,
|
|
47
|
+
LINK_META_SOURCE,
|
|
48
|
+
LINK_RECORD_SUFFIX,
|
|
49
|
+
LINK_RECORD_TITLE_KEY,
|
|
50
|
+
LINK_RECORD_URL_KEY,
|
|
51
|
+
LINK_SOURCE_JOINER,
|
|
52
|
+
LINK_SOURCE_WITH_OTHER_LINK_TEMPLATE,
|
|
53
|
+
MALFORMED_CALL_URL_TEMPLATE,
|
|
54
|
+
META_CONTENT_ATTRIBUTE,
|
|
55
|
+
META_NAME_ATTRIBUTE,
|
|
56
|
+
META_TAG_PATTERN,
|
|
57
|
+
PAGE_TITLE_PATTERN,
|
|
58
|
+
REPEAT_ITEM_KEY,
|
|
59
|
+
REPEAT_RENDERER_MISSING_HEADER,
|
|
60
|
+
REPEAT_RENDERER_SCRIPT_PATH,
|
|
61
|
+
REPEAT_TIMES_KEY,
|
|
62
|
+
REPEATED_ITEM_HEADER,
|
|
63
|
+
REPEATED_ITEM_LINE_TEMPLATE,
|
|
64
|
+
REPEATED_ITEM_RETRY_INSTRUCTION,
|
|
65
|
+
REPUBLISH_NOTE,
|
|
66
|
+
SECOND_LINK_REASON_TEMPLATE,
|
|
67
|
+
TAG_ATTRIBUTE_PATTERN,
|
|
68
|
+
)
|
|
69
|
+
from hooks_constants.artifact_dark_mode_gate_constants import (
|
|
70
|
+
ALLOW_EXIT_CODE,
|
|
71
|
+
ARTIFACT_TOOL_NAME,
|
|
72
|
+
BLOCK_EXIT_CODE,
|
|
73
|
+
GATE_EVENT_NAME,
|
|
74
|
+
RENDERER_MISSING_EXIT_CODE,
|
|
75
|
+
RENDERER_TIMEOUT_SECONDS,
|
|
76
|
+
)
|
|
77
|
+
from hooks_constants.artifact_template_pointer_constants import ARTIFACT_TEMPLATE_PATH
|
|
78
|
+
from hooks_constants.hook_block_logger import log_hook_block
|
|
79
|
+
from hooks_constants.hook_specific_output_keys import (
|
|
80
|
+
HOOK_EVENT_NAME_KEY,
|
|
81
|
+
HOOK_SPECIFIC_OUTPUT_KEY,
|
|
82
|
+
)
|
|
83
|
+
from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
|
|
84
|
+
from hooks_constants.spawn_readiness_hook_constants import (
|
|
85
|
+
ADDITIONAL_CONTEXT_KEY,
|
|
86
|
+
TOOL_INPUT_KEY,
|
|
87
|
+
TOOL_NAME_KEY,
|
|
88
|
+
)
|
|
89
|
+
from session.artifact_template_pointer import installed_template_path
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def page_source_after_edits(page_source: str, all_edits: object) -> str:
|
|
93
|
+
"""Return the page as the publish sends it, with the call's ``edits`` applied.
|
|
94
|
+
|
|
95
|
+
The Artifact tool applies the edits in order, all or none. Each ``old_str``
|
|
96
|
+
must occur exactly once in the page as it stands. An edit that can add a
|
|
97
|
+
section must be checked too, so the gate applies the same edits first::
|
|
98
|
+
|
|
99
|
+
[{"old_str": "old", "new_str": "new"}] on "<p>old</p>" -> "<p>new</p>"
|
|
100
|
+
one edit whose old_str is missing or occurs twice -> the page unchanged
|
|
101
|
+
no edits, or an edit that is not an old_str/new_str pair -> the page unchanged
|
|
102
|
+
|
|
103
|
+
A call with a missed edit publishes nothing, so the unchanged page is the
|
|
104
|
+
one the gate reads.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
page_source: The HTML in the page file.
|
|
108
|
+
all_edits: The ``edits`` value of the publish call, or None.
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
The page source with every edit applied, or the page source unchanged.
|
|
112
|
+
"""
|
|
113
|
+
if not isinstance(all_edits, list):
|
|
114
|
+
return page_source
|
|
115
|
+
edited_source = page_source
|
|
116
|
+
for each_edit in all_edits:
|
|
117
|
+
if not isinstance(each_edit, dict):
|
|
118
|
+
return page_source
|
|
119
|
+
old_text = each_edit.get(EDIT_OLD_TEXT_KEY)
|
|
120
|
+
new_text = each_edit.get(EDIT_NEW_TEXT_KEY)
|
|
121
|
+
if not isinstance(old_text, str) or not isinstance(new_text, str):
|
|
122
|
+
return page_source
|
|
123
|
+
if edited_source.count(old_text) != 1:
|
|
124
|
+
return page_source
|
|
125
|
+
edited_source = edited_source.replace(old_text, new_text)
|
|
126
|
+
return edited_source
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class _FolderRecord(NamedTuple):
|
|
130
|
+
source: str
|
|
131
|
+
page_exists: bool
|
|
132
|
+
link: str
|
|
133
|
+
title: str
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def is_artifact_link(candidate: object) -> bool:
|
|
137
|
+
"""Return whether ``candidate`` is a whole claude.ai artifact link.
|
|
138
|
+
|
|
139
|
+
>>> is_artifact_link("https://claude.ai/artifact/Ab_12")
|
|
140
|
+
True
|
|
141
|
+
>>> is_artifact_link("https://claude.ai/artifact/Ab_12/")
|
|
142
|
+
False
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
candidate: A call ``url``, a record ``url``, or a meta tag's content.
|
|
146
|
+
"""
|
|
147
|
+
return isinstance(candidate, str) and ARTIFACT_LINK_PATTERN.fullmatch(candidate) is not None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def page_title(page_source: str) -> str:
|
|
151
|
+
"""Return the text of the page's ``<title>``, or an empty string.
|
|
152
|
+
|
|
153
|
+
>>> page_title("<title> Sample Run </title><p>x</p>")
|
|
154
|
+
'Sample Run'
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
page_source: The HTML of the page.
|
|
158
|
+
"""
|
|
159
|
+
title_match = PAGE_TITLE_PATTERN.search(page_source)
|
|
160
|
+
return title_match.group(1).strip() if title_match else ""
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def link_record_path(page_path: Path) -> Path:
|
|
164
|
+
"""Return the record file that holds the link of the page at ``page_path``.
|
|
165
|
+
|
|
166
|
+
>>> link_record_path(Path("/work/first-look.html")).name
|
|
167
|
+
'first-look.html.artifact-link.json'
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
page_path: The local page file.
|
|
171
|
+
"""
|
|
172
|
+
return page_path.with_name(page_path.name + LINK_RECORD_SUFFIX)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _link_record(record_path: Path) -> dict[str, str]:
|
|
176
|
+
try:
|
|
177
|
+
loaded_record = json.loads(record_path.read_text(encoding="utf-8"))
|
|
178
|
+
except (OSError, ValueError):
|
|
179
|
+
return {}
|
|
180
|
+
if not isinstance(loaded_record, dict):
|
|
181
|
+
return {}
|
|
182
|
+
return {
|
|
183
|
+
each_key: each_value
|
|
184
|
+
for each_key, each_value in loaded_record.items()
|
|
185
|
+
if isinstance(each_key, str) and isinstance(each_value, str)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _meta_page_link(page_source: str) -> str:
|
|
190
|
+
for each_meta_tag in META_TAG_PATTERN.findall(page_source):
|
|
191
|
+
all_attributes: dict[str, str] = {}
|
|
192
|
+
for each_name, each_double_quoted, each_single_quoted in TAG_ATTRIBUTE_PATTERN.findall(
|
|
193
|
+
each_meta_tag
|
|
194
|
+
):
|
|
195
|
+
all_attributes.setdefault(
|
|
196
|
+
each_name.lower(), (each_double_quoted or each_single_quoted).strip()
|
|
197
|
+
)
|
|
198
|
+
meta_link = all_attributes.get(META_CONTENT_ATTRIBUTE, "")
|
|
199
|
+
is_link_meta = all_attributes.get(META_NAME_ATTRIBUTE, "").lower() == LINK_META_NAME
|
|
200
|
+
if is_link_meta and is_artifact_link(meta_link):
|
|
201
|
+
return meta_link
|
|
202
|
+
return ""
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _record_link(all_record_fields: dict[str, str]) -> str:
|
|
206
|
+
recorded_link = all_record_fields.get(LINK_RECORD_URL_KEY, "")
|
|
207
|
+
return recorded_link if is_artifact_link(recorded_link) else ""
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _renamed_page_records(page_path: Path, title: str) -> list[tuple[str, str]]:
|
|
211
|
+
if not title:
|
|
212
|
+
return []
|
|
213
|
+
all_folder_records = []
|
|
214
|
+
for each_record_path in sorted(page_path.parent.glob("*" + LINK_RECORD_SUFFIX)):
|
|
215
|
+
each_page_path = page_path.parent / each_record_path.name.removesuffix(LINK_RECORD_SUFFIX)
|
|
216
|
+
if each_page_path == page_path:
|
|
217
|
+
continue
|
|
218
|
+
each_record = _link_record(each_record_path)
|
|
219
|
+
all_folder_records.append(
|
|
220
|
+
_FolderRecord(
|
|
221
|
+
source=str(each_record_path),
|
|
222
|
+
page_exists=each_page_path.exists(),
|
|
223
|
+
link=_record_link(each_record),
|
|
224
|
+
title=each_record.get(LINK_RECORD_TITLE_KEY, ""),
|
|
225
|
+
)
|
|
226
|
+
)
|
|
227
|
+
links_of_other_present_pages = {
|
|
228
|
+
each_record.link for each_record in all_folder_records if each_record.page_exists
|
|
229
|
+
}
|
|
230
|
+
return [
|
|
231
|
+
(each_record.link, each_record.source)
|
|
232
|
+
for each_record in all_folder_records
|
|
233
|
+
if not each_record.page_exists
|
|
234
|
+
and each_record.title == title
|
|
235
|
+
and each_record.link
|
|
236
|
+
and each_record.link not in links_of_other_present_pages
|
|
237
|
+
]
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _page_link_and_source(page_path: Path, page_source: str) -> tuple[str, str]:
|
|
241
|
+
all_links_with_sources: list[tuple[str, str]] = []
|
|
242
|
+
meta_link = _meta_page_link(page_source)
|
|
243
|
+
if meta_link:
|
|
244
|
+
all_links_with_sources.append((meta_link, LINK_META_SOURCE))
|
|
245
|
+
own_record_path = link_record_path(page_path)
|
|
246
|
+
own_link = _record_link(_link_record(own_record_path))
|
|
247
|
+
if own_link:
|
|
248
|
+
all_links_with_sources.append((own_link, str(own_record_path)))
|
|
249
|
+
all_links_with_sources.extend(_renamed_page_records(page_path, page_title(page_source)))
|
|
250
|
+
if not all_links_with_sources:
|
|
251
|
+
return "", ""
|
|
252
|
+
first_link = all_links_with_sources[0][0]
|
|
253
|
+
return first_link, LINK_SOURCE_JOINER.join(
|
|
254
|
+
each_source
|
|
255
|
+
if each_link == first_link
|
|
256
|
+
else LINK_SOURCE_WITH_OTHER_LINK_TEMPLATE.format(source=each_source, link=each_link)
|
|
257
|
+
for each_link, each_source in all_links_with_sources
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def recorded_page_link(page_path: Path, page_source: str) -> str:
|
|
262
|
+
"""Return the link this page was published at before, or an empty string.
|
|
263
|
+
|
|
264
|
+
The gate looks in three places, in this order::
|
|
265
|
+
|
|
266
|
+
<meta name="artifact-link" content="<link>"> in the page -> that link
|
|
267
|
+
first-look.html.artifact-link.json beside first-look.html -> its url
|
|
268
|
+
a record in the same folder with this title, page file gone -> its url
|
|
269
|
+
|
|
270
|
+
Each place counts only when it holds an artifact link, and the meta tag
|
|
271
|
+
counts in either attribute order. The third place catches a page renamed
|
|
272
|
+
in its folder. A record whose page file is still there belongs to a
|
|
273
|
+
separate page, even when the two titles match, so it is skipped. So is a
|
|
274
|
+
record whose link the record of another page in the folder still holds.
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
page_path: The local page file.
|
|
278
|
+
page_source: The HTML the publish sends.
|
|
279
|
+
|
|
280
|
+
Returns:
|
|
281
|
+
The recorded link, or an empty string when the page has none.
|
|
282
|
+
"""
|
|
283
|
+
return _page_link_and_source(page_path, page_source)[0]
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _run_renderer(wrapped_page_path: Path) -> subprocess.CompletedProcess[str] | str:
|
|
287
|
+
try:
|
|
288
|
+
return subprocess.run(
|
|
289
|
+
["node", str(REPEAT_RENDERER_SCRIPT_PATH), str(wrapped_page_path)],
|
|
290
|
+
capture_output=True,
|
|
291
|
+
text=True,
|
|
292
|
+
timeout=RENDERER_TIMEOUT_SECONDS,
|
|
293
|
+
check=False,
|
|
294
|
+
)
|
|
295
|
+
except FileNotFoundError:
|
|
296
|
+
return "node is not installed; install Node.js, then run: npm install -g playwright && npx playwright install chromium"
|
|
297
|
+
except subprocess.TimeoutExpired:
|
|
298
|
+
return f"the render took longer than {RENDERER_TIMEOUT_SECONDS} seconds"
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def repeated_items(page_source: str) -> tuple[list[dict[str, object]] | None, str]:
|
|
302
|
+
"""Render the wrapped page and return each item it draws more than once.
|
|
303
|
+
|
|
304
|
+
Args:
|
|
305
|
+
page_source: The HTML the publish sends.
|
|
306
|
+
|
|
307
|
+
Returns:
|
|
308
|
+
The repeats (empty when each item is drawn once) and an empty message,
|
|
309
|
+
or None and the reason the renderer could not run.
|
|
310
|
+
"""
|
|
311
|
+
with tempfile.TemporaryDirectory() as scratch_directory:
|
|
312
|
+
wrapped_page_path = Path(scratch_directory) / "wrapped_page.html"
|
|
313
|
+
wrapped_page_path.write_text(wrap_in_publish_skeleton(page_source), encoding="utf-8")
|
|
314
|
+
completed_render = _run_renderer(wrapped_page_path)
|
|
315
|
+
if isinstance(completed_render, str):
|
|
316
|
+
return None, completed_render
|
|
317
|
+
if completed_render.returncode == RENDERER_MISSING_EXIT_CODE:
|
|
318
|
+
return None, completed_render.stderr.strip()
|
|
319
|
+
try:
|
|
320
|
+
all_repeats = json.loads(completed_render.stdout)
|
|
321
|
+
except ValueError:
|
|
322
|
+
all_repeats = None
|
|
323
|
+
if not isinstance(all_repeats, list):
|
|
324
|
+
return None, completed_render.stderr.strip() or "the renderer printed no result"
|
|
325
|
+
return all_repeats, ""
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def full_rule_pointer() -> str:
|
|
329
|
+
"""Return the sentence that names where the installed rule text sits.
|
|
330
|
+
|
|
331
|
+
Returns:
|
|
332
|
+
One sentence with the path of the artifact page README on this host.
|
|
333
|
+
"""
|
|
334
|
+
return FULL_RULE_POINTER_TEMPLATE.format(
|
|
335
|
+
path_of_page_readme=installed_template_path(ARTIFACT_TEMPLATE_PATH)
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def format_repeat_reason(all_repeats: list[dict[str, object]]) -> str:
|
|
340
|
+
"""Return the deny message that names each repeated item and its count.
|
|
341
|
+
|
|
342
|
+
Args:
|
|
343
|
+
all_repeats: The repeats the renderer reported, most repeated first.
|
|
344
|
+
|
|
345
|
+
Returns:
|
|
346
|
+
The message the session reads when the publish is denied.
|
|
347
|
+
"""
|
|
348
|
+
all_lines = [REPEATED_ITEM_HEADER]
|
|
349
|
+
all_lines.extend(
|
|
350
|
+
REPEATED_ITEM_LINE_TEMPLATE.format(
|
|
351
|
+
item=each_repeat.get(REPEAT_ITEM_KEY), times=each_repeat.get(REPEAT_TIMES_KEY)
|
|
352
|
+
)
|
|
353
|
+
for each_repeat in all_repeats
|
|
354
|
+
)
|
|
355
|
+
return "".join(all_lines) + REPEATED_ITEM_RETRY_INSTRUCTION + full_rule_pointer()
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _block(block_reason: str, page_path: Path) -> int:
|
|
359
|
+
log_hook_block(
|
|
360
|
+
Path(__file__).name,
|
|
361
|
+
GATE_EVENT_NAME,
|
|
362
|
+
block_reason,
|
|
363
|
+
tool_name=ARTIFACT_TOOL_NAME,
|
|
364
|
+
offending_input_preview=str(page_path),
|
|
365
|
+
)
|
|
366
|
+
sys.stderr.write(block_reason)
|
|
367
|
+
return BLOCK_EXIT_CODE
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _second_link_reason(link_in_call: object, recorded_link: str, link_source: str) -> str:
|
|
371
|
+
malformed_url_line = (
|
|
372
|
+
MALFORMED_CALL_URL_TEMPLATE.format(url=link_in_call)
|
|
373
|
+
if isinstance(link_in_call, str) and link_in_call
|
|
374
|
+
else ""
|
|
375
|
+
)
|
|
376
|
+
return malformed_url_line + SECOND_LINK_REASON_TEMPLATE.format(
|
|
377
|
+
link=recorded_link, link_source=link_source
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _republish_note_output() -> dict[str, dict[str, str]]:
|
|
382
|
+
return {
|
|
383
|
+
HOOK_SPECIFIC_OUTPUT_KEY: {
|
|
384
|
+
HOOK_EVENT_NAME_KEY: GATE_EVENT_NAME,
|
|
385
|
+
ADDITIONAL_CONTEXT_KEY: REPUBLISH_NOTE + full_rule_pointer(),
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def main() -> int:
|
|
391
|
+
hook_input = read_hook_input_dictionary_from_stdin()
|
|
392
|
+
if hook_input is None:
|
|
393
|
+
return ALLOW_EXIT_CODE
|
|
394
|
+
tool_input = hook_input.get(TOOL_INPUT_KEY)
|
|
395
|
+
page_path = published_page_path(hook_input.get(TOOL_NAME_KEY), tool_input)
|
|
396
|
+
if page_path is None or not page_path.is_file() or not isinstance(tool_input, dict):
|
|
397
|
+
return ALLOW_EXIT_CODE
|
|
398
|
+
page_source = page_source_after_edits(
|
|
399
|
+
page_path.read_text(encoding="utf-8", errors="replace"),
|
|
400
|
+
tool_input.get(ARTIFACT_EDITS_INPUT_KEY),
|
|
401
|
+
)
|
|
402
|
+
link_in_call = tool_input.get(ARTIFACT_URL_INPUT_KEY)
|
|
403
|
+
has_link_in_call = is_artifact_link(link_in_call)
|
|
404
|
+
recorded_link, link_source = _page_link_and_source(page_path, page_source)
|
|
405
|
+
if recorded_link and not has_link_in_call:
|
|
406
|
+
return _block(_second_link_reason(link_in_call, recorded_link, link_source), page_path)
|
|
407
|
+
all_repeats, renderer_problem = repeated_items(page_source)
|
|
408
|
+
if all_repeats is None:
|
|
409
|
+
return _block(REPEAT_RENDERER_MISSING_HEADER + renderer_problem, page_path)
|
|
410
|
+
if all_repeats:
|
|
411
|
+
return _block(format_repeat_reason(all_repeats), page_path)
|
|
412
|
+
if has_link_in_call:
|
|
413
|
+
sys.stdout.write(json.dumps(_republish_note_output()))
|
|
414
|
+
return ALLOW_EXIT_CODE
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
if __name__ == "__main__":
|
|
418
|
+
sys.exit(main())
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
const childProcess = require("child_process");
|
|
5
|
+
const fs = require("fs");
|
|
6
|
+
const path = require("path");
|
|
7
|
+
|
|
8
|
+
const LARGEST_ICON_SIDE_IN_PIXELS = 64;
|
|
9
|
+
const ITEM_NAME_LENGTH = 120;
|
|
10
|
+
const VIEWPORT_SIZE = { width: 1280, height: 900 };
|
|
11
|
+
const PAGE_LOAD_TIMEOUT_MILLISECONDS = 15000;
|
|
12
|
+
const IMAGE_SETTLE_TIMEOUT_MILLISECONDS = 3000;
|
|
13
|
+
const PAGE_ADDRESS = "https://artifact-page.invalid/";
|
|
14
|
+
const STAND_IN_IMAGE = '<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400"/>';
|
|
15
|
+
const RENDERER_MISSING_EXIT_CODE = 3;
|
|
16
|
+
|
|
17
|
+
function loadPlaywright() {
|
|
18
|
+
try {
|
|
19
|
+
return require("playwright");
|
|
20
|
+
} catch (localError) {
|
|
21
|
+
const globalRoot = childProcess.execSync("npm root -g", { encoding: "utf8" }).trim();
|
|
22
|
+
return require(path.join(globalRoot, "playwright"));
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function countDrawnItems([largestIconSide, itemNameLength]) {
|
|
27
|
+
const isDrawn = (element) => {
|
|
28
|
+
if (!element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
const box = element.getBoundingClientRect();
|
|
32
|
+
return box.width > 0 && box.height > 0;
|
|
33
|
+
};
|
|
34
|
+
const isLargerThanAnIcon = (element) => {
|
|
35
|
+
const box = element.getBoundingClientRect();
|
|
36
|
+
return box.width > largestIconSide || box.height > largestIconSide;
|
|
37
|
+
};
|
|
38
|
+
const countsByKind = { image: new Map(), "data-item": new Map() };
|
|
39
|
+
const countItem = (kind, countKey, item) => {
|
|
40
|
+
const itemCount = countsByKind[kind].get(countKey) || { kind, item: item.slice(0, itemNameLength), times: 0 };
|
|
41
|
+
itemCount.times += 1;
|
|
42
|
+
countsByKind[kind].set(countKey, itemCount);
|
|
43
|
+
};
|
|
44
|
+
for (const image of document.querySelectorAll("img[src]")) {
|
|
45
|
+
const source = image.getAttribute("src").trim();
|
|
46
|
+
if (source && isDrawn(image) && isLargerThanAnIcon(image)) {
|
|
47
|
+
countItem("image", image.src, source);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
for (const element of document.querySelectorAll("[data-item]")) {
|
|
51
|
+
const itemKey = element.getAttribute("data-item").trim();
|
|
52
|
+
if (itemKey && isDrawn(element)) {
|
|
53
|
+
countItem("data-item", itemKey, itemKey);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const allRepeats = Object.values(countsByKind)
|
|
57
|
+
.flatMap((itemCounts) => [...itemCounts.values()])
|
|
58
|
+
.filter((itemCount) => itemCount.times > 1);
|
|
59
|
+
return allRepeats.sort((first, second) => second.times - first.times);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function loadEveryImage(settleTimeout) {
|
|
63
|
+
const allLoads = [...document.querySelectorAll("img[src]")].map((image) => {
|
|
64
|
+
image.loading = "eager";
|
|
65
|
+
return image.complete ? Promise.resolve() : new Promise((resolve) => {
|
|
66
|
+
image.addEventListener("load", resolve, { once: true });
|
|
67
|
+
image.addEventListener("error", resolve, { once: true });
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
return Promise.race([Promise.all(allLoads), new Promise((resolve) => setTimeout(resolve, settleTimeout))]);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function main() {
|
|
74
|
+
const pageHtml = fs.readFileSync(process.argv[2], "utf8");
|
|
75
|
+
let playwright;
|
|
76
|
+
try {
|
|
77
|
+
playwright = loadPlaywright();
|
|
78
|
+
} catch (loadError) {
|
|
79
|
+
process.stderr.write("Playwright is not installed; run: npm install -g playwright && npx playwright install chromium\n");
|
|
80
|
+
return RENDERER_MISSING_EXIT_CODE;
|
|
81
|
+
}
|
|
82
|
+
let browser;
|
|
83
|
+
try {
|
|
84
|
+
browser = await playwright.chromium.launch();
|
|
85
|
+
} catch (launchError) {
|
|
86
|
+
process.stderr.write(`Chromium did not start for Playwright; run: npx playwright install chromium (${launchError.message.split("\n")[0]})\n`);
|
|
87
|
+
return RENDERER_MISSING_EXIT_CODE;
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
const page = await browser.newPage({ viewport: VIEWPORT_SIZE });
|
|
91
|
+
page.setDefaultTimeout(PAGE_LOAD_TIMEOUT_MILLISECONDS);
|
|
92
|
+
await page.route("**/*", (route) => {
|
|
93
|
+
const request = route.request();
|
|
94
|
+
if (request.url() === PAGE_ADDRESS) {
|
|
95
|
+
return route.fulfill({ contentType: "text/html; charset=utf-8", body: pageHtml });
|
|
96
|
+
}
|
|
97
|
+
if (request.resourceType() === "image") {
|
|
98
|
+
return route.fulfill({ contentType: "image/svg+xml", body: STAND_IN_IMAGE });
|
|
99
|
+
}
|
|
100
|
+
return route.continue();
|
|
101
|
+
});
|
|
102
|
+
await page.goto(PAGE_ADDRESS, { waitUntil: "load", timeout: PAGE_LOAD_TIMEOUT_MILLISECONDS }).catch(() => undefined);
|
|
103
|
+
await page.evaluate(loadEveryImage, IMAGE_SETTLE_TIMEOUT_MILLISECONDS).catch(() => undefined);
|
|
104
|
+
const allRepeats = await page.evaluate(countDrawnItems, [LARGEST_ICON_SIDE_IN_PIXELS, ITEM_NAME_LENGTH]);
|
|
105
|
+
process.stdout.write(JSON.stringify(allRepeats));
|
|
106
|
+
} finally {
|
|
107
|
+
await browser.close();
|
|
108
|
+
}
|
|
109
|
+
return 0;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
main().then((exitCode) => process.exit(exitCode));
|