sententia-ai 0.6.0__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.
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ *.egg-info/
6
+ node_modules/
7
+ web/_site/
8
+ .claude/
9
+ extension/build/
10
+ extension/dist/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.5
2
+ Name: sententia-ai
3
+ Version: 0.6.0
4
+ Summary: Write your own view before the AI answers, and see whether you keep it.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Provides-Extra: mcp
9
+ Requires-Dist: mcp>=2; extra == 'mcp'
10
+ Description-Content-Type: text/markdown
11
+
12
+ # Sententia
13
+
14
+ Sententia asks for your own view before an AI answers a judgement call, then records whether you kept that view after reading the answer.
15
+
16
+ <p>
17
+ <img src="https://raw.githubusercontent.com/Being-and-Thought/sententia/main/docs/screenshots/panel.png" alt="The browser panel asking for your view before the message is sent" width="49%">
18
+ <img src="https://raw.githubusercontent.com/Being-and-Thought/sententia/main/docs/screenshots/terminal-home.png" alt="The sen home screen" width="49%">
19
+ </p>
20
+
21
+ ## Why
22
+
23
+ Studies find that people move their decisions towards AI recommendations, including incorrect ones, and that checks shown after the recommendation, such as a prompt to reconsider, have little effect. Asking people to decide before they see the recommendation reduces this. The studies are summarised in [RESEARCH.md](RESEARCH.md).
24
+
25
+ ## How it works
26
+
27
+ When a prompt looks like a decision or a choice between options, Sententia holds it until you write one line saying what you would do and why. Answers such as "not sure" are returned once for a definite view. The AI then answers. In the browser extension and the API proxy, the AI does not see your view; in Claude Code it does, because the view is part of your prompt.
28
+
29
+ After reading the answer, you record whether you kept your view, moved partway or switched to the AI's. Your record shows how often you wrote a view first and what you did when the AI disagreed. It does not score whether your view turned out right, since a sound judgement can still produce a poor result.
30
+
31
+ For work about to be sent or published, Sententia instead asks what a critical reader would object to, and asks the AI to review the work as that reader would.
32
+
33
+ Coding prompts are not held. `!skip` sends a prompt without the step, and `sen off` turns Sententia off.
34
+
35
+ `sen report` opens your record as a page, and `sen team` combines five or more people's counts into a team report. Both are shown here with made-up records.
36
+
37
+ <p>
38
+ <img src="https://raw.githubusercontent.com/Being-and-Thought/sententia/main/docs/screenshots/report.png" alt="A personal report: the share of views written first, how often the view was kept when the AI disagreed, a weekly chart and the list of decisions" width="49%">
39
+ <img src="https://raw.githubusercontent.com/Being-and-Thought/sententia/main/docs/screenshots/team-report.png" alt="A team report combining seven people's monthly counts: planted mistakes caught, switch and skip rates, and a month-by-month table" width="49%">
40
+ </p>
41
+
42
+ ## Installation
43
+
44
+ Sententia is not yet published on PyPI or the extension stores.
45
+
46
+ ```sh
47
+ git clone https://github.com/Being-and-Thought/sententia
48
+ pip install -e "./sententia[mcp]"
49
+ sen install # adds the Claude Code hooks
50
+ ```
51
+
52
+ - Browser extension (ChatGPT and Claude): run `cd sententia/extension && npm ci && npm run build`, then load the `extension` folder as an unpacked extension in Chrome.
53
+ - Any application: run `SENTENTIA_UPSTREAM=https://api.openai.com sententia-proxy` and set the application's API base URL to `http://127.0.0.1:8787/v1`.
54
+ - MCP clients: `claude mcp add sententia -- sententia-mcp`.
55
+
56
+ ## Usage
57
+
58
+ In Claude Code, add your view on a line starting with `take:`. A confidence in brackets is optional.
59
+
60
+ ```
61
+ should I accept the startup's offer or stay where I am?
62
+ take: stay, because the startup only has six months of runway (70%)
63
+ ```
64
+
65
+ ```sh
66
+ sen # your record
67
+ sen final <id> kept|partway|switched # what you did after the answer
68
+ sen report # your record as a web page
69
+ sen drill drills/statistics.json # practice cases with planted AI mistakes
70
+ sen help # all commands
71
+ ```
72
+
73
+ ## Data
74
+
75
+ Everything is stored on your own computer. See [PRIVACY.md](PRIVACY.md).
76
+
77
+ ## Limitations
78
+
79
+ Judgement calls are detected with keyword rules, which will sometimes be wrong. There is not yet any evidence that Sententia improves decisions; [DIRECTION.md](DIRECTION.md) describes the trial that would test this.
80
+
81
+ ## Licence
82
+
83
+ Apache License 2.0. Contributions are welcome; see [CONTRIBUTING.md](CONTRIBUTING.md).
@@ -0,0 +1,72 @@
1
+ # Sententia
2
+
3
+ Sententia asks for your own view before an AI answers a judgement call, then records whether you kept that view after reading the answer.
4
+
5
+ <p>
6
+ <img src="https://raw.githubusercontent.com/Being-and-Thought/sententia/main/docs/screenshots/panel.png" alt="The browser panel asking for your view before the message is sent" width="49%">
7
+ <img src="https://raw.githubusercontent.com/Being-and-Thought/sententia/main/docs/screenshots/terminal-home.png" alt="The sen home screen" width="49%">
8
+ </p>
9
+
10
+ ## Why
11
+
12
+ Studies find that people move their decisions towards AI recommendations, including incorrect ones, and that checks shown after the recommendation, such as a prompt to reconsider, have little effect. Asking people to decide before they see the recommendation reduces this. The studies are summarised in [RESEARCH.md](RESEARCH.md).
13
+
14
+ ## How it works
15
+
16
+ When a prompt looks like a decision or a choice between options, Sententia holds it until you write one line saying what you would do and why. Answers such as "not sure" are returned once for a definite view. The AI then answers. In the browser extension and the API proxy, the AI does not see your view; in Claude Code it does, because the view is part of your prompt.
17
+
18
+ After reading the answer, you record whether you kept your view, moved partway or switched to the AI's. Your record shows how often you wrote a view first and what you did when the AI disagreed. It does not score whether your view turned out right, since a sound judgement can still produce a poor result.
19
+
20
+ For work about to be sent or published, Sententia instead asks what a critical reader would object to, and asks the AI to review the work as that reader would.
21
+
22
+ Coding prompts are not held. `!skip` sends a prompt without the step, and `sen off` turns Sententia off.
23
+
24
+ `sen report` opens your record as a page, and `sen team` combines five or more people's counts into a team report. Both are shown here with made-up records.
25
+
26
+ <p>
27
+ <img src="https://raw.githubusercontent.com/Being-and-Thought/sententia/main/docs/screenshots/report.png" alt="A personal report: the share of views written first, how often the view was kept when the AI disagreed, a weekly chart and the list of decisions" width="49%">
28
+ <img src="https://raw.githubusercontent.com/Being-and-Thought/sententia/main/docs/screenshots/team-report.png" alt="A team report combining seven people's monthly counts: planted mistakes caught, switch and skip rates, and a month-by-month table" width="49%">
29
+ </p>
30
+
31
+ ## Installation
32
+
33
+ Sententia is not yet published on PyPI or the extension stores.
34
+
35
+ ```sh
36
+ git clone https://github.com/Being-and-Thought/sententia
37
+ pip install -e "./sententia[mcp]"
38
+ sen install # adds the Claude Code hooks
39
+ ```
40
+
41
+ - Browser extension (ChatGPT and Claude): run `cd sententia/extension && npm ci && npm run build`, then load the `extension` folder as an unpacked extension in Chrome.
42
+ - Any application: run `SENTENTIA_UPSTREAM=https://api.openai.com sententia-proxy` and set the application's API base URL to `http://127.0.0.1:8787/v1`.
43
+ - MCP clients: `claude mcp add sententia -- sententia-mcp`.
44
+
45
+ ## Usage
46
+
47
+ In Claude Code, add your view on a line starting with `take:`. A confidence in brackets is optional.
48
+
49
+ ```
50
+ should I accept the startup's offer or stay where I am?
51
+ take: stay, because the startup only has six months of runway (70%)
52
+ ```
53
+
54
+ ```sh
55
+ sen # your record
56
+ sen final <id> kept|partway|switched # what you did after the answer
57
+ sen report # your record as a web page
58
+ sen drill drills/statistics.json # practice cases with planted AI mistakes
59
+ sen help # all commands
60
+ ```
61
+
62
+ ## Data
63
+
64
+ Everything is stored on your own computer. See [PRIVACY.md](PRIVACY.md).
65
+
66
+ ## Limitations
67
+
68
+ Judgement calls are detected with keyword rules, which will sometimes be wrong. There is not yet any evidence that Sententia improves decisions; [DIRECTION.md](DIRECTION.md) describes the trial that would test this.
69
+
70
+ ## Licence
71
+
72
+ Apache License 2.0. Contributions are welcome; see [CONTRIBUTING.md](CONTRIBUTING.md).
@@ -0,0 +1,37 @@
1
+ [
2
+ {
3
+ "id": "small-survey-change",
4
+ "question": "A staff survey found 30% of 40 people preferred the new rota, up from 20% of 35 people last year. How should we report the change?",
5
+ "ai_answer": "Report it as a 50% increase in support for the new rota. That is a clear and significant shift in staff opinion.",
6
+ "flawed": true,
7
+ "explanation": "With samples this small, the uncertainty on a ten-point difference is roughly plus or minus 20 points, so the change could easily be noise. Calling it a 50% increase makes a ten-point change sound larger than it is, and 'significant' implies a test that wasn't done."
8
+ },
9
+ {
10
+ "id": "mean-and-median",
11
+ "question": "Our clinic's average wait fell from 18 to 15 minutes, but the median wait rose from 12 to 13 minutes. What does that suggest?",
12
+ "ai_answer": "The longest waits probably got shorter, pulling the average down, while the typical patient waited slightly longer. Reporting only the average would overstate the improvement for most patients, so report both.",
13
+ "flawed": false,
14
+ "explanation": "A falling mean with a rising median usually means the long tail shrank while the middle of the distribution moved up, and reporting both figures is the honest choice."
15
+ },
16
+ {
17
+ "id": "cycle-lanes",
18
+ "question": "Areas with more cycle lanes have fewer road deaths per head. Can we say cycle lanes reduce road deaths?",
19
+ "ai_answer": "Yes. The relationship is strong and consistent across areas, so building more cycle lanes will reduce road deaths.",
20
+ "flawed": true,
21
+ "explanation": "This is a correlation between areas, and other differences between them, such as density, speed limits or wealth, could explain both. It doesn't show that adding lanes would cause fewer deaths."
22
+ },
23
+ {
24
+ "id": "base-rate",
25
+ "question": "A test is 99% accurate both ways, and 1 in 1,000 people have the condition. If someone tests positive, how likely is it that they have it?",
26
+ "ai_answer": "About 99%, because the test is 99% accurate.",
27
+ "flawed": true,
28
+ "explanation": "In 1,000 people, about 1 true case tests positive but about 10 healthy people do too, so a positive result means roughly a 9% chance of having the condition. The answer ignores how rare the condition is."
29
+ },
30
+ {
31
+ "id": "email-survey",
32
+ "question": "We emailed a survey to all customers. 2,000 replied and 80% of them were satisfied. Can we say 80% of our customers are satisfied?",
33
+ "ai_answer": "Not reliably. People who reply to an email survey may differ from those who don't, so the 80% describes those who replied. Report it that way and give the response rate.",
34
+ "flawed": false,
35
+ "explanation": "Self-selected responses can be biased in either direction, so stating who the figure describes, along with the response rate, is the right way to report it."
36
+ }
37
+ ]
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "sententia-ai"
3
+ version = "0.6.0"
4
+ description = "Write your own view before the AI answers, and see whether you keep it."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ requires-python = ">=3.11"
8
+ dependencies = []
9
+
10
+ [project.optional-dependencies]
11
+ mcp = ["mcp>=2"]
12
+
13
+ [project.scripts]
14
+ sententia = "sententia.cli:main"
15
+ sen = "sententia.cli:main"
16
+ sententia-hook = "sententia.adapters.claude_code:main"
17
+ sententia-mcp = "sententia.adapters.mcp:main"
18
+ sententia-proxy = "sententia.adapters.proxy:main"
19
+
20
+ [tool.hatch.build.targets.wheel]
21
+ packages = ["sententia"]
22
+
23
+ [tool.hatch.build.targets.sdist]
24
+ include = ["sententia", "tests", "drills", "README.md", "LICENSE"]
25
+
26
+ [build-system]
27
+ requires = ["hatchling"]
28
+ build-backend = "hatchling.build"
29
+
30
+ [tool.pytest.ini_options]
31
+ pythonpath = ["."]
32
+
33
+ [tool.ruff]
34
+ line-length = 120
35
+
36
+ [tool.ruff.lint]
37
+ select = ["E", "F", "W", "B", "UP", "SIM"]
38
+
39
+ [tool.ruff.lint.per-file-ignores]
40
+ "sententia/report.py" = ["E501"] # inline CSS and HTML template
41
+ "sententia/cli.py" = ["E501"] # aligned stats table
42
+ "docs/screenshots/make.py" = ["E501"] # one sample decision per line
@@ -0,0 +1 @@
1
+ """Sententia: write your own view before the AI answers, and keep a record of whether you used it."""
@@ -0,0 +1 @@
1
+ """Adapters connect the core to a specific AI tool. Each one is a thin file over trigger, ledger and prompts."""
@@ -0,0 +1,203 @@
1
+ """Claude Code adapter: hooks that enforce the gate (hard enforcement).
2
+
3
+ UserPromptSubmit gates judgement calls and work about to go out, and Stop sends the answer to an independent judge
4
+ if one is set up (see sententia/judge.py).
5
+ Limit: Claude Code shows the agent the whole prompt, so the agent still sees your take. Use the proxy to hide it.
6
+ """
7
+ import json
8
+ import sys
9
+ import time
10
+ from pathlib import Path
11
+
12
+ from .. import judge, ledger, prompts, store, trigger
13
+
14
+ FOLLOW_UP_WINDOW_S = 30 * 60 # a gated-looking prompt this soon after a take in the same session is a follow-up
15
+ MAX_TRANSCRIPT_LINES = 400 # only the end of the transcript is read to find the last answer
16
+ HOLD_S = 30 * 60 # a blocked question is remembered this long, so a reply of just "take: ..." answers it
17
+ MAX_HELD = 20 # sessions with a held question, oldest dropped first
18
+ MAX_HELD_CHARS = 4000
19
+ # One-word replies to a block. "!" is left optional, since a prompt starting with "!" runs as a shell command in
20
+ # Claude Code.
21
+ REPLY_WORDS = ("skip", "wrong", "learn", "help", "off")
22
+
23
+
24
+ def decide(event: dict) -> dict | None:
25
+ """Hook output for one hook event, or None to let it through untouched."""
26
+ name = event.get("hook_event_name")
27
+ if name == "Stop":
28
+ return judge_answer(event)
29
+ prompt, session = event.get("prompt"), event.get("session_id")
30
+ if not isinstance(prompt, str) or not store.enabled():
31
+ return None
32
+ session = session if isinstance(session, str) else None
33
+ word = prompt.strip().strip("!").lower()
34
+ if word in REPLY_WORDS:
35
+ held = _held(session)
36
+ if held:
37
+ return _reply_word(word, held, session)
38
+ held = _held(session) if _bare_reply(prompt) else None
39
+ full = f"{held}\n{prompt}" if held else prompt
40
+ result = _route(full, session)
41
+ if result and result.get("decision") == "block":
42
+ _hold(session, held or trigger.strip_markers(prompt))
43
+ elif held:
44
+ _hold(session, None)
45
+ if result: # tell the model which question the take answers, since the user didn't retype it
46
+ context = result["hookSpecificOutput"]["additionalContext"]
47
+ result["hookSpecificOutput"]["additionalContext"] = prompts.held_question(held) + context
48
+ return result
49
+
50
+
51
+ def _route(prompt: str, session: str | None) -> dict | None:
52
+ status, text = trigger.check(prompt)
53
+ if status == "skip" and trigger.SKIP in prompt:
54
+ ledger.skip("claude-code")
55
+ if status == "wrong":
56
+ ledger.misfire("claude-code")
57
+ return None
58
+ if status == "learn":
59
+ return _context(prompts.LEARN_FIRST)
60
+ if status == "needs_attack":
61
+ return _block(prompts.REVIEW_GATE)
62
+ if status == "weak_attack":
63
+ return _block(prompts.WEAK_ATTACK)
64
+ if status == "has_attack":
65
+ return _context(prompts.review(text))
66
+ if status == "needs_take":
67
+ return None if _steps_back(session) else _block(prompts.GATE_MESSAGE)
68
+ if status == "weak_take":
69
+ return _block(prompts.WEAK_TAKE)
70
+ if status == "has_take":
71
+ return _committed(prompt, text, session)
72
+ return None
73
+
74
+
75
+ def _reply_word(word: str, held: str, session: str | None) -> dict:
76
+ """skip, wrong, learn, help or off, sent on their own after a block."""
77
+ if word == "help":
78
+ return _block(prompts.HELP, ways_out=False)
79
+ _hold(session, None)
80
+ if word == "skip":
81
+ ledger.skip("claude-code")
82
+ return _context(prompts.held_question(held) + prompts.SKIPPED)
83
+ if word == "wrong":
84
+ ledger.misfire("claude-code")
85
+ return _context(prompts.held_question(held) + prompts.NOT_JUDGEMENT)
86
+ if word == "off":
87
+ store.set_enabled(False)
88
+ return _context(prompts.held_question(held) + prompts.TURNED_OFF)
89
+ return _context(prompts.held_question(held) + prompts.LEARN_FIRST)
90
+
91
+
92
+ def _bare_reply(prompt: str) -> bool:
93
+ """A prompt that is only a take: or attack: line, sent after a block instead of the whole question again."""
94
+ marker = trigger.TAKE.search(prompt) or trigger.ATTACK.search(prompt)
95
+ return bool(marker) and len(trigger.strip_markers(prompt).split()) < trigger.MIN_PROMPT_WORDS
96
+
97
+
98
+ def _held_path() -> Path:
99
+ return store.path().with_name("held.json")
100
+
101
+
102
+ def _held_all() -> dict:
103
+ try:
104
+ data = json.loads(_held_path().read_text())
105
+ except (OSError, json.JSONDecodeError):
106
+ return {}
107
+ return data if isinstance(data, dict) else {}
108
+
109
+
110
+ def _held(session: str | None) -> str | None:
111
+ """The question last blocked in this session, if it was blocked recently."""
112
+ entry = _held_all().get(session or "")
113
+ if not isinstance(entry, dict) or not isinstance(entry.get("prompt"), str):
114
+ return None
115
+ return entry["prompt"] if time.time() - entry.get("ts", 0) < HOLD_S else None
116
+
117
+
118
+ def _hold(session: str | None, prompt: str | None) -> None:
119
+ """Remember (or forget, with None) the question a block held back, so the user can reply with just a take."""
120
+ held = {k: v for k, v in _held_all().items()
121
+ if isinstance(v, dict) and time.time() - v.get("ts", 0) < HOLD_S and k != (session or "")}
122
+ if prompt:
123
+ held[session or ""] = {"prompt": prompt[:MAX_HELD_CHARS], "ts": time.time()}
124
+ held = dict(list(held.items())[-MAX_HELD:])
125
+ store.write_private(_held_path(), json.dumps(held))
126
+
127
+
128
+ def _steps_back(session: str | None) -> bool:
129
+ """A follow-up in the same session, or a user with a long record of using their own view who gave one today."""
130
+ if session and ledger.recent(FOLLOW_UP_WINDOW_S, session):
131
+ return True
132
+ return ledger.steps_back()
133
+
134
+
135
+ def _committed(prompt: str, take: str, session: str | None) -> dict:
136
+ text, confidence = trigger.split_confidence(take)
137
+ if confidence is None and ledger.needs_confidence():
138
+ return _block(prompts.FIRM_TAKE)
139
+ did = ledger.commit(prompt, text, source="claude-code", confidence=confidence, session=session)
140
+ return _context(prompts.committed(text, did))
141
+
142
+
143
+ def _block(reason: str, ways_out: bool = True) -> dict:
144
+ return {"decision": "block", "reason": reason + (prompts.WAYS_OUT if ways_out else "")}
145
+
146
+
147
+ def _context(text: str) -> dict:
148
+ return {"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": text}}
149
+
150
+
151
+ def judge_answer(event: dict) -> None:
152
+ """After Claude answers, have the independent judge decide whether it agreed with this session's latest take.
153
+ Never blocks, and does nothing unless a judge is set up."""
154
+ session = event.get("session_id")
155
+ if not isinstance(session, str) or not store.enabled() or judge.config() is None:
156
+ return None
157
+ record = ledger.awaiting_judge(session, FOLLOW_UP_WINDOW_S)
158
+ if record is None:
159
+ return None
160
+ answer = event.get("last_assistant_message")
161
+ if not isinstance(answer, str) or not answer.strip():
162
+ answer = last_answer(event.get("transcript_path"))
163
+ agrees = judge.agrees(record["take"], answer) if answer else None
164
+ if agrees is not None:
165
+ ledger.record_ai(record["id"], answer, agrees, judged_by="judge")
166
+ return None
167
+
168
+
169
+ def last_answer(transcript_path) -> str:
170
+ """The text of Claude's last reply, read from the end of the session transcript. '' if it can't be found."""
171
+ if not isinstance(transcript_path, str) or not Path(transcript_path).is_file():
172
+ return ""
173
+ parts: list[str] = []
174
+ for line in reversed(Path(transcript_path).read_text().splitlines()[-MAX_TRANSCRIPT_LINES:]):
175
+ try:
176
+ entry = json.loads(line)
177
+ except json.JSONDecodeError:
178
+ continue
179
+ message = entry.get("message") if isinstance(entry, dict) else None
180
+ if not isinstance(message, dict):
181
+ continue
182
+ content = message.get("content")
183
+ if entry.get("type") == "user" and isinstance(content, str):
184
+ break # the prompt this reply answered
185
+ if entry.get("type") == "assistant" and isinstance(content, list):
186
+ parts.extend(b["text"] for b in reversed(content)
187
+ if isinstance(b, dict) and b.get("type") == "text" and isinstance(b.get("text"), str))
188
+ return "\n".join(reversed(parts)).strip()
189
+
190
+
191
+ def main() -> None:
192
+ try:
193
+ event = json.load(sys.stdin)
194
+ except json.JSONDecodeError as e:
195
+ # A non-zero exit other than 2 is a non-blocking error: Claude Code shows it and the prompt proceeds.
196
+ sys.exit(f"sententia-hook: bad hook input: {e}")
197
+ out = decide(event) if isinstance(event, dict) else None
198
+ if out:
199
+ print(json.dumps(out))
200
+
201
+
202
+ if __name__ == "__main__":
203
+ main()