raynsis-shift 0.1.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,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,4 @@
1
+ raynsis-shift
2
+ Copyright 2026 RAYNSIS AI Workforce
3
+
4
+ This product includes software developed by RAYNSIS AI Workforce.
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: raynsis-shift
3
+ Version: 0.1.0
4
+ Summary: Timed work orders for Claude Code: 'keep working until 17:30' stays in force until 17:30.
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ License-File: NOTICE
10
+ Dynamic: license-file
11
+
12
+ # RAYNSIS Shift
13
+
14
+ **"Keep working until 17:30" should still be true at 16:00.**
15
+
16
+ You give Claude Code a timed order. It finishes one item, writes a tidy summary and stops. You type "continue".
17
+ Again. And again. In the setup this was extracted from, the owner gave 14 timed orders in 30 days and had to
18
+ re-issue every one of them by hand.
19
+
20
+ raynsis-shift keeps the order per session and turns back every attempt to end the turn until the deadline.
21
+
22
+ ```
23
+ pip install raynsis-shift
24
+ raynsis-shift install
25
+ ```
26
+
27
+ Then just say it:
28
+
29
+ - `keep working until 17:30`
30
+ - `don't stop for 3 hours`
31
+ - `carry on for another 45 minutes`
32
+
33
+ `raynsis-shift status` shows active orders. `raynsis-shift undo` removes the two hooks.
34
+
35
+ ## It cannot loop forever
36
+
37
+ The order is released when any of these is true:
38
+
39
+ | Condition | Why |
40
+ |---|---|
41
+ | The deadline passed | The order is over. |
42
+ | The answer contains `order-complete: <what was measured>` | Nothing in scope is left; the reason is logged. |
43
+ | Two blocks in a row with no tool call | The agent has nothing to do or is stuck; forcing it only burns tokens. |
44
+ | 40 blocks issued | Hard ceiling. |
45
+ | You type `stop`, `that's enough` or `cancel the order` | You are in charge. |
46
+ | `RAYNSIS_SHIFT=off` is set | Kill switch. |
47
+
48
+ Orders are capped at 9 hours. A prompt needs both a time and a work verb, so "the meeting runs until 5pm"
49
+ is not an order. If the transcript cannot be read, the gate does not block.
50
+
51
+ ## How it works
52
+
53
+ Two hooks, one file, standard library only.
54
+
55
+ - `UserPromptSubmit`: parses the order, stores the deadline in `~/.raynsis-shift/orders/<session>.json`,
56
+ and reminds the model of the time left on every prompt.
57
+ - `Stop`: while an order is active, returns `{"decision": "block", "reason": ...}` naming the deadline and
58
+ asking for the next item in scope.
59
+
60
+ Every decision is one line in `~/.raynsis-shift/log.jsonl`.
61
+
62
+ ## Limits
63
+
64
+ - English order phrases only in 0.1.
65
+ - Tested on macOS with Python 3.9.
66
+ - An order belongs to one session. Other sessions are not affected.
67
+
68
+ ## Tests
69
+
70
+ ```
71
+ python -m unittest discover tests
72
+ ```
@@ -0,0 +1,61 @@
1
+ # RAYNSIS Shift
2
+
3
+ **"Keep working until 17:30" should still be true at 16:00.**
4
+
5
+ You give Claude Code a timed order. It finishes one item, writes a tidy summary and stops. You type "continue".
6
+ Again. And again. In the setup this was extracted from, the owner gave 14 timed orders in 30 days and had to
7
+ re-issue every one of them by hand.
8
+
9
+ raynsis-shift keeps the order per session and turns back every attempt to end the turn until the deadline.
10
+
11
+ ```
12
+ pip install raynsis-shift
13
+ raynsis-shift install
14
+ ```
15
+
16
+ Then just say it:
17
+
18
+ - `keep working until 17:30`
19
+ - `don't stop for 3 hours`
20
+ - `carry on for another 45 minutes`
21
+
22
+ `raynsis-shift status` shows active orders. `raynsis-shift undo` removes the two hooks.
23
+
24
+ ## It cannot loop forever
25
+
26
+ The order is released when any of these is true:
27
+
28
+ | Condition | Why |
29
+ |---|---|
30
+ | The deadline passed | The order is over. |
31
+ | The answer contains `order-complete: <what was measured>` | Nothing in scope is left; the reason is logged. |
32
+ | Two blocks in a row with no tool call | The agent has nothing to do or is stuck; forcing it only burns tokens. |
33
+ | 40 blocks issued | Hard ceiling. |
34
+ | You type `stop`, `that's enough` or `cancel the order` | You are in charge. |
35
+ | `RAYNSIS_SHIFT=off` is set | Kill switch. |
36
+
37
+ Orders are capped at 9 hours. A prompt needs both a time and a work verb, so "the meeting runs until 5pm"
38
+ is not an order. If the transcript cannot be read, the gate does not block.
39
+
40
+ ## How it works
41
+
42
+ Two hooks, one file, standard library only.
43
+
44
+ - `UserPromptSubmit`: parses the order, stores the deadline in `~/.raynsis-shift/orders/<session>.json`,
45
+ and reminds the model of the time left on every prompt.
46
+ - `Stop`: while an order is active, returns `{"decision": "block", "reason": ...}` naming the deadline and
47
+ asking for the next item in scope.
48
+
49
+ Every decision is one line in `~/.raynsis-shift/log.jsonl`.
50
+
51
+ ## Limits
52
+
53
+ - English order phrases only in 0.1.
54
+ - Tested on macOS with Python 3.9.
55
+ - An order belongs to one session. Other sessions are not affected.
56
+
57
+ ## Tests
58
+
59
+ ```
60
+ python -m unittest discover tests
61
+ ```
@@ -0,0 +1,16 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "raynsis-shift"
7
+ version = "0.1.0"
8
+ description = "Timed work orders for Claude Code: 'keep working until 17:30' stays in force until 17:30."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE", "NOTICE"]
13
+ dependencies = []
14
+
15
+ [project.scripts]
16
+ raynsis-shift = "raynsis_shift.gate:main"
@@ -0,0 +1,2 @@
1
+ """raynsis-shift: "work until 17:30" becomes something Claude Code cannot quietly forget."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,275 @@
1
+ """Timed work orders for Claude Code.
2
+
3
+ You write "keep working until 17:30" or "don't stop for 3 hours". Without a gate the agent finishes one turn and
4
+ stops, and you type "continue" again and again. This module keeps the order per session and turns back every attempt
5
+ to end the turn until the deadline, with written release conditions so it can never loop forever.
6
+
7
+ Two hook modes (see `raynsis-shift install`):
8
+ prompt (UserPromptSubmit): reads a timed order from the prompt, stores the deadline, reminds the model each turn.
9
+ stop (Stop): while an order is active, blocks the end of the turn and asks for the next item of work.
10
+
11
+ The order is released when any of these is true:
12
+ - the deadline passed (or is under two minutes away)
13
+ - the last answer contains "order-complete: <measured reason>"
14
+ - two blocks in a row saw no tool call at all (nothing left to do, or stuck)
15
+ - MAX_BLOCKS blocks were issued
16
+ - the user says stop ("stop", "that's enough", "cancel the order"), or RAYNSIS_SHIFT=off is set
17
+
18
+ Standard library only. Every failure is silent and lets the turn end (fail open). Decisions are appended to
19
+ ~/.raynsis-shift/log.jsonl.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import re
26
+ import sys
27
+ import time
28
+ from pathlib import Path
29
+
30
+ MAX_HOURS = 9.0
31
+ MAX_BLOCKS = 40
32
+ MAX_PROMPT = 1500
33
+ RELEASE = "order-complete:"
34
+
35
+ _VERB = r"(?:keep\s+(?:going|working|at\s+it)|don'?t\s+stop|do\s+not\s+stop|work|continue|carry\s+on|stay\s+on\s+it|run|go)"
36
+ _GAP = r"(?:\W+\w+){0,6}?\W+"
37
+ CLOCK = re.compile(r"(?:until|till|til)\s+(\d{1,2})(?:[:.](\d{2}))?\s*(am|pm)?\b", re.I)
38
+ HOURS = re.compile(r"(?:for|another)\s+(?:the\s+next\s+)?(\d+(?:\.\d+)?)\s*(?:more\s+)?(?:h|hr|hrs|hours?)\b", re.I)
39
+ MINUTES = re.compile(r"(?:for|another)\s+(?:the\s+next\s+)?(\d+)\s*(?:more\s+)?(?:m|min|mins|minutes?)\b", re.I)
40
+ INTENT = re.compile(_VERB, re.I)
41
+ CANCEL = re.compile(r"^\s*(?:stop|that'?s\s+enough|you\s+can\s+stop|ok(?:ay)?\s+stop)\s*[.!]*\s*$|cancel\s+the\s+(?:order|deadline)", re.I)
42
+
43
+
44
+ def home() -> Path:
45
+ return Path(os.environ.get("RAYNSIS_SHIFT_HOME") or Path.home() / ".raynsis-shift")
46
+
47
+
48
+ def _log(record: dict) -> None:
49
+ try:
50
+ home().mkdir(parents=True, exist_ok=True)
51
+ with open(home() / "log.jsonl", "a", encoding="utf-8") as f:
52
+ f.write(json.dumps({"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), **record}, ensure_ascii=False) + "\n")
53
+ except Exception:
54
+ pass
55
+
56
+
57
+ def _path(session: str) -> Path:
58
+ return home() / "orders" / (re.sub(r"[^A-Za-z0-9_.-]", "_", session or "none")[:80] + ".json")
59
+
60
+
61
+ def _read(session: str):
62
+ try:
63
+ return json.loads(_path(session).read_text(encoding="utf-8"))
64
+ except Exception:
65
+ return None
66
+
67
+
68
+ def _write(session: str, order: dict) -> None:
69
+ p = _path(session)
70
+ p.parent.mkdir(parents=True, exist_ok=True)
71
+ p.write_text(json.dumps(order, ensure_ascii=False), encoding="utf-8")
72
+
73
+
74
+ def _drop(session: str) -> None:
75
+ try:
76
+ _path(session).unlink()
77
+ except OSError:
78
+ pass
79
+
80
+
81
+ def _hhmm(t: float) -> str:
82
+ return time.strftime("%H:%M", time.localtime(t))
83
+
84
+
85
+ def parse(prompt: str, now: float = None):
86
+ """Deadline (epoch seconds) if the prompt is a timed work order, else None. Needs both a time and a work verb,
87
+ so "the meeting runs until 5pm" is not an order. Capped at MAX_HOURS."""
88
+ now = now or time.time()
89
+ text = " ".join((prompt or "").split())
90
+ if not text or len(text) > MAX_PROMPT or text.startswith("<") or not INTENT.search(text):
91
+ return None
92
+ cap = now + MAX_HOURS * 3600
93
+ m = HOURS.search(text)
94
+ if m:
95
+ return min(now + float(m.group(1)) * 3600, cap)
96
+ m = MINUTES.search(text)
97
+ if m:
98
+ return min(now + int(m.group(1)) * 60, cap)
99
+ m = CLOCK.search(text)
100
+ if m:
101
+ hour, minute, half = int(m.group(1)), int(m.group(2) or 0), (m.group(3) or "").lower()
102
+ if half == "pm" and hour < 12:
103
+ hour += 12
104
+ if half == "am" and hour == 12:
105
+ hour = 0
106
+ if hour > 23 or minute > 59:
107
+ return None
108
+ lt = time.localtime(now)
109
+ target = time.mktime((lt.tm_year, lt.tm_mon, lt.tm_mday, hour, minute, 0, 0, 0, -1))
110
+ if target <= now:
111
+ target += 86400 # "until 02:00" said at 23:00 means tomorrow
112
+ return min(target, cap)
113
+ return None
114
+
115
+
116
+ def on_prompt(event: dict, now: float = None) -> str:
117
+ """Text to add to the context ('' for none)."""
118
+ now = now or time.time()
119
+ session = event.get("session_id")
120
+ prompt = str(event.get("prompt") or "")
121
+ if not session or os.environ.get("RAYNSIS_SHIFT") == "off":
122
+ return ""
123
+ if CANCEL.search(prompt.strip()):
124
+ if _read(session):
125
+ _drop(session)
126
+ _log({"event": "cancelled", "session": session})
127
+ return "Timed order cancelled by the user. You may end the turn normally."
128
+ return ""
129
+ deadline = parse(prompt, now)
130
+ if deadline:
131
+ _write(session, {"deadline": deadline, "start": now, "source": " ".join(prompt.split())[:200], "blocks": 0, "idle": 0, "offset": 0})
132
+ _log({"event": "order", "session": session, "minutes": int((deadline - now) / 60)})
133
+ order = _read(session)
134
+ if not order or order["deadline"] - now < 120:
135
+ return ""
136
+ return (f"TIMED ORDER: do not stop before {_hhmm(order['deadline'])} ({int((order['deadline'] - now) / 60)} min left). When one item is done, "
137
+ f"move to the next item in scope without asking. If nothing is left, write '{RELEASE} <what you measured>'.")
138
+
139
+
140
+ def _tool_calls(transcript: str, offset: int):
141
+ try:
142
+ size = os.path.getsize(transcript)
143
+ if offset > size:
144
+ offset = 0
145
+ with open(transcript, "rb") as f:
146
+ f.seek(offset)
147
+ data = f.read()
148
+ return data.count(b'"type":"tool_use"') + data.count(b'"type": "tool_use"'), size
149
+ except OSError:
150
+ return None, offset
151
+
152
+
153
+ def on_stop(event: dict, now: float = None) -> str:
154
+ """Reason to block the end of the turn ('' to let it end)."""
155
+ now = now or time.time()
156
+ session = event.get("session_id")
157
+ if not session or os.environ.get("RAYNSIS_SHIFT") == "off":
158
+ return ""
159
+ order = _read(session)
160
+ if not order:
161
+ return ""
162
+ left = order.get("deadline", 0) - now
163
+ if left < 120:
164
+ _drop(session)
165
+ _log({"event": "deadline_reached", "session": session, "blocks": order.get("blocks", 0)})
166
+ return ""
167
+ last = str(event.get("last_assistant_message") or "")
168
+ if RELEASE in last:
169
+ _drop(session)
170
+ _log({"event": "order_complete", "session": session, "reason": last.split(RELEASE, 1)[1].strip()[:160]})
171
+ return ""
172
+ if order.get("blocks", 0) >= MAX_BLOCKS:
173
+ _drop(session)
174
+ _log({"event": "max_blocks", "session": session})
175
+ return ""
176
+ calls, size = _tool_calls(str(event.get("transcript_path") or ""), int(order.get("offset", 0)))
177
+ if calls is None:
178
+ return "" # cannot measure the work done: do not block blind
179
+ order["idle"] = 0 if calls > 0 else int(order.get("idle", 0)) + 1
180
+ order["offset"] = size
181
+ if order["idle"] >= 2: # two blocks, no tool call: nothing to do, or stuck
182
+ order["idle"] = 0
183
+ _write(session, order)
184
+ _log({"event": "released_idle", "session": session})
185
+ return ""
186
+ order["blocks"] = int(order.get("blocks", 0)) + 1
187
+ _write(session, order)
188
+ _log({"event": "block", "session": session, "n": order["blocks"], "minutes_left": int(left / 60), "tool_calls": calls})
189
+ return (f"TIMED ORDER (\"{order.get('source', '')[:140]}\"): deadline {_hhmm(order['deadline'])}, {int(left / 60)} min left. Do not end the turn. "
190
+ f"Do the next item in scope now; do not ask questions, park decisions that need the user and move on. If nothing in scope is "
191
+ f"really left, write '{RELEASE} <what you measured>'. [block {order['blocks']} of {MAX_BLOCKS}]")
192
+
193
+
194
+ def main(argv=None) -> int:
195
+ for _s in (sys.stdout, sys.stderr): # Windows pipes default to a legacy code page
196
+ try:
197
+ _s.reconfigure(encoding="utf-8")
198
+ except (AttributeError, ValueError):
199
+ pass
200
+ argv = sys.argv[1:] if argv is None else argv
201
+ mode = argv[0] if argv else ""
202
+ try:
203
+ if mode in ("prompt", "stop"):
204
+ raw = sys.stdin.read()
205
+ event = json.loads(raw) if raw.strip() else {}
206
+ if mode == "prompt":
207
+ text = on_prompt(event)
208
+ if text:
209
+ print(text)
210
+ else:
211
+ reason = on_stop(event)
212
+ if reason:
213
+ print(json.dumps({"decision": "block", "reason": reason}))
214
+ return 0
215
+ if mode in ("install", "undo"):
216
+ return _settings(mode == "install")
217
+ if mode == "status":
218
+ d = home() / "orders"
219
+ orders = sorted(d.glob("*.json")) if d.is_dir() else []
220
+ for p in orders:
221
+ o = json.loads(p.read_text(encoding="utf-8"))
222
+ print(f"{p.stem} until {_hhmm(o['deadline'])} blocks {o.get('blocks', 0)} \"{o.get('source', '')[:60]}\"")
223
+ if not orders:
224
+ print("no active order")
225
+ return 0
226
+ except Exception:
227
+ return 0
228
+ print("usage: raynsis-shift install | undo | status (hook modes: prompt, stop)")
229
+ return 1
230
+
231
+
232
+ MARK = "raynsis_shift.gate"
233
+
234
+
235
+ def _settings(install: bool) -> int:
236
+ import shutil
237
+ path = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude") / "settings.json"
238
+ try:
239
+ settings = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
240
+ except Exception:
241
+ print(f"{path} is not valid JSON; nothing changed.")
242
+ return 1
243
+ if path.exists() and install:
244
+ backup = path.with_name(f"settings.json.raynsis-shift-backup-{time.strftime('%Y%m%d-%H%M%S')}")
245
+ shutil.copy2(path, backup)
246
+ print(f"backup: {backup}")
247
+ hooks = settings.get("hooks") or {}
248
+ removed = 0
249
+ for name in list(hooks):
250
+ groups = []
251
+ for group in hooks[name] or []:
252
+ keep = [h for h in group.get("hooks") or [] if MARK not in str(h.get("command") or "")]
253
+ removed += len(group.get("hooks") or []) - len(keep)
254
+ if keep:
255
+ groups.append({**group, "hooks": keep})
256
+ if groups:
257
+ hooks[name] = groups
258
+ else:
259
+ del hooks[name]
260
+ if install:
261
+ for name, mode in (("UserPromptSubmit", "prompt"), ("Stop", "stop")):
262
+ hooks.setdefault(name, []).append({"hooks": [{"type": "command", "command": f'"{sys.executable}" -m {MARK} {mode}', "timeout": 10}]})
263
+ if hooks:
264
+ settings["hooks"] = hooks
265
+ else:
266
+ settings.pop("hooks", None)
267
+ if install or removed:
268
+ path.parent.mkdir(parents=True, exist_ok=True)
269
+ path.write_text(json.dumps(settings, ensure_ascii=False, indent=1), encoding="utf-8")
270
+ print(f"installed 2 hooks into {path}" if install else f"removed {removed} hooks from {path}")
271
+ return 0
272
+
273
+
274
+ if __name__ == "__main__":
275
+ sys.exit(main())
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: raynsis-shift
3
+ Version: 0.1.0
4
+ Summary: Timed work orders for Claude Code: 'keep working until 17:30' stays in force until 17:30.
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ License-File: NOTICE
10
+ Dynamic: license-file
11
+
12
+ # RAYNSIS Shift
13
+
14
+ **"Keep working until 17:30" should still be true at 16:00.**
15
+
16
+ You give Claude Code a timed order. It finishes one item, writes a tidy summary and stops. You type "continue".
17
+ Again. And again. In the setup this was extracted from, the owner gave 14 timed orders in 30 days and had to
18
+ re-issue every one of them by hand.
19
+
20
+ raynsis-shift keeps the order per session and turns back every attempt to end the turn until the deadline.
21
+
22
+ ```
23
+ pip install raynsis-shift
24
+ raynsis-shift install
25
+ ```
26
+
27
+ Then just say it:
28
+
29
+ - `keep working until 17:30`
30
+ - `don't stop for 3 hours`
31
+ - `carry on for another 45 minutes`
32
+
33
+ `raynsis-shift status` shows active orders. `raynsis-shift undo` removes the two hooks.
34
+
35
+ ## It cannot loop forever
36
+
37
+ The order is released when any of these is true:
38
+
39
+ | Condition | Why |
40
+ |---|---|
41
+ | The deadline passed | The order is over. |
42
+ | The answer contains `order-complete: <what was measured>` | Nothing in scope is left; the reason is logged. |
43
+ | Two blocks in a row with no tool call | The agent has nothing to do or is stuck; forcing it only burns tokens. |
44
+ | 40 blocks issued | Hard ceiling. |
45
+ | You type `stop`, `that's enough` or `cancel the order` | You are in charge. |
46
+ | `RAYNSIS_SHIFT=off` is set | Kill switch. |
47
+
48
+ Orders are capped at 9 hours. A prompt needs both a time and a work verb, so "the meeting runs until 5pm"
49
+ is not an order. If the transcript cannot be read, the gate does not block.
50
+
51
+ ## How it works
52
+
53
+ Two hooks, one file, standard library only.
54
+
55
+ - `UserPromptSubmit`: parses the order, stores the deadline in `~/.raynsis-shift/orders/<session>.json`,
56
+ and reminds the model of the time left on every prompt.
57
+ - `Stop`: while an order is active, returns `{"decision": "block", "reason": ...}` naming the deadline and
58
+ asking for the next item in scope.
59
+
60
+ Every decision is one line in `~/.raynsis-shift/log.jsonl`.
61
+
62
+ ## Limits
63
+
64
+ - English order phrases only in 0.1.
65
+ - Tested on macOS with Python 3.9.
66
+ - An order belongs to one session. Other sessions are not affected.
67
+
68
+ ## Tests
69
+
70
+ ```
71
+ python -m unittest discover tests
72
+ ```
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ NOTICE
3
+ README.md
4
+ pyproject.toml
5
+ raynsis_shift/__init__.py
6
+ raynsis_shift/gate.py
7
+ raynsis_shift.egg-info/PKG-INFO
8
+ raynsis_shift.egg-info/SOURCES.txt
9
+ raynsis_shift.egg-info/dependency_links.txt
10
+ raynsis_shift.egg-info/entry_points.txt
11
+ raynsis_shift.egg-info/top_level.txt
12
+ tests/test_gate.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ raynsis-shift = raynsis_shift.gate:main
@@ -0,0 +1 @@
1
+ raynsis_shift
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,94 @@
1
+ import json
2
+ import os
3
+ import sys
4
+ import tempfile
5
+ import time
6
+ import unittest
7
+ from pathlib import Path
8
+ from unittest import mock
9
+
10
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
11
+ from raynsis_shift import gate # noqa: E402
12
+
13
+ NOON = time.mktime((2026, 12, 3, 12, 0, 0, 0, 0, -1))
14
+
15
+
16
+ class Parse(unittest.TestCase):
17
+ def test_durations_and_clock_times(self):
18
+ self.assertEqual(gate.parse("keep working for 3 hours", NOON), NOON + 3 * 3600)
19
+ self.assertEqual(gate.parse("Don't stop for another 45 minutes please", NOON), NOON + 45 * 60)
20
+ self.assertEqual(gate.parse("work until 17:30 on the backlog", NOON), NOON + 5.5 * 3600)
21
+ self.assertEqual(gate.parse("keep going until 5pm", NOON), NOON + 5 * 3600)
22
+ self.assertEqual(gate.parse("continue till 11:00", NOON), NOON + gate.MAX_HOURS * 3600) # tomorrow, capped
23
+
24
+ def test_needs_a_work_verb_and_caps_the_length(self):
25
+ self.assertIsNone(gate.parse("the meeting is until 5pm", NOON))
26
+ self.assertIsNone(gate.parse("fix the login bug", NOON))
27
+ self.assertIsNone(gate.parse("keep working until 25:99", NOON))
28
+ self.assertEqual(gate.parse("keep working for 40 hours", NOON), NOON + gate.MAX_HOURS * 3600)
29
+ self.assertIsNone(gate.parse("work for 2 hours " + "x" * 2000, NOON))
30
+
31
+
32
+ class Flow(unittest.TestCase):
33
+ def setUp(self):
34
+ self.tmp = tempfile.TemporaryDirectory()
35
+ self.patch = mock.patch.dict(os.environ, {"RAYNSIS_SHIFT_HOME": self.tmp.name})
36
+ self.patch.start()
37
+ self.transcript = Path(self.tmp.name) / "t.jsonl"
38
+ self.transcript.write_text("")
39
+ self.event = {"session_id": "s1", "transcript_path": str(self.transcript)}
40
+
41
+ def tearDown(self):
42
+ self.patch.stop()
43
+ self.tmp.cleanup()
44
+
45
+ def work(self):
46
+ with open(self.transcript, "a") as f:
47
+ f.write('{"type":"tool_use"}\n')
48
+
49
+ def test_blocks_until_deadline_then_releases(self):
50
+ self.assertIn("13:00", gate.on_prompt({**self.event, "prompt": "keep working for 1 hour"}, NOON))
51
+ self.work()
52
+ self.assertIn("Do not end the turn", gate.on_stop(self.event, NOON + 60))
53
+ self.work()
54
+ self.assertIn("block 2", gate.on_stop(self.event, NOON + 600))
55
+ self.assertEqual(gate.on_stop(self.event, NOON + 3600 - 60), "") # under two minutes left
56
+ self.assertIsNone(gate._read("s1"))
57
+
58
+ def test_release_phrase_idle_and_other_sessions(self):
59
+ gate.on_prompt({**self.event, "prompt": "don't stop for 2 hours"}, NOON)
60
+ self.assertEqual(gate.on_stop({"session_id": "other", "transcript_path": str(self.transcript)}, NOON + 60), "")
61
+ self.assertNotEqual(gate.on_stop(self.event, NOON + 60), "") # first block, no tool call yet: idle 1
62
+ self.assertEqual(gate.on_stop(self.event, NOON + 120), "") # second in a row with no work: let go
63
+ self.work()
64
+ self.assertNotEqual(gate.on_stop(self.event, NOON + 180), "") # work happened: blocks again
65
+ self.assertEqual(gate.on_stop({**self.event, "last_assistant_message": "order-complete: 5 of 5 items verified"}, NOON + 240), "")
66
+ self.assertIsNone(gate._read("s1"))
67
+
68
+ def test_cancel_cap_and_unreadable_transcript(self):
69
+ gate.on_prompt({**self.event, "prompt": "work for 3 hours"}, NOON)
70
+ self.assertEqual(gate.on_stop({"session_id": "s1", "transcript_path": "/nonexistent"}, NOON + 60), "")
71
+ self.assertIn("cancelled", gate.on_prompt({**self.event, "prompt": "stop"}, NOON + 90))
72
+ self.assertEqual(gate.on_stop(self.event, NOON + 120), "")
73
+ gate.on_prompt({**self.event, "prompt": "work for 3 hours"}, NOON)
74
+ order = gate._read("s1"); order["blocks"] = gate.MAX_BLOCKS; gate._write("s1", order)
75
+ self.assertEqual(gate.on_stop(self.event, NOON + 60), "")
76
+ events = [json.loads(l)["event"] for l in (Path(self.tmp.name) / "log.jsonl").read_text().splitlines()]
77
+ self.assertEqual(events, ["order", "cancelled", "order", "max_blocks"])
78
+
79
+ def test_install_and_undo_leave_other_hooks_alone(self):
80
+ cfg = Path(self.tmp.name) / "claude"
81
+ cfg.mkdir()
82
+ mine = {"hooks": {"Stop": [{"hooks": [{"type": "command", "command": "echo mine"}]}]}}
83
+ (cfg / "settings.json").write_text(json.dumps(mine))
84
+ with mock.patch.dict(os.environ, {"CLAUDE_CONFIG_DIR": str(cfg)}), mock.patch("builtins.print"):
85
+ gate.main(["install"]); gate.main(["install"])
86
+ now = json.loads((cfg / "settings.json").read_text())
87
+ self.assertEqual(len(now["hooks"]["Stop"]), 2)
88
+ self.assertEqual(len(now["hooks"]["UserPromptSubmit"]), 1)
89
+ gate.main(["undo"])
90
+ self.assertEqual(json.loads((cfg / "settings.json").read_text()), mine)
91
+
92
+
93
+ if __name__ == "__main__":
94
+ unittest.main()