studysystem 1.0.0__py3-none-any.whl

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 (112) hide show
  1. studysystem/__init__.py +1 -0
  2. studysystem/assets/note-callouts.lua +100 -0
  3. studysystem/assets/note-no-html.lua +28 -0
  4. studysystem/assets/note.css +146 -0
  5. studysystem/cli.py +344 -0
  6. studysystem/dashboard.html +781 -0
  7. studysystem/dashboard.py +377 -0
  8. studysystem/db/__init__.py +1 -0
  9. studysystem/db/engine.py +158 -0
  10. studysystem/db/migrate.py +122 -0
  11. studysystem/db/migrations/env.py +59 -0
  12. studysystem/db/migrations/script.py.mako +29 -0
  13. studysystem/db/migrations/versions/0000_baseline.py +19 -0
  14. studysystem/db/migrations/versions/0001_the_whole_schema.py +1743 -0
  15. studysystem/db/migrations/versions/0002_semester_ignores_case.py +38 -0
  16. studysystem/db/migrations/versions/0003_course_vault_folder.py +26 -0
  17. studysystem/db/migrations/versions/0004_note_pdf_path.py +26 -0
  18. studysystem/db/migrations/versions/0005_tagging_kind.py +39 -0
  19. studysystem/db/migrations/versions/0006_practice_mode.py +36 -0
  20. studysystem/db/migrations/versions/0007_exam_prep_from.py +25 -0
  21. studysystem/db/migrations/versions/0008_more_papers_kind.py +37 -0
  22. studysystem/db/migrations/versions/0009_past_exam_month_date.py +28 -0
  23. studysystem/db/migrations/versions/0010_task_parts.py +70 -0
  24. studysystem/db/migrations/versions/0011_observation_kind.py +39 -0
  25. studysystem/db/migrations/versions/0012_profile_claim.py +52 -0
  26. studysystem/db/migrations/versions/0013_assumed_instructor_papers.py +40 -0
  27. studysystem/db/migrations/versions/0014_scan_confirmation.py +44 -0
  28. studysystem/db/migrations/versions/0015_practice_item_count.py +37 -0
  29. studysystem/db/migrations/versions/0016_timetable_patterns.py +102 -0
  30. studysystem/db/migrations/versions/0017_course_dropped.py +36 -0
  31. studysystem/db/migrations/versions/0018_syllabus_topics.py +82 -0
  32. studysystem/db/migrations/versions/0019_course_lab_group.py +36 -0
  33. studysystem/db/migrations/versions/0020_chapter_scope.py +61 -0
  34. studysystem/db/migrations/versions/0021_note_retired_at.py +28 -0
  35. studysystem/db/migrations/versions/0022_rescope.py +48 -0
  36. studysystem/db/migrations/versions/0023_backlog_reason.py +42 -0
  37. studysystem/db/migrations/versions/0024_guess_sensitivity.py +35 -0
  38. studysystem/db/migrations/versions/0025_shortfall_inputs.py +83 -0
  39. studysystem/db/migrations/versions/0026_trials_switch.py +36 -0
  40. studysystem/db/tables.py +1096 -0
  41. studysystem/demo.py +722 -0
  42. studysystem/errors.py +39 -0
  43. studysystem/server/__init__.py +83 -0
  44. studysystem/server/__main__.py +5 -0
  45. studysystem/services/__init__.py +1 -0
  46. studysystem/services/adherence.py +147 -0
  47. studysystem/services/assessments.py +171 -0
  48. studysystem/services/capacity.py +164 -0
  49. studysystem/services/claims.py +405 -0
  50. studysystem/services/course_folder.py +82 -0
  51. studysystem/services/courses.py +176 -0
  52. studysystem/services/coverage.py +121 -0
  53. studysystem/services/dashboard_key.py +102 -0
  54. studysystem/services/feedback.py +412 -0
  55. studysystem/services/forward_eval.py +65 -0
  56. studysystem/services/gate.py +77 -0
  57. studysystem/services/generation.py +2864 -0
  58. studysystem/services/ids.py +15 -0
  59. studysystem/services/intake.py +278 -0
  60. studysystem/services/launcher.py +455 -0
  61. studysystem/services/lookups.py +91 -0
  62. studysystem/services/materials.py +97 -0
  63. studysystem/services/note_markdown.py +241 -0
  64. studysystem/services/notes.py +396 -0
  65. studysystem/services/parts.py +65 -0
  66. studysystem/services/past_exams.py +115 -0
  67. studysystem/services/pdf_render.py +148 -0
  68. studysystem/services/pdf_worker.py +184 -0
  69. studysystem/services/plan.py +1300 -0
  70. studysystem/services/private_view.py +38 -0
  71. studysystem/services/profiles.py +544 -0
  72. studysystem/services/programs.py +16 -0
  73. studysystem/services/replacements.py +107 -0
  74. studysystem/services/rescope.py +277 -0
  75. studysystem/services/settings.py +50 -0
  76. studysystem/services/setup.py +235 -0
  77. studysystem/services/shortfall.py +443 -0
  78. studysystem/services/state.py +846 -0
  79. studysystem/services/statements.py +222 -0
  80. studysystem/services/study_loop.py +998 -0
  81. studysystem/services/summaries.py +369 -0
  82. studysystem/services/syllabus.py +138 -0
  83. studysystem/services/system_work.py +113 -0
  84. studysystem/services/taxonomy.py +459 -0
  85. studysystem/services/topics.py +477 -0
  86. studysystem/services/trials.py +201 -0
  87. studysystem/services/unconfirmed.py +95 -0
  88. studysystem/services/units.py +34 -0
  89. studysystem/services/users.py +53 -0
  90. studysystem/services/values.py +168 -0
  91. studysystem/startup.py +147 -0
  92. studysystem/tools/__init__.py +4 -0
  93. studysystem/tools/course_setup.py +185 -0
  94. studysystem/tools/dashboard.py +27 -0
  95. studysystem/tools/feedback.py +66 -0
  96. studysystem/tools/gate.py +24 -0
  97. studysystem/tools/generation.py +156 -0
  98. studysystem/tools/materials.py +32 -0
  99. studysystem/tools/notes.py +29 -0
  100. studysystem/tools/past_exams.py +51 -0
  101. studysystem/tools/ping.py +9 -0
  102. studysystem/tools/plan.py +40 -0
  103. studysystem/tools/profiles.py +94 -0
  104. studysystem/tools/results.py +77 -0
  105. studysystem/tools/study_loop.py +145 -0
  106. studysystem/tools/summaries.py +52 -0
  107. studysystem/tools/topics.py +143 -0
  108. studysystem-1.0.0.dist-info/METADATA +254 -0
  109. studysystem-1.0.0.dist-info/RECORD +112 -0
  110. studysystem-1.0.0.dist-info/WHEEL +4 -0
  111. studysystem-1.0.0.dist-info/entry_points.txt +3 -0
  112. studysystem-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1 @@
1
+ """STUDYSYSTEM: an MCP server that plans and tracks a student's semester."""
@@ -0,0 +1,100 @@
1
+ -- The callout boxes (D-80, D-81): pandoc runs this on a note while turning it into the page
2
+ -- Chrome prints. A paragraph or bullet that starts with a note marker becomes a box - a div with
3
+ -- classes `callout` and its kind, styled by note.css; a run of the same marker joins into one box
4
+ -- with one title.
5
+ -- A line naming more than one marker (the legend) stays plain; a marker mid-sentence stays inline.
6
+
7
+ local MARKERS = {
8
+ { prefix = "\u{26A0}", kind = "warning", title = "\u{26A0}\u{FE0F} Common mistake" },
9
+ { prefix = "\u{1F4A1}", kind = "tip", title = "\u{1F4A1} Tip" },
10
+ { prefix = "\u{1F3AF}", kind = "target", title = "\u{1F3AF} Exam target" },
11
+ }
12
+
13
+ local function marker_of(block)
14
+ if block.t ~= "Para" and block.t ~= "Plain" then return nil end
15
+ local text = pandoc.utils.stringify(block)
16
+ -- the legend line names all three markers: it is not a callout
17
+ local found = 0
18
+ for _, m in ipairs(MARKERS) do
19
+ if text:find(m.prefix, 1, true) then found = found + 1 end
20
+ end
21
+ if found > 1 then return nil end
22
+ for _, m in ipairs(MARKERS) do
23
+ if text:sub(1, #m.prefix) == m.prefix then return m end
24
+ end
25
+ return nil
26
+ end
27
+
28
+ -- drop the leading marker (and its variation selector and space) from a block's inlines
29
+ local function strip_marker(block)
30
+ local inl = block.content
31
+ while #inl > 0 do
32
+ local first = inl[1]
33
+ if first.t == "Space" then
34
+ table.remove(inl, 1)
35
+ elseif first.t == "Str" then
36
+ local s = first.text
37
+ -- whole UTF-8 sequences: a Lua character class would cut an emoji byte by byte
38
+ local rest = s
39
+ for _, m in ipairs(MARKERS) do
40
+ if rest:sub(1, #m.prefix) == m.prefix then rest = rest:sub(#m.prefix + 1) end
41
+ end
42
+ if rest:sub(1, 3) == "\u{FE0F}" then rest = rest:sub(4) end
43
+ if rest == s then break end
44
+ if rest == "" then table.remove(inl, 1) else first.text = rest; break end
45
+ else
46
+ break
47
+ end
48
+ end
49
+ return pandoc.Para(inl)
50
+ end
51
+
52
+ local function box(m, blocks)
53
+ local content = { pandoc.Para({ pandoc.Strong({ pandoc.Str(m.title) }) }) }
54
+ for _, b in ipairs(blocks) do table.insert(content, b) end
55
+ return pandoc.Div(content, pandoc.Attr("", { "callout", m.kind }))
56
+ end
57
+
58
+ -- walk a block list: group consecutive marker paragraphs, and lift marker items out of lists
59
+ local function rewrite(blocks)
60
+ local out, run, run_m = {}, {}, nil
61
+ local function flush()
62
+ if run_m then table.insert(out, box(run_m, run)) end
63
+ run, run_m = {}, nil
64
+ end
65
+ local function add_marked(m, item_blocks)
66
+ if run_m ~= m then flush(); run_m = m end
67
+ item_blocks[1] = strip_marker(item_blocks[1])
68
+ for _, b in ipairs(item_blocks) do table.insert(run, b) end
69
+ end
70
+ for _, b in ipairs(blocks) do
71
+ local m = marker_of(b)
72
+ if m then
73
+ add_marked(m, { b })
74
+ elseif b.t == "BulletList" then
75
+ local plain = {}
76
+ for _, item in ipairs(b.content) do
77
+ local im = item[1] and marker_of(item[1])
78
+ if im then
79
+ if #plain > 0 then flush(); table.insert(out, pandoc.BulletList(plain)); plain = {} end
80
+ add_marked(im, { table.unpack(item) })
81
+ else
82
+ flush()
83
+ table.insert(plain, item)
84
+ end
85
+ end
86
+ flush()
87
+ if #plain > 0 then table.insert(out, pandoc.BulletList(plain)) end
88
+ else
89
+ flush()
90
+ table.insert(out, b)
91
+ end
92
+ end
93
+ flush()
94
+ return out
95
+ end
96
+
97
+ function Pandoc(doc)
98
+ doc.blocks = rewrite(doc.blocks)
99
+ return doc
100
+ end
@@ -0,0 +1,28 @@
1
+ -- Nothing in a note runs or loads when it prints (D-81). A note body is model-written, and the
2
+ -- page is opened by Chrome to print it: a <script> must never run, and no file or URL may be
3
+ -- pulled in - pandoc's --embed-resources would read a local path a markdown image names, or
4
+ -- fetch a remote one. So raw HTML becomes text (pandoc's GFM reader ignores `-raw_html`), and
5
+ -- an image becomes `[image: its alt text]`. A link keeps its address only when it opens a web
6
+ -- page, an email or a place in the note: in a PDF, a click on `file://host/share` sends the
7
+ -- Windows login, and `javascript:` or `ms-msdt:` runs something.
8
+
9
+ function RawBlock(el)
10
+ if el.format:match("html") then return pandoc.Para({ pandoc.Str(el.text) }) end
11
+ end
12
+
13
+ function RawInline(el)
14
+ if el.format:match("html") then return pandoc.Str(el.text) end
15
+ end
16
+
17
+ local SAFE = { http = true, https = true, mailto = true }
18
+
19
+ function Link(el)
20
+ if el.target:sub(1, 1) == "#" then return nil end
21
+ local scheme = el.target:match("^(%a[%w+.-]*):")
22
+ if scheme and SAFE[scheme:lower()] then return nil end
23
+ return el.content
24
+ end
25
+
26
+ function Image(el)
27
+ return pandoc.Str("[image: " .. pandoc.utils.stringify(el.caption) .. "]")
28
+ end
@@ -0,0 +1,146 @@
1
+ /* The PDF look of a note (D-81): Arial, blue headings, blue table header rows, amber / blue /
2
+ orange callout boxes, plain gray code - the look of the older PDF summaries. Chrome prints the
3
+ page with this sheet; restyle a note by editing it. */
4
+
5
+ @page {
6
+ size: A4;
7
+ margin: 16mm 15mm;
8
+ }
9
+
10
+ /* pandoc's standalone page narrows and pads the body for screens - undone for print */
11
+ html,
12
+ body {
13
+ max-width: none;
14
+ margin: 0;
15
+ padding: 0;
16
+ background: #fff;
17
+ }
18
+
19
+ body {
20
+ font-family: Arial, Helvetica, sans-serif;
21
+ font-size: 10.5pt;
22
+ line-height: 1.4;
23
+ color: #1a1a1a;
24
+ hyphens: none;
25
+ }
26
+
27
+ h1 {
28
+ font-size: 20pt;
29
+ color: #1f4e79;
30
+ margin: 0 0 8pt;
31
+ }
32
+
33
+ h2 {
34
+ font-size: 14pt;
35
+ color: #2e74b5;
36
+ border-bottom: 1.5px solid #2e74b5;
37
+ padding-bottom: 2pt;
38
+ margin: 18pt 0 6pt;
39
+ }
40
+
41
+ h3 {
42
+ font-size: 12pt;
43
+ color: #1f4e79;
44
+ margin: 12pt 0 4pt;
45
+ }
46
+
47
+ h1,
48
+ h2,
49
+ h3 {
50
+ break-after: avoid;
51
+ }
52
+
53
+ p {
54
+ margin: 4pt 0;
55
+ }
56
+
57
+ ul,
58
+ ol {
59
+ margin: 4pt 0;
60
+ padding-left: 20pt;
61
+ }
62
+
63
+ li {
64
+ margin: 2pt 0;
65
+ }
66
+
67
+ code {
68
+ font-family: Consolas, "Courier New", monospace;
69
+ font-size: 9.5pt;
70
+ }
71
+
72
+ pre {
73
+ background: #f2f2f2;
74
+ border: 1px solid #d9d9d9;
75
+ padding: 6pt 8pt;
76
+ margin: 6pt 0;
77
+ white-space: pre-wrap;
78
+ overflow-wrap: anywhere;
79
+ break-inside: avoid;
80
+ }
81
+
82
+ pre code {
83
+ font-size: 9pt;
84
+ }
85
+
86
+ table {
87
+ border-collapse: collapse;
88
+ width: 100%;
89
+ margin: 6pt 0;
90
+ font-size: 9.5pt;
91
+ }
92
+
93
+ thead {
94
+ display: table-header-group;
95
+ }
96
+
97
+ th {
98
+ background: #2e75b6;
99
+ color: #fff;
100
+ text-align: left;
101
+ }
102
+
103
+ th,
104
+ td {
105
+ border: 1px solid #bfbfbf;
106
+ padding: 3pt 5pt;
107
+ vertical-align: top;
108
+ }
109
+
110
+ tbody tr:nth-child(even) {
111
+ background: #f5f8fc;
112
+ }
113
+
114
+ tr {
115
+ break-inside: avoid;
116
+ }
117
+
118
+ .callout {
119
+ border: 1px solid;
120
+ border-left-width: 4pt;
121
+ padding: 4pt 8pt;
122
+ margin: 6pt 0;
123
+ break-inside: avoid;
124
+ }
125
+
126
+ .callout p {
127
+ margin: 3pt 0;
128
+ }
129
+
130
+ .callout.warning {
131
+ background: #fff2cc;
132
+ border-color: #bf9000;
133
+ color: #5c4700;
134
+ }
135
+
136
+ .callout.tip {
137
+ background: #deebf7;
138
+ border-color: #2e75b6;
139
+ color: #1f3864;
140
+ }
141
+
142
+ .callout.target {
143
+ background: #fbe4d5;
144
+ border-color: #c55a11;
145
+ color: #843c0c;
146
+ }
studysystem/cli.py ADDED
@@ -0,0 +1,344 @@
1
+ """The `study` command: setup, migrate, downgrade, serve, dashboard, start, stop, demo. Only
2
+ migrate and downgrade alter an existing schema (D-22); serve and dashboard build a brand-new one
3
+ (D-324, D-335)."""
4
+
5
+ import datetime
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import click
10
+ from alembic.util import CommandError
11
+ from sqlalchemy import Engine
12
+ from sqlalchemy.exc import DatabaseError, OperationalError
13
+
14
+ from studysystem.db import migrate
15
+ from studysystem.db.engine import WalUnavailable, db_path, make_engine, snapshot, unavailable
16
+ from studysystem.errors import StudyError
17
+ from studysystem.services.users import ensure_user
18
+
19
+
20
+ def _line(e: StudyError) -> click.ClickException:
21
+ return click.ClickException(f"{e.code}: {e.message}. {e.fix}")
22
+
23
+
24
+ def _open(path: Path) -> tuple[Engine, str | None]:
25
+ """The engine and the revision it is at. Reading the revision is the first connection, where
26
+ a locked, unreadable or damaged file shows - so it is refused before any copy is taken."""
27
+ engine = make_engine(path)
28
+ try:
29
+ return engine, migrate.current_revision(engine)
30
+ except (DatabaseError, WalUnavailable) as e:
31
+ raise _line(unavailable(path, e)) from None
32
+
33
+
34
+ def _busy(e: OperationalError, path: Path) -> click.ClickException:
35
+ """Another program held the write lock past busy_timeout - with WAL a reader never waits,
36
+ but the run's write does. Any other database error is a real fault and stays a crash (D-36)."""
37
+ if "database is locked" not in str(e.orig):
38
+ raise e
39
+ return _line(
40
+ StudyError(
41
+ code="database_busy",
42
+ message=f"another program is writing to {path}",
43
+ fix="close it (the dashboard, a running server) or let it finish, then run the "
44
+ "command again",
45
+ )
46
+ )
47
+
48
+
49
+ @click.group()
50
+ def study() -> None:
51
+ """Plan and track a semester: migrate the database, serve MCP, or serve the dashboard."""
52
+
53
+
54
+ @study.command()
55
+ def setup() -> None:
56
+ """Set up this computer: the output folder, Claude, and the dashboard at sign-in. Run it once
57
+ after the install, in a terminal outside Claude (D-332)."""
58
+ from studysystem.services import setup as machine # imported here for the reason serve gives
59
+
60
+ problems = []
61
+ try:
62
+ # Everything that refuses the whole run comes before the first change (D-354, D-356).
63
+ machine.refuse_custom_data_dir()
64
+ machine.refuse_private_view()
65
+ new = machine.entry()
66
+ config = _choose_config(machine.config_files())
67
+ old = None
68
+ if config is not None:
69
+ try:
70
+ old = machine.current_entry(config)
71
+ except StudyError as e:
72
+ if e.code == "setup_custom_data_dir":
73
+ raise
74
+ problems.append(e)
75
+ config = None
76
+ except StudyError as e:
77
+ raise _line(e) from None
78
+
79
+ _ask_output_folder()
80
+ for step in (lambda: _connect_claude(config, old, problems), _ask_sign_in):
81
+ try:
82
+ step()
83
+ except StudyError as e:
84
+ problems.append(e)
85
+
86
+ click.echo("\nFor another host (Claude Code, Gemini CLI), paste this entry:")
87
+ click.echo(json.dumps({"mcpServers": {machine.SERVER: new}}, indent=2))
88
+ click.echo("\nFor Codex, run this line instead:")
89
+ click.echo(machine.codex_command())
90
+ if problems:
91
+ raise click.ClickException("; ".join(_line(e).message for e in problems))
92
+ click.echo("\nSetup is done.")
93
+
94
+
95
+ def _choose_config(found: list[Path]) -> Path | None:
96
+ """The Claude config to write: the only one, or the one the student picks (D-344)."""
97
+ if len(found) < 2:
98
+ return found[0] if found else None
99
+ click.echo("This computer has more than one Claude config. The first was used last:")
100
+ for n, path in enumerate(found, 1):
101
+ click.echo(f" {n}. {path}")
102
+ picked = click.prompt("Which one?", type=click.IntRange(1, len(found)), default=1)
103
+ return found[picked - 1]
104
+
105
+
106
+ def _ask_output_folder() -> None:
107
+ """Ask for the output folder, once; a different one later changes only on a clear yes (D-350,
108
+ D-351)."""
109
+ from studysystem.services import settings
110
+ from studysystem.services import setup as machine
111
+
112
+ saved = settings.saved_output_dir()
113
+ variable = settings.variable_output_dir()
114
+ click.echo("The study system writes your notes and summaries in one folder, for all courses.")
115
+ suggested = saved or variable
116
+ while True:
117
+ answer = click.prompt(
118
+ "Full path of that folder", default=str(suggested) if suggested else None
119
+ )
120
+ try:
121
+ folder = machine.output_folder(answer)
122
+ break
123
+ except StudyError as e:
124
+ click.echo(f"{e.message}. {e.fix}.")
125
+
126
+ if saved is not None and machine.same_folder(folder, saved) and variable is not None:
127
+ try:
128
+ folder = machine.output_folder(str(variable))
129
+ click.echo(f"{settings.VAULT_ENV} is set on this computer.")
130
+ except StudyError:
131
+ pass # the variable names no folder: nothing to change to
132
+ if saved is not None and not machine.same_folder(folder, saved):
133
+ click.echo(f"The saved folder is {saved}\nThe other folder is {folder}")
134
+ click.echo(
135
+ "If you change it, files already written stay in the saved folder. Move them yourself "
136
+ "if you want them in the other one."
137
+ )
138
+ picked = click.prompt(
139
+ "Change to the other folder, or was it a mistake?",
140
+ type=click.Choice(["change", "mistake"]),
141
+ )
142
+ if picked == "mistake":
143
+ click.echo(f"Kept: {saved}")
144
+ return
145
+ settings.save_output_dir(folder)
146
+ click.echo(f"Saved: {folder}")
147
+
148
+
149
+ def _connect_claude(config: Path | None, old: dict | None, problems: list[StudyError]) -> None:
150
+ """Put the server entry in Claude's config: the student agrees to replace a different one
151
+ (D-349), and says that Claude is closed (D-345)."""
152
+ from studysystem.services import setup as machine
153
+
154
+ if config is None:
155
+ if not problems: # none found, rather than one that could not be read
156
+ click.echo(
157
+ "\nNo Claude config was found. Install Claude, start it once, quit it, then run "
158
+ "`study setup` again."
159
+ )
160
+ return
161
+ new = machine.wanted_entry(old)
162
+ if old == new:
163
+ click.echo(f"\nClaude is already connected: {config}")
164
+ return
165
+ if old is not None:
166
+ click.echo(f"\nClaude already starts a study system, from {config}:")
167
+ click.echo(json.dumps(old, indent=2))
168
+ click.echo("Setup would replace it with the installed one:")
169
+ click.echo(json.dumps(new, indent=2))
170
+ click.echo(
171
+ "Yes: Claude starts the installed study system from now on. No: Claude keeps the one "
172
+ "it starts today. Your courses, hours and notes stay the same either way, and a copy "
173
+ "of the config is kept."
174
+ )
175
+ if not click.confirm("Replace it?", default=None):
176
+ click.echo("Kept. Claude's config was not changed.")
177
+ return
178
+ else:
179
+ click.echo(f"\nSetup adds the study system to Claude's config: {config}")
180
+ click.echo(f"\n{machine.how_to_quit()}")
181
+ if not click.confirm("Is Claude closed now?", default=None):
182
+ click.echo("Claude's config was not changed. Quit Claude, then run `study setup` again.")
183
+ return
184
+ copy = machine.write_entry(config, new)
185
+ click.echo(f"Claude is connected: {config}\nA copy of the old config: {copy}")
186
+
187
+
188
+ def _ask_sign_in() -> None:
189
+ """Ask about the dashboard's start at sign-in; a no changes nothing (D-289, D-353)."""
190
+ from studysystem.services import launcher
191
+
192
+ enabled = launcher.autostart_enabled()
193
+ if enabled is None:
194
+ click.echo(
195
+ "\nThe dashboard cannot start at sign-in on this system. `study start` starts it."
196
+ )
197
+ return
198
+ click.echo()
199
+ if click.confirm(launcher.ASK, default=None):
200
+ launcher.set_autostart(True)
201
+ sent = launcher.start_dashboard()
202
+ click.echo(f"The dashboard starts at every sign-in. It runs now: {sent['url']}")
203
+ click.echo(launcher.invitation())
204
+ return
205
+ launcher.keep_answer()
206
+ if enabled:
207
+ click.echo("It was on already and stays on. Your computer's startup settings turn it off.")
208
+ click.echo("Start the dashboard whenever you want it: `study start`.")
209
+
210
+
211
+ @study.command("migrate")
212
+ def migrate_cmd() -> None:
213
+ """Snapshot the database, then upgrade its schema to head."""
214
+ path = db_path()
215
+ engine, before = _open(path)
216
+ now = datetime.datetime.now().astimezone()
217
+ # One copy per run, not per day: each migrate is a restore point worth keeping.
218
+ target = snapshot(engine, now.date(), f"-premigrate-{now:%H%M%S}", unique=True)
219
+
220
+ try:
221
+ migrate.upgrade(engine)
222
+ except CommandError as e: # e.g. a database a newer build migrated: a revision unknown here
223
+ raise click.ClickException(f"{e}; nothing was changed") from None
224
+ except OperationalError as e:
225
+ raise _busy(e, path) from None
226
+ # Printed before the user step: if that one waits out the lock, the landed upgrade and its
227
+ # copy are already on screen.
228
+ click.echo(f"snapshot: {target}")
229
+ click.echo(f"{before} -> {migrate.current_revision(engine)}")
230
+
231
+ try:
232
+ user_id = ensure_user(engine) # a no-op after the first run (D-31)
233
+ except OperationalError as e:
234
+ raise _busy(e, path) from None
235
+ click.echo(f"user: {user_id}")
236
+
237
+
238
+ @study.command()
239
+ @click.argument("target")
240
+ def downgrade(target: str) -> None:
241
+ """Move the schema back to TARGET (a revision id, or `base` for empty). Development only:
242
+ it drops tables and columns, so it snapshots first, as migrate does (D-23)."""
243
+ path = db_path()
244
+ if not path.exists(): # opening it would leave an empty file behind
245
+ raise click.ClickException(f"no database at {path}; nothing to downgrade")
246
+ engine, before = _open(path)
247
+ now = datetime.datetime.now().astimezone()
248
+ snap = snapshot(engine, now.date(), f"-predowngrade-{now:%H%M%S}", unique=True)
249
+
250
+ try:
251
+ migrate.downgrade(engine, target)
252
+ except CommandError as e: # a TARGET alembic cannot reach, most often a typo
253
+ # The run is one transaction (env.py), so the database is unchanged and the copy only
254
+ # duplicates it: drop it.
255
+ # Asking alembic first would mean re-implementing its target syntax (`head-1`, `0005+1`).
256
+ if snap is not None:
257
+ snap.unlink()
258
+ raise click.ClickException(f"{e}; nothing was changed") from None
259
+ except OperationalError as e:
260
+ refusal = _busy(e, path) # any other database error re-raises here, keeping the copy
261
+ if snap is not None:
262
+ snap.unlink() # waited out at BEGIN IMMEDIATE: unchanged, as for a refused target
263
+ raise refusal from None
264
+ click.echo(f"snapshot: {snap}")
265
+ click.echo(f"{before} -> {migrate.current_revision(engine)}")
266
+
267
+
268
+ @study.command()
269
+ def serve() -> None:
270
+ """Start the MCP server on stdio."""
271
+ # Imported here: the server pulls in the SDK and every tool module, and a broken import there
272
+ # must not also break `study migrate` - the command that recovers from it.
273
+ from studysystem.server import main
274
+
275
+ main()
276
+
277
+
278
+ @study.command()
279
+ @click.option("--port", default=8765, show_default=True, help="The port on 127.0.0.1.")
280
+ def dashboard(port: int) -> None:
281
+ """Serve the dashboard's HTTP route on 127.0.0.1, beside the MCP server."""
282
+ from studysystem.dashboard import main # imported here for the reason serve gives
283
+
284
+ try:
285
+ main(port)
286
+ except StudyError as e:
287
+ raise _line(e) from None
288
+
289
+
290
+ @study.command()
291
+ @click.option("--port", default=8765, show_default=True, help="The port on 127.0.0.1.")
292
+ def start(port: int) -> None:
293
+ """Start the dashboard in the background, with no window. After an upgrade (D-342)."""
294
+ from studysystem.services import launcher # imported here for the reason serve gives
295
+
296
+ try:
297
+ sent = launcher.start_dashboard(port)
298
+ except StudyError as e:
299
+ raise _line(e) from None
300
+ click.echo(f"dashboard {'started' if sent['started'] else 'already running'}: {sent['url']}")
301
+ click.echo(launcher.invitation(port))
302
+
303
+
304
+ @study.command()
305
+ @click.option("--port", default=8765, show_default=True, help="The port on 127.0.0.1.")
306
+ def stop(port: int) -> None:
307
+ """Stop the dashboard that runs in the background. Before an upgrade (D-342)."""
308
+ from studysystem.services import launcher # imported here for the reason serve gives
309
+
310
+ try:
311
+ sent = launcher.stop_dashboard(port)
312
+ except StudyError as e:
313
+ raise _line(e) from None
314
+ click.echo("dashboard stopped" if sent["stopped"] else "no dashboard was running")
315
+
316
+
317
+ @study.command()
318
+ @click.option("--port", default=8766, show_default=True, help="The port on 127.0.0.1.")
319
+ def demo(port: int) -> None:
320
+ """Build a demo database of invented data in its own folder, then serve the dashboard on it.
321
+ It never opens your own database (D-305)."""
322
+ # Imported here, as `dashboard` does: the seed pulls in every service.
323
+ from studysystem import demo as seeded
324
+ from studysystem.dashboard import main
325
+
326
+ folder = seeded.demo_dir()
327
+ click.echo(f"building the demo database in {folder} ...")
328
+ try:
329
+ _, summary, path = seeded.build(folder)
330
+ except StudyError as e:
331
+ raise _line(e) from None
332
+ click.echo(f"database: {path}")
333
+ click.echo(
334
+ f"{summary['courses']} courses, {summary['papers']} past papers, "
335
+ f"{summary['materials']} chapters and slides, {summary['meetings']} class meetings, "
336
+ f"{summary['hours']} hours entries ({summary['minutes']} min), {summary['plans']} plans"
337
+ )
338
+ click.echo(f"dashboard: http://127.0.0.1:{port} (invented data; Ctrl+C to stop)")
339
+ main(port, locked=False)
340
+
341
+
342
+ # `python -m studysystem.cli dashboard`: how study_dashboard starts it (D-289).
343
+ if __name__ == "__main__":
344
+ study()