@giamme/forge 0.16.0 → 0.18.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.
Files changed (95) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/SKILL.md +16 -3
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +8 -0
  5. package/docs/commands.md +70 -6
  6. package/docs/dataset.md +13 -0
  7. package/docs/decomposed-runs.md +8 -0
  8. package/docs/forge-ui.md +23 -2
  9. package/docs/memory.md +2 -0
  10. package/docs/reviews.md +15 -1
  11. package/docs/safety.md +8 -0
  12. package/forge +24 -1
  13. package/package.json +1 -1
  14. package/references/dataset.md +143 -5
  15. package/references/decision-models.md +15 -2
  16. package/references/decompose.md +180 -11
  17. package/references/planning.md +3 -2
  18. package/references/solo.md +2 -1
  19. package/references/ui.md +5 -2
  20. package/scripts/forge-artifact.sh +14 -0
  21. package/scripts/forge-brief.py +132 -0
  22. package/scripts/forge-compare.py +11 -1
  23. package/scripts/forge-config.py +176 -9
  24. package/scripts/forge-contract.py +98 -4
  25. package/scripts/forge-control.py +86 -13
  26. package/scripts/forge-dispatch.sh +14 -10
  27. package/scripts/forge-du.py +167 -0
  28. package/scripts/forge-issues.py +4 -3
  29. package/scripts/forge-ledger.py +3 -1
  30. package/scripts/forge-lib-adopt.sh +8 -1
  31. package/scripts/forge-lib-plans.sh +5 -2
  32. package/scripts/forge-lib-review.sh +29 -1
  33. package/scripts/forge-metrics.sh +29 -3
  34. package/scripts/forge-parallel-options.sh +4 -0
  35. package/scripts/forge-parallel.sh +506 -10
  36. package/scripts/forge-plan-check.py +25 -2
  37. package/scripts/forge-planner.py +20 -6
  38. package/scripts/forge-prompt.py +120 -0
  39. package/scripts/forge-retro.py +115 -0
  40. package/scripts/forge-runs-compact.py +443 -0
  41. package/scripts/forge-runs-rm.py +2 -0
  42. package/scripts/forge-runs.py +18 -3
  43. package/scripts/forge-schedule.py +279 -4
  44. package/scripts/forge-shadow.py +35 -10
  45. package/scripts/forge-solo.sh +2 -0
  46. package/scripts/forge-summarize.py +698 -0
  47. package/scripts/forge-sweep.py +25 -10
  48. package/scripts/forge-ui-options.sh +10 -0
  49. package/scripts/forge_brief/__init__.py +587 -0
  50. package/scripts/forge_brief/answers.py +459 -0
  51. package/scripts/forge_dataset/__init__.py +10 -0
  52. package/scripts/forge_dataset/cli.py +83 -0
  53. package/scripts/forge_dataset/export.py +18 -4
  54. package/scripts/forge_dataset/facts.py +280 -0
  55. package/scripts/forge_dataset/harvest.py +56 -9
  56. package/scripts/forge_dataset/history.py +5 -3
  57. package/scripts/forge_dataset/outcomes.py +206 -58
  58. package/scripts/forge_dataset/pairs.py +174 -0
  59. package/scripts/forge_dataset/risk.py +108 -0
  60. package/scripts/forge_dataset/tiers.py +427 -0
  61. package/scripts/forge_decide/__init__.py +11 -1
  62. package/scripts/forge_decide/cli.py +23 -2
  63. package/scripts/forge_decide/labels.py +30 -6
  64. package/scripts/forge_decide/replay.py +10 -4
  65. package/scripts/forge_locations.py +366 -0
  66. package/scripts/forge_registry.py +19 -0
  67. package/scripts/forge_retro/__init__.py +417 -0
  68. package/scripts/forge_retro/issues.py +1193 -0
  69. package/scripts/forge_retro/report.py +671 -0
  70. package/scripts/forge_side/__init__.py +477 -0
  71. package/scripts/forge_storage.py +515 -0
  72. package/ui/README.md +68 -8
  73. package/ui/docs/api.md +217 -20
  74. package/ui/forge_ui/control.py +92 -11
  75. package/ui/forge_ui/export.py +31 -5
  76. package/ui/forge_ui/findings.py +4 -2
  77. package/ui/forge_ui/links.py +337 -0
  78. package/ui/forge_ui/models.py +57 -4
  79. package/ui/forge_ui/projects.py +4 -1
  80. package/ui/forge_ui/reader.py +732 -34
  81. package/ui/forge_ui/server.py +8 -0
  82. package/ui/forge_ui/static/app.js +92 -5
  83. package/ui/forge_ui/static/briefview.js +302 -0
  84. package/ui/forge_ui/static/checksview.js +6 -2
  85. package/ui/forge_ui/static/controls.js +5 -0
  86. package/ui/forge_ui/static/diffview.js +7 -3
  87. package/ui/forge_ui/static/index.html +3 -0
  88. package/ui/forge_ui/static/panel.js +311 -4
  89. package/ui/forge_ui/static/runmodel.js +13 -1
  90. package/ui/forge_ui/static/storageview.js +271 -0
  91. package/ui/forge_ui/static/style.css +100 -3
  92. package/ui/forge_ui/static/worktreesview.js +3 -3
  93. package/ui/forge_ui/storage.py +136 -0
  94. package/ui/forge_ui/transcripts.py +35 -10
  95. package/ui/forge_ui/worktrees.py +154 -13
@@ -4,8 +4,8 @@ The server never writes a run dir, a repo or forge's config itself. A write is o
4
4
  `<forge root>/forge ...` with an argv list and no shell, in its own process group, under a lock;
5
5
  this module holds the route table, the body validation, the call and the mapping of the CLI's
6
6
  exit code to an HTTP answer. server.py does the authentication and hands each authenticated POST
7
- to `dispatch`. Profile create and edit are the one call that writes a JSON body to the CLI's
8
- stdin (`--file -`); every other call has no stdin.
7
+ to `dispatch`. Profile create and edit write a JSON body to the CLI's stdin (`--file -`);
8
+ a brief answer writes the answer text the same way. Every other call has no stdin.
9
9
  """
10
10
  from __future__ import annotations
11
11
 
@@ -34,6 +34,10 @@ MAX_DECIDE_VALUE = 256
34
34
  # The profile object written to `forge config profile … --file -`. The HTTP body is already capped
35
35
  # at 64 KiB by the server; this caps the stdin text itself, which a re-encode can make larger.
36
36
  MAX_PROFILE_BODY = 64 * 1024
37
+ # A brief answer, in characters. The CLI then keeps the leading 4 KiB of what remains after it
38
+ # strips control characters; this bound is the one the route enforces before that call.
39
+ MAX_ANSWER = 4096
40
+ _QID = re.compile(r'^q[0-9]+$')
37
41
  _PROFILE_NAME = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$')
38
42
  _PROFILE_KEY = re.compile(r'^(routing|policy)\.[a-z_.]+$')
39
43
  _PROFILE_ACTIONS = ('create', 'edit', 'set', 'unset', 'rm', 'use')
@@ -133,8 +137,9 @@ def run_cli(argv, timeout, stdin=None):
133
137
  On timeout the whole group gets SIGTERM, then SIGKILL after TERM_WAIT_S, and the leader is
134
138
  reaped before this returns, so a caller that holds a lock can release it knowing nothing of
135
139
  the call is still running. The CLI's environment is the server's plus `cli_env`. `stdin` is
136
- bytes written to the process and then closed, or None. Only a profile create or edit passes
137
- any, and only after its size was checked; every other call keeps stdin closed.
140
+ bytes written to the process and then closed, or None. A profile create or edit passes the
141
+ profile object, and a brief answer passes the answer text, each only after its size was
142
+ checked; every other call keeps stdin closed.
138
143
  """
139
144
  env = dict(os.environ, **cli_env) if cli_env else None
140
145
  try:
@@ -205,6 +210,26 @@ def map_exit(result):
205
210
  return status, body
206
211
 
207
212
 
213
+ def _text_exit(result):
214
+ """(status, body) for a CLI that prints text. Exit 0 is success even with no JSON object.
215
+
216
+ A late brief answer prints a notice and exits 0. `output` is stdout, so the page can show it.
217
+ A non-zero exit uses the same status mapping as `map_exit` and also carries `exit` and `output`.
218
+ """
219
+ if result.timed_out:
220
+ return 504, {'error': 'timeout', 'detail': TIMEOUT_DETAIL}
221
+ if result.error:
222
+ return 502, {'error': 'bad gateway', 'detail': result.error[:DETAIL_MAX]}
223
+ output = result.stdout
224
+ if result.code == 0:
225
+ return 200, {'exit': 0, 'output': output}
226
+ status, error = _EXITS.get(result.code, (502, 'bad gateway'))
227
+ detail = _message(result.stderr) if result.code == 3 else _last_line(result.stderr)
228
+ body = {'error': error, 'detail': detail or f'the forge CLI exited {result.code}',
229
+ 'exit': result.code, 'output': output}
230
+ return status, body
231
+
232
+
208
233
  # -------------------------------------------------------------------------------------- validation
209
234
 
210
235
  class BadBody(Exception):
@@ -268,12 +293,14 @@ class Context:
268
293
  found = self.server.catalog.locate(self.key)
269
294
  return found[0] if found and found[1] in kinds else None
270
295
 
271
- def call(self, *args, limit=None, stdin=None):
296
+ def call(self, *args, limit=None, stdin=None, json_stdout=True):
272
297
  """One CLI call, mapped to (status, body); the run's lock is the caller's to hold.
273
298
 
274
299
  `limit` is the route's timeout; a timeout given to `dispatch` (a test's) replaces it.
275
- `stdin` is bytes for the one profile write that uses `--file -`, or None."""
276
- return map_exit(run_cli([str(self.cli), *args], self.timeout or limit or TIMEOUT_S, stdin=stdin))
300
+ `stdin` is bytes for a call that uses `--file -`, or None. `json_stdout` is false when a
301
+ successful CLI prints text (a brief answer, including a late-answer notice)."""
302
+ result = run_cli([str(self.cli), *args], self.timeout or limit or TIMEOUT_S, stdin=stdin)
303
+ return map_exit(result) if json_stdout else _text_exit(result)
277
304
 
278
305
  def locked(self, work):
279
306
  """work() under the run's lock; 409 busy when another write to this run is in flight."""
@@ -305,6 +332,43 @@ def _change(ctx):
305
332
  return ctx.locked(lambda: ctx.call('control', action, path, *tail, '--actor', 'ui', '--json'))
306
333
 
307
334
 
335
+ def _answer_text(value):
336
+ """The answer string, or BadBody. 1 to MAX_ANSWER characters, no NUL, encodable as UTF-8."""
337
+ if not isinstance(value, str):
338
+ raise BadBody('answer must be a string')
339
+ if '\x00' in value:
340
+ raise BadBody('answer must not contain a NUL')
341
+ if not 1 <= len(value) <= MAX_ANSWER:
342
+ raise BadBody(f'answer must be 1 to {MAX_ANSWER} characters')
343
+ try:
344
+ return value.encode('utf-8')
345
+ except UnicodeEncodeError:
346
+ raise BadBody('answer must be valid text')
347
+
348
+
349
+ def _brief_answer(ctx):
350
+ """POST an answer: `forge brief answer <plan> <task> <qid> --file - --actor ui`, text on stdin.
351
+
352
+ A late answer is exit 0 with a notice on stdout, so it is a success and the page can show it.
353
+ """
354
+ ctx.route = 'brief'
355
+ task, qid = ctx.parts
356
+ try:
357
+ if not isinstance(ctx.body, dict):
358
+ raise BadBody('body must be a JSON object')
359
+ if not _QID.fullmatch(qid):
360
+ raise BadBody('qid must match ^q[0-9]+$')
361
+ _check_fields(ctx.body, ('answer',))
362
+ stdin = _answer_text(ctx.body.get('answer'))
363
+ except BadBody as exc:
364
+ return _invalid(str(exc))
365
+ path = ctx.locate(('plan',))
366
+ if path is None:
367
+ return 404, {'error': 'not found'}
368
+ return ctx.locked(lambda: ctx.call('brief', 'answer', path, task, qid, '--file', '-', '--actor', 'ui',
369
+ stdin=stdin, json_stdout=False))
370
+
371
+
308
372
  # ----------------------------------------------------------------- issues, delete and config routes
309
373
 
310
374
  def _invalid(detail):
@@ -839,6 +903,19 @@ def _project_memories(ctx):
839
903
  return (404, {'error': 'not found'}) if found is None else (200, found)
840
904
 
841
905
 
906
+ def _storage(ctx):
907
+ # The Disk screen (#139): forge_storage's report, measured in the background and cached per server
908
+ # (storage.CACHE_S); ?refresh=1 measures again.
909
+ from forge_ui import storage
910
+ ctx.route = 'storage'
911
+ try:
912
+ params = _query_params(ctx.query, ('refresh',))
913
+ refresh = _bit(params, 'refresh')
914
+ except BadBody as exc:
915
+ return _invalid(str(exc))
916
+ return 200, storage.screen(ctx.server).answer(refresh=refresh)
917
+
918
+
842
919
  def _worktrees(ctx):
843
920
  # The Worktrees screen (#125): git and the run dirs, read here, plus the history `forge dataset worktrees`
844
921
  # keeps, read through the CLI. Cached per server (worktrees.CACHE_S); ?refresh=1 reads everything again.
@@ -859,6 +936,8 @@ def _worktrees(ctx):
859
936
  ROUTES = [
860
937
  ('GET', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _show),
861
938
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _change),
939
+ ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/tasks/([A-Za-z0-9][A-Za-z0-9._-]{0,127})/brief/([^/]+)'),
940
+ _brief_answer),
862
941
  ('GET', re.compile(r'/api/runs/([0-9a-f]{12})/issues'), _issues_list),
863
942
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues'), _issues_file),
864
943
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues/dismiss'), _issues_dismiss),
@@ -869,6 +948,7 @@ ROUTES = [
869
948
  ('POST', re.compile(r'/api/config()'), _config_set),
870
949
  ('GET', re.compile(r'/api/models/reviewers()'), _reviewer_outcomes),
871
950
  ('GET', re.compile(r'/api/worktrees()'), _worktrees),
951
+ ('GET', re.compile(r'/api/storage()'), _storage),
872
952
  ('GET', re.compile(r'/api/projects()'), _projects),
873
953
  ('GET', re.compile(r'/api/projects/([0-9a-f]{8})'), _project),
874
954
  ('GET', re.compile(r'/api/projects/([0-9a-f]{8})/findings'), _project_findings),
@@ -877,12 +957,12 @@ ROUTES = [
877
957
 
878
958
 
879
959
  def match(method, path):
880
- """(handler, run key) for a route, or None."""
960
+ """(handler, match) for a route, or None. Group 1 of the match is the run key."""
881
961
  for verb, pattern, handler in ROUTES:
882
962
  if verb == method:
883
963
  found = pattern.fullmatch(path)
884
964
  if found:
885
- return handler, found.group(1)
965
+ return handler, found
886
966
  return None
887
967
 
888
968
 
@@ -895,7 +975,8 @@ def dispatch(server, cli, method, path, body, timeout=None, query=''):
895
975
  found = match(method, path)
896
976
  if found is None:
897
977
  return None
898
- handler, key = found
899
- ctx = Context(server, cli, key, body, timeout, query)
978
+ handler, matched = found
979
+ ctx = Context(server, cli, matched.group(1), body, timeout, query)
980
+ ctx.parts = matched.groups()[1:]
900
981
  status, obj = handler(ctx)
901
982
  return status, obj, ctx.route, ctx.key
@@ -25,9 +25,23 @@ import urllib.parse
25
25
  from forge_ui import __version__, reader, server
26
26
 
27
27
  STATIC = server.STATIC_DIR
28
- # what the exported page runs, in index.html's order; the cloud, the leaderboard and notifications need a server
29
- SCRIPTS = ('theme.js', 'icons.js', 'datatable.js', 'shell.js', 'runmodel.js', 'cloudmodel.js', 'graph.js', 'gantt.js', 'verifyview.js', 'checksview.js', 'panel.js', 'diffview.js', 'convo.js', 'files.js', 'map3d.js',
30
- 'search.js', 'app.js')
28
+ # what the exported page runs; every other script index.html loads is in LEFT_OUT, with the reason
29
+ SCRIPTS = ('theme.js', 'icons.js', 'datatable.js', 'shell.js', 'runmodel.js', 'cloudmodel.js', 'graph.js', 'gantt.js', 'verifyview.js', 'checksview.js',
30
+ 'briefview.js', 'panel.js', 'diffview.js', 'convo.js', 'files.js', 'map3d.js', 'search.js', 'app.js')
31
+ LEFT_OUT = {
32
+ 'uikit.js': 'write helpers and the guards that keep a poll from redrawing what a person holds; a snapshot neither writes nor polls',
33
+ 'controls.js': 'changes a live run',
34
+ 'rundelete.js': 'deletes a run',
35
+ 'settings.js': 'the settings screen reads and writes the server',
36
+ 'notify.js': 'notifications come from polling the run list',
37
+ 'modelstats.js': 'the model leaderboard needs /api/models, which a snapshot does not carry',
38
+ 'leaderboard.js': 'the model leaderboard needs /api/models, which a snapshot does not carry',
39
+ 'cloudui.js': 'the run cloud needs every run, and a snapshot carries one',
40
+ 'findingsview.js': 'the open-findings page dismisses findings or files them as issues',
41
+ 'worktreesview.js': 'the Worktrees screen needs /api/worktrees',
42
+ 'storageview.js': 'the Disk screen needs /api/storage',
43
+ 'projectsview.js': 'the Projects screen needs every run of the repository',
44
+ }
31
45
  MODULES = ('iso.js', 'cloud3d.js', 'findings3d.js', 'stagectl.js', 'scene3d.js') # bundled in dependency order
32
46
  DIFF_CAP = 1 << 20 # one diff's JSON
33
47
  TRANSCRIPT_CAP = 2 << 20 # one execution's transcript
@@ -40,8 +54,14 @@ _TEXT_KEYS = frozenset(('prompt', 'last', 'request', 'log_tail', 'dwarf_tail', '
40
54
  'dwarf_input', 'error', 'last_line', 'message', 'excerpt', 'tail', 'lines', 'call', 'split',
41
55
  'needs_input', 'detail'))
42
56
  # keys that are private text only under one parent: a person's --reason on each decision (`reason` elsewhere is
43
- # a short machine word, such as a sweep's dropped-finding reason, and stays)
44
- _TEXT_KEYS_UNDER = {'decisions': frozenset(('reason',))}
57
+ # a short machine word, such as a sweep's dropped-finding reason, and stays); the --reason of each adoption too.
58
+ # A task header's goal and criteria are paragraphs of the prompt; the run's own `goal` (its title) stays.
59
+ # A brief question's why, the choices in options, its default and the answer a person typed are private
60
+ # only under `questions` and `parked` (`text` is already in _TEXT_KEYS). `scope`, `state` and `id` stay.
61
+ _TEXT_KEYS_UNDER = {'decisions': frozenset(('reason',)), 'adoptions': frozenset(('reason',)),
62
+ 'adoption': frozenset(('reason',)), 'header': frozenset(('goal', 'criteria')),
63
+ 'questions': frozenset(('why', 'options', 'default', 'answer')),
64
+ 'parked': frozenset(('why', 'options', 'default', 'answer'))}
45
65
 
46
66
 
47
67
  def _enc(value):
@@ -172,6 +192,10 @@ def build(catalog, key, texts=False, paths=False, now=None):
172
192
  reviews = [r.get('name') for r in (run.get('final_reviews') or []) if isinstance(r, dict) and r.get('name')]
173
193
  for name in reviews:
174
194
  snap.add(f'{base}/final-reviews/{_enc(name)}')
195
+ adopted = [a['review'] for a in (run.get('adoptions') or []) if isinstance(a, dict) and isinstance(a.get('review'), str)
196
+ and re.fullmatch(r'adopt-[0-9]+-[0-9]+', a['review'])]
197
+ for name in adopted:
198
+ snap.add(f'{base}/adoptions/{_enc(name)}')
175
199
  snap.add(f'{base}/files')
176
200
  snap.add(f'{base}/findings')
177
201
  fractal = run.get('fractal') or {}
@@ -193,6 +217,8 @@ def build(catalog, key, texts=False, paths=False, now=None):
193
217
  snap.add(url, cap=DIFF_CAP)
194
218
  for name in reviews:
195
219
  snap.add(f'{base}/final-reviews/{_enc(name)}/diff', cap=DIFF_CAP)
220
+ for name in adopted:
221
+ snap.add(f'{base}/adoptions/{_enc(name)}/diff', cap=DIFF_CAP)
196
222
  # what each dwarf and reviewer said and ran: its conversation is all text, and so are the commands it ran
197
223
  for name in names:
198
224
  if name.startswith(('dwarf-', 'qa-')):
@@ -104,14 +104,16 @@ def listing(text, limit=200):
104
104
  return None
105
105
  result = []
106
106
  for status, severity, line, block in found[:limit]:
107
- first = block.split('\n', 1)[0]
107
+ first, facts = block.split('\n', 1)[0], None
108
108
  try:
109
109
  match = module._LOCATION.search(first)
110
+ # #119: the facts suffix is shown apart, never as part of the summary
111
+ first, facts = module.split_facts(first)[0], module.facts(block)
110
112
  except Exception:
111
113
  match = None
112
114
  result.append(dict(severity=None if severity is None else 'P%d' % severity, status=status,
113
115
  location=match.group(0) if match else None, line=line,
114
- summary=first.strip()[:_SUMMARY_MAX],
116
+ summary=first.strip()[:_SUMMARY_MAX], facts=facts,
115
117
  text=block if len(block) <= _TEXT_MAX else block[:_TEXT_MAX] + '…'))
116
118
  return result
117
119
 
@@ -0,0 +1,337 @@
1
+ """GitHub links named in a task's markdown. No network, and no git."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+
7
+ # A fenced block (CommonMark: up to three spaces, matching marker, backtick info has no backtick).
8
+ _FENCE = re.compile(r'^( {0,3})(`{3,}|~{3,})(.*)$')
9
+ # An ATX heading. `#8` has no space, so it stays a reference; `# Title` does not.
10
+ _ATX = re.compile(r'^[ ]{0,3}#{1,6}(?:[ \t]|$)')
11
+ # One block-quote marker: up to three spaces, `>`, and one optional space (CommonMark).
12
+ _QUOTE = re.compile(r'^( {0,3}> ?)')
13
+ # A thematic break. It takes precedence over a list marker (`- - -` is not a list).
14
+ _HR = re.compile(r'^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$')
15
+ _NEXT = re.compile(r'https://github\.com/[^\s<>)\]]+|(?<![\w/])#(\d+)\b', re.IGNORECASE)
16
+ _ISSUE = re.compile(
17
+ r'^https://github\.com/([^/\s?#]+)/([^/\s?#]+)/(issues|pull)/(\d+)(?:[/?#]|$)', re.IGNORECASE)
18
+ _REMOTES = (
19
+ re.compile(r'^git@github\.com:([^/]+)/([^/]+?)(?:\.git)?/?$', re.IGNORECASE),
20
+ re.compile(r'^ssh://(?:git@)?github\.com/([^/]+)/([^/]+?)(?:\.git)?/?$', re.IGNORECASE),
21
+ re.compile(r'^https://github\.com/([^/]+)/([^/]+?)(?:\.git)?/?$', re.IGNORECASE),
22
+ re.compile(r'^git://github\.com/([^/]+)/([^/]+?)(?:\.git)?/?$', re.IGNORECASE),
23
+ )
24
+
25
+
26
+ class _ListItem:
27
+ """One open list item. `indent` is the spaces a later line needs to stay inside it."""
28
+
29
+ def __init__(self, indent, has_content):
30
+ self.indent = indent
31
+ self.has_content = has_content
32
+
33
+
34
+ def _blank(line):
35
+ return line.strip(' \t') == ''
36
+
37
+
38
+ def _expand_leading(line):
39
+ """Leading tabs become spaces at stops of 4, the way CommonMark measures indent.
40
+
41
+ Only the indent is expanded. A tab later in the line is left as it is, and the original
42
+ line is what gets masked, so a reference's text does not move.
43
+ """
44
+ column = 0
45
+ index = 0
46
+ while index < len(line) and line[index] in ' \t':
47
+ if line[index] == ' ':
48
+ column += 1
49
+ else:
50
+ column += 4 - (column % 4)
51
+ index += 1
52
+ return ' ' * column + line[index:]
53
+
54
+
55
+ def _space_indent(line):
56
+ index = 0
57
+ while index < len(line) and line[index] == ' ':
58
+ index += 1
59
+ return index
60
+
61
+
62
+ def _open_fence(line):
63
+ """`(marker, length, indent)` or None. `line` is what remains after its containers."""
64
+ match = _FENCE.match(line)
65
+ if match is None:
66
+ return None
67
+ indent, mark, info = match.group(1), match.group(2), match.group(3)
68
+ if mark[0] == '`' and '`' in info:
69
+ return None
70
+ return mark[0], len(mark), len(indent)
71
+
72
+
73
+ def _close_fence(line, opened):
74
+ match = _FENCE.match(line)
75
+ if match is None:
76
+ return False
77
+ mark, info = match.group(2), match.group(3)
78
+ # CommonMark: a closer may take up to three spaces whatever the opener took; _FENCE caps it.
79
+ return mark[0] == opened[0] and len(mark) >= opened[1] and not info.strip()
80
+
81
+
82
+ def _list_opener(line):
83
+ """`(content indent, has content)` when `line` starts a list item, else None.
84
+
85
+ Four or more spaces before the marker is an indented code block, not a list. More than
86
+ four spaces after the marker are content; the item's own indent stays marker plus one.
87
+ """
88
+ if _HR.match(line):
89
+ return None
90
+ mark_at = 0
91
+ while mark_at < 3 and mark_at < len(line) and line[mark_at] == ' ':
92
+ mark_at += 1
93
+ if mark_at >= len(line) or line[mark_at] == ' ':
94
+ return None
95
+ body = line[mark_at:]
96
+ if body[0] in '-+*':
97
+ width = 1
98
+ else:
99
+ width = 0
100
+ while width < len(body) and width < 9 and body[width].isdigit():
101
+ width += 1
102
+ if width == 0 or width >= len(body) or body[width] not in '.)':
103
+ return None
104
+ width += 1
105
+ after = body[width:]
106
+ spaces = 0
107
+ while spaces < len(after) and after[spaces] == ' ':
108
+ spaces += 1
109
+ if spaces == 0 and after != '':
110
+ return None
111
+ if spaces == len(after):
112
+ padding, has_content = 1, False
113
+ elif spaces > 4:
114
+ padding, has_content = 1, True
115
+ else:
116
+ padding, has_content = spaces, True
117
+ return mark_at + width + padding, has_content
118
+
119
+
120
+ def _list_interrupts(line):
121
+ """A bullet interrupts a paragraph. An ordered marker does only when its number is 1."""
122
+ if _list_opener(line) is None:
123
+ return False
124
+ body = line[_space_indent(line):]
125
+ return body[:1] in '-+*' or body.startswith('1.') or body.startswith('1)')
126
+
127
+
128
+ def _interrupts_paragraph(line):
129
+ return (_ATX.match(line) is not None or _open_fence(line) is not None or _QUOTE.match(line) is not None
130
+ or _HR.match(line) is not None or _list_interrupts(line))
131
+
132
+
133
+ def _open_containers(rest, containers, paragraph):
134
+ """Open block quotes and list items at the start of `rest`. Return the leaf content."""
135
+ while rest:
136
+ match = _QUOTE.match(rest)
137
+ if match:
138
+ containers.append('quote')
139
+ rest = rest[match.end():]
140
+ paragraph = False
141
+ continue
142
+ opened = _list_opener(rest)
143
+ if opened is not None and (not paragraph or _list_interrupts(rest)):
144
+ indent, has_content = opened
145
+ containers.append(_ListItem(indent, has_content))
146
+ rest = rest[indent:]
147
+ paragraph = False
148
+ continue
149
+ break
150
+ return rest
151
+
152
+
153
+ def _continue(line, containers, allow_lazy):
154
+ """Match open quotes and list items outside-in.
155
+
156
+ Return `(kept, rest, lazy)`. A miss closes that container and everything inside it
157
+ (`kept` false) so the line is tried again. A fenced block does not continue lazily:
158
+ `allow_lazy` is only for a paragraph, and a line that starts a block is not one.
159
+ """
160
+ rest = line
161
+ for index, box in enumerate(containers):
162
+ if box == 'quote':
163
+ match = _QUOTE.match(rest)
164
+ if match:
165
+ rest = rest[match.end():]
166
+ continue
167
+ elif _blank(rest):
168
+ # A blank line stays in an item that already has content, and ends an empty one.
169
+ if not box.has_content:
170
+ del containers[index:]
171
+ return False, line, False
172
+ continue
173
+ else:
174
+ spaces = _space_indent(rest)
175
+ if spaces >= box.indent:
176
+ rest = rest[box.indent:]
177
+ box.has_content = True
178
+ continue
179
+ if allow_lazy and not _blank(line) and not _interrupts_paragraph(rest):
180
+ return True, line, True
181
+ del containers[index:]
182
+ return False, line, False
183
+ return True, rest, False
184
+
185
+
186
+ def _mask(text):
187
+ """Blank fenced blocks, inline code spans, and ATX heading lines. Length stays put.
188
+
189
+ A fence inside a block quote ends when the quote ends: a fenced block does not run on
190
+ into the next paragraph. A fence under a list item is indented with the item; that
191
+ indent is removed before the marker is recognized. A marker indented four or more
192
+ spaces outside a list is an indented code block and is left alone. A quoted fence
193
+ marker inside a top-level fence is content, so it does not close the outer fence.
194
+ """
195
+ masked, containers, fence, paragraph = [], [], None, False
196
+ lines = text.splitlines()
197
+ index = 0
198
+ while index < len(lines):
199
+ line = lines[index]
200
+ view = _expand_leading(line)
201
+ if fence is not None:
202
+ kept, rest, _lazy = _continue(view, containers, allow_lazy=False)
203
+ if not kept:
204
+ fence = None
205
+ continue
206
+ if _close_fence(rest, fence):
207
+ fence = None
208
+ masked.append(' ' * len(line))
209
+ index += 1
210
+ continue
211
+ kept, rest, lazy = _continue(view, containers, allow_lazy=paragraph)
212
+ if not kept:
213
+ continue
214
+ if lazy:
215
+ paragraph = True
216
+ masked.append(line)
217
+ index += 1
218
+ continue
219
+ rest = _open_containers(rest, containers, paragraph)
220
+ opened = _open_fence(rest)
221
+ if opened is not None:
222
+ fence = opened
223
+ paragraph = False
224
+ masked.append(' ' * len(line))
225
+ index += 1
226
+ continue
227
+ paragraph = not _blank(rest) and _ATX.match(rest) is None and _HR.match(rest) is None
228
+ masked.append(line)
229
+ index += 1
230
+ body = _mask_spans('\n'.join(masked))
231
+ blanked = []
232
+ for line in body.split('\n'):
233
+ blanked.append(' ' * len(line) if _ATX.match(line) else line)
234
+ return '\n'.join(blanked)
235
+
236
+
237
+ def _mask_spans(text):
238
+ """Blank inline code spans. A span closes on the next run of the same number of backticks."""
239
+ out, index, size = [], 0, len(text)
240
+ while index < size:
241
+ if text[index] != '`':
242
+ out.append(text[index])
243
+ index += 1
244
+ continue
245
+ end = index
246
+ while end < size and text[end] == '`':
247
+ end += 1
248
+ length, cursor, close = end - index, end, None
249
+ while cursor < size:
250
+ if text[cursor] != '`':
251
+ cursor += 1
252
+ continue
253
+ run = cursor
254
+ while run < size and text[run] == '`':
255
+ run += 1
256
+ if run - cursor == length:
257
+ close = run
258
+ break
259
+ cursor = run
260
+ if close is None:
261
+ out.append(text[index:end])
262
+ index = end
263
+ else:
264
+ out.append(' ' * (close - index))
265
+ index = close
266
+ return ''.join(out)
267
+
268
+
269
+ def _slug(origin):
270
+ """`(owner, repo)` of a GitHub remote, or None. SSH and HTTPS both work. No network."""
271
+ if not isinstance(origin, str):
272
+ return None
273
+ text = origin.strip()
274
+ if len(text) >= 2 and text[0] == text[-1] and text[0] in '\'"':
275
+ text = text[1:-1].strip()
276
+ for pattern in _REMOTES:
277
+ match = pattern.match(text)
278
+ if match is None:
279
+ continue
280
+ owner, repo = match.group(1), match.group(2)
281
+ if owner in ('.', '..') or repo in ('.', '..'):
282
+ return None
283
+ return owner, repo
284
+ return None
285
+
286
+
287
+ def _number(text):
288
+ """The integer, or None when the digit string is longer than Python will convert."""
289
+ try:
290
+ return int(text)
291
+ except ValueError:
292
+ return None
293
+
294
+
295
+ def _issue(token, source):
296
+ token = token.rstrip('.,;:!?')
297
+ match = _ISSUE.match(token)
298
+ if match is None:
299
+ return dict(kind='url', number=None, url=token, source=source)
300
+ number = _number(match.group(4))
301
+ # A number past the conversion limit is still a URL; it is not an issue number.
302
+ if number is None:
303
+ return dict(kind='url', number=None, url=token, source=source)
304
+ owner, repo, kind = match.group(1), match.group(2), match.group(3).lower()
305
+ path = 'pull' if kind == 'pull' else 'issues'
306
+ url = f'https://github.com/{owner}/{repo}/{path}/{number}'
307
+ return dict(kind='pr' if kind == 'pull' else 'issue', number=number, url=url, source=source)
308
+
309
+
310
+ def extract(text, source, origin=None):
311
+ """`[{kind, number, url, source}]` in order, deduplicated.
312
+
313
+ `kind` is `issue`, `pr` or `url`. A `#N` reference is an issue; its url is
314
+ `https://github.com/<owner>/<repo>/issues/N` when `origin` is that repo's GitHub
315
+ remote, and null otherwise. Full issue and pull URLs are canonical, so the same
316
+ number written as `#N` and as a URL is one link. A digit string Python will not
317
+ convert is skipped for `#N`, and kept as kind `url` for a full URL. Nothing is fetched.
318
+ """
319
+ if not text:
320
+ return []
321
+ slug = _slug(origin)
322
+ found, seen = [], set()
323
+ for match in _NEXT.finditer(_mask(text)):
324
+ if match.group(1) is None:
325
+ item = _issue(match.group(0), source)
326
+ else:
327
+ number = _number(match.group(1))
328
+ if number is None:
329
+ continue
330
+ url = f'https://github.com/{slug[0]}/{slug[1]}/issues/{number}' if slug else None
331
+ item = dict(kind='issue', number=number, url=url, source=source)
332
+ key = (item['kind'], item['number'], item['url'])
333
+ if key in seen:
334
+ continue
335
+ seen.add(key)
336
+ found.append(item)
337
+ return found