raynsis-concierge 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-concierge
2
+ Copyright 2026 RAYNSIS AI Workforce
3
+
4
+ This product includes software developed by RAYNSIS AI Workforce.
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: raynsis-concierge
3
+ Version: 0.1.0
4
+ Summary: Run Claude Code from your home directory: no project folder to pick. Prompt routing, memory recall and guard rails as plain Python hooks.
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 Concierge
13
+
14
+ **Open one terminal. Say what you need. No project folder, no setup per task.**
15
+
16
+ raynsis-concierge turns Claude Code into a single home-directory assistant. You start `claude` in your home directory and
17
+ state the job in plain words. Four small hooks do the rest:
18
+
19
+ | Hook | When it runs | What it does |
20
+ |---|---|---|
21
+ | `route_prompt` | every prompt | Finds the skills and agents whose trigger phrases appear in your request and puts them in front of the model. |
22
+ | `memory_recall` | every prompt | Adds the memory notes that match the request: at most 2 notes and 700 characters, once per session, every decision logged. |
23
+ | `session_topic` | every prompt | Names the session after the work (three words, no model call) so you can find and reopen it later. |
24
+ | `guard_home_glob` | before a file search | Stops a search rooted at the home directory before it walks every folder you own. |
25
+
26
+ Pure Python standard library. No database, no model calls, no network.
27
+
28
+ ## Install
29
+
30
+ ```
31
+ pip install raynsis-concierge
32
+ raynsis-concierge install
33
+ raynsis-concierge doctor
34
+ ```
35
+
36
+ `install` backs up `~/.claude/settings.json`, adds four hook entries and leaves every other setting alone.
37
+ `raynsis-concierge undo` removes them again. `doctor` prints what it found and what is missing.
38
+
39
+ Then:
40
+
41
+ 1. Edit `~/.raynsis-concierge/routing.json`: one entry per skill or agent, with the phrases that should trigger it.
42
+ 2. Copy `~/.raynsis-concierge/CLAUDE.home.md` to `~/CLAUDE.md` and describe where your things live.
43
+ 3. Start `claude` in your home directory.
44
+
45
+ ## Daily use
46
+
47
+ ```
48
+ raynsis-concierge sessions
49
+ raynsis-concierge search supplier payment
50
+ ```
51
+
52
+ `sessions` lists recent sessions by topic with the command that reopens each one. `search` looks through your
53
+ memory notes with the same matcher the hook uses.
54
+
55
+ ## What "no folder" means
56
+
57
+ Your work still lives in folders. The difference is that you never choose one: the router file says what lives
58
+ where, the routing table says which tool fits which request, and memory notes carry what was decided before.
59
+ The assistant navigates; you describe the job.
60
+
61
+ ## Measured, not assumed
62
+
63
+ Every hook appends one JSON line per decision to `~/.raynsis-concierge/log/`. Memory recall is strict on purpose: a
64
+ recalled note costs context on every later turn. In the system this was extracted from, loosening the matcher
65
+ to one shared word made 41% of recalled notes irrelevant on 179 real prompts; requiring two brought it to 8%.
66
+ Read your own log before changing the thresholds.
67
+
68
+ ## Limits
69
+
70
+ - Tested on macOS with Python 3.9. Linux should work; Windows is not tested yet.
71
+ - The memory directory name is derived from the working directory the way Claude Code does it today. If that
72
+ changes, set `"memory_dir"` in `~/.raynsis-concierge/config.json`.
73
+ - Hooks fail open: if one breaks, your prompt still goes through.
74
+
75
+ ## Tests
76
+
77
+ ```
78
+ python -m unittest discover tests
79
+ ```
@@ -0,0 +1,68 @@
1
+ # RAYNSIS Concierge
2
+
3
+ **Open one terminal. Say what you need. No project folder, no setup per task.**
4
+
5
+ raynsis-concierge turns Claude Code into a single home-directory assistant. You start `claude` in your home directory and
6
+ state the job in plain words. Four small hooks do the rest:
7
+
8
+ | Hook | When it runs | What it does |
9
+ |---|---|---|
10
+ | `route_prompt` | every prompt | Finds the skills and agents whose trigger phrases appear in your request and puts them in front of the model. |
11
+ | `memory_recall` | every prompt | Adds the memory notes that match the request: at most 2 notes and 700 characters, once per session, every decision logged. |
12
+ | `session_topic` | every prompt | Names the session after the work (three words, no model call) so you can find and reopen it later. |
13
+ | `guard_home_glob` | before a file search | Stops a search rooted at the home directory before it walks every folder you own. |
14
+
15
+ Pure Python standard library. No database, no model calls, no network.
16
+
17
+ ## Install
18
+
19
+ ```
20
+ pip install raynsis-concierge
21
+ raynsis-concierge install
22
+ raynsis-concierge doctor
23
+ ```
24
+
25
+ `install` backs up `~/.claude/settings.json`, adds four hook entries and leaves every other setting alone.
26
+ `raynsis-concierge undo` removes them again. `doctor` prints what it found and what is missing.
27
+
28
+ Then:
29
+
30
+ 1. Edit `~/.raynsis-concierge/routing.json`: one entry per skill or agent, with the phrases that should trigger it.
31
+ 2. Copy `~/.raynsis-concierge/CLAUDE.home.md` to `~/CLAUDE.md` and describe where your things live.
32
+ 3. Start `claude` in your home directory.
33
+
34
+ ## Daily use
35
+
36
+ ```
37
+ raynsis-concierge sessions
38
+ raynsis-concierge search supplier payment
39
+ ```
40
+
41
+ `sessions` lists recent sessions by topic with the command that reopens each one. `search` looks through your
42
+ memory notes with the same matcher the hook uses.
43
+
44
+ ## What "no folder" means
45
+
46
+ Your work still lives in folders. The difference is that you never choose one: the router file says what lives
47
+ where, the routing table says which tool fits which request, and memory notes carry what was decided before.
48
+ The assistant navigates; you describe the job.
49
+
50
+ ## Measured, not assumed
51
+
52
+ Every hook appends one JSON line per decision to `~/.raynsis-concierge/log/`. Memory recall is strict on purpose: a
53
+ recalled note costs context on every later turn. In the system this was extracted from, loosening the matcher
54
+ to one shared word made 41% of recalled notes irrelevant on 179 real prompts; requiring two brought it to 8%.
55
+ Read your own log before changing the thresholds.
56
+
57
+ ## Limits
58
+
59
+ - Tested on macOS with Python 3.9. Linux should work; Windows is not tested yet.
60
+ - The memory directory name is derived from the working directory the way Claude Code does it today. If that
61
+ changes, set `"memory_dir"` in `~/.raynsis-concierge/config.json`.
62
+ - Hooks fail open: if one breaks, your prompt still goes through.
63
+
64
+ ## Tests
65
+
66
+ ```
67
+ python -m unittest discover tests
68
+ ```
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "raynsis-concierge"
7
+ version = "0.1.0"
8
+ description = "Run Claude Code from your home directory: no project folder to pick. Prompt routing, memory recall and guard rails as plain Python hooks."
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-concierge = "raynsis_concierge.cli:main"
17
+
18
+ [tool.setuptools.packages.find]
19
+ include = ["raynsis_concierge*"]
20
+
21
+ [tool.setuptools.package-data]
22
+ raynsis_concierge = ["templates/*"]
@@ -0,0 +1,2 @@
1
+ """raynsis-concierge: run Claude Code from your home directory, with no project folder to pick."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,180 @@
1
+ """raynsis-concierge command line: install, undo, doctor, sessions, search."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import shutil
6
+ import sys
7
+ import time
8
+ from pathlib import Path
9
+
10
+ from . import __version__
11
+ from .common import base_dir, claude_dir, load_json, save_json
12
+ from .hooks.memory_recall import memory_dir, parse_note, rank
13
+
14
+ MARK = "raynsis_concierge.hooks."
15
+ HOOKS = [
16
+ ("UserPromptSubmit", None, "route_prompt"),
17
+ ("UserPromptSubmit", None, "memory_recall"),
18
+ ("UserPromptSubmit", None, "session_topic"),
19
+ ("PreToolUse", "Glob", "guard_home_glob"),
20
+ ]
21
+ TEMPLATES = Path(__file__).parent / "templates"
22
+
23
+
24
+ def command(module: str) -> str:
25
+ return f'"{sys.executable}" -m {MARK}{module}'
26
+
27
+
28
+ def settings_path() -> Path:
29
+ return claude_dir() / "settings.json"
30
+
31
+
32
+ def installed(settings: dict) -> list:
33
+ found = []
34
+ for event, groups in (settings.get("hooks") or {}).items():
35
+ for group in groups or []:
36
+ for hook in group.get("hooks") or []:
37
+ if MARK in str(hook.get("command") or ""):
38
+ found.append((event, str(hook["command"]).rsplit(MARK, 1)[1]))
39
+ return found
40
+
41
+
42
+ def strip(settings: dict) -> int:
43
+ """Remove every raynsis-concierge hook, and any group or event left empty by that. Returns how many were removed."""
44
+ removed = 0
45
+ hooks = settings.get("hooks") or {}
46
+ for event in list(hooks):
47
+ groups = []
48
+ for group in hooks[event] or []:
49
+ keep = [h for h in group.get("hooks") or [] if MARK not in str(h.get("command") or "")]
50
+ removed += len(group.get("hooks") or []) - len(keep)
51
+ if keep:
52
+ groups.append({**group, "hooks": keep})
53
+ if groups:
54
+ hooks[event] = groups
55
+ else:
56
+ del hooks[event]
57
+ if "hooks" in settings and not hooks:
58
+ del settings["hooks"]
59
+ return removed
60
+
61
+
62
+ def do_install(_args) -> int:
63
+ path = settings_path()
64
+ settings = load_json(path, {})
65
+ if not isinstance(settings, dict):
66
+ print(f"raynsis-concierge: {path} is not a JSON object; nothing changed.")
67
+ return 1
68
+ if path.exists():
69
+ backup = path.with_name(f"settings.json.raynsis-concierge-backup-{time.strftime('%Y%m%d-%H%M%S')}")
70
+ shutil.copy2(path, backup)
71
+ print(f"backup: {backup}")
72
+ strip(settings)
73
+ hooks = settings.setdefault("hooks", {})
74
+ for event, matcher, module in HOOKS:
75
+ group = {"hooks": [{"type": "command", "command": command(module), "timeout": 10}]}
76
+ if matcher:
77
+ group["matcher"] = matcher
78
+ hooks.setdefault(event, []).append(group)
79
+ save_json(path, settings)
80
+ base = base_dir()
81
+ base.mkdir(parents=True, exist_ok=True)
82
+ for name, target in (("routing.example.json", base / "routing.json"), ("CLAUDE.home.md", base / "CLAUDE.home.md")):
83
+ if not target.exists():
84
+ shutil.copy2(TEMPLATES / name, target)
85
+ print(f"created: {target}")
86
+ print(f"installed {len(HOOKS)} hooks into {path}")
87
+ print("next: edit ~/.raynsis-concierge/routing.json, copy ~/.raynsis-concierge/CLAUDE.home.md to ~/CLAUDE.md, then start `claude` in your home directory.")
88
+ return 0
89
+
90
+
91
+ def do_undo(_args) -> int:
92
+ path = settings_path()
93
+ settings = load_json(path, None)
94
+ if not isinstance(settings, dict):
95
+ print("raynsis-concierge: no settings file to change.")
96
+ return 0
97
+ removed = strip(settings)
98
+ if removed:
99
+ save_json(path, settings)
100
+ print(f"removed {removed} hooks from {path}. Your notes, routing table and logs in {base_dir()} were left in place.")
101
+ return 0
102
+
103
+
104
+ def do_doctor(_args) -> int:
105
+ problems = 0
106
+
107
+ def check(ok: bool, good: str, bad: str) -> None:
108
+ nonlocal problems
109
+ problems += 0 if ok else 1
110
+ print(("ok " if ok else "check ") + (good if ok else bad))
111
+
112
+ print(f"raynsis-concierge {__version__} · python {sys.version.split()[0]} · {sys.platform}")
113
+ settings = load_json(settings_path(), {})
114
+ have = {m for _, m in installed(settings if isinstance(settings, dict) else {})}
115
+ want = {m for _, _, m in HOOKS}
116
+ check(have >= want, f"{len(want)} hooks registered in {settings_path()}", f"missing hooks: {', '.join(sorted(want - have))} · run `raynsis-concierge install`")
117
+ routing = load_json(base_dir() / "routing.json", None)
118
+ check(isinstance(routing, list) and len(routing) > 0, f"routing table has {len(routing or [])} entries", f"no routing table at {base_dir() / 'routing.json'}")
119
+ home = str(Path.home())
120
+ mem = memory_dir(home)
121
+ notes = list(mem.glob("*.md")) if mem.is_dir() else []
122
+ check(mem.is_dir(), f"memory directory {mem} · {len(notes)} notes", f"no memory directory yet at {mem} (Claude Code creates it on first use from ~)")
123
+ check((Path.home() / "CLAUDE.md").exists(), "~/CLAUDE.md router file present", "no ~/CLAUDE.md: copy ~/.raynsis-concierge/CLAUDE.home.md there and fill it in")
124
+ index = mem / "MEMORY.md"
125
+ if index.exists():
126
+ size = index.stat().st_size
127
+ check(size <= 20_000, f"MEMORY.md is {size} bytes", f"MEMORY.md is {size} bytes: it loads on every turn, trim it under 20,000")
128
+ print("all good" if not problems else f"{problems} thing(s) to look at")
129
+ return 0 if not problems else 1
130
+
131
+
132
+ def do_sessions(args) -> int:
133
+ d = base_dir() / "sessions"
134
+ records = [load_json(p, {}) for p in d.glob("*.json")] if d.is_dir() else []
135
+ records = sorted((r for r in records if isinstance(r, dict) and r.get("session")), key=lambda r: str(r.get("last")), reverse=True)
136
+ if not records:
137
+ print("no sessions recorded yet")
138
+ return 0
139
+ for r in records[: args.limit]:
140
+ print(f'{r.get("last", "?"):19} {str(r.get("topic") or "untitled"):32} claude --resume {r["session"]}')
141
+ return 0
142
+
143
+
144
+ def do_search(args) -> int:
145
+ d = memory_dir(str(Path.home()))
146
+ notes = [parse_note(p) for p in sorted(d.glob("*.md")) if p.name != "MEMORY.md"] if d.is_dir() else []
147
+ hits = rank(" ".join(args.query), notes, min_shared=1)
148
+ if not hits:
149
+ print(f"nothing matched in {len(notes)} notes (searched {d})")
150
+ return 1
151
+ for note, shared in hits[: args.limit]:
152
+ print(f'{note["file"]} · {note["description"][:100]} · matched: {", ".join(shared)}')
153
+ return 0
154
+
155
+
156
+ def main(argv=None) -> int:
157
+ for _s in (sys.stdout, sys.stderr): # Windows pipes default to a legacy code page
158
+ try:
159
+ _s.reconfigure(encoding="utf-8")
160
+ except (AttributeError, ValueError):
161
+ pass
162
+ p = argparse.ArgumentParser(prog="raynsis-concierge", description="Run Claude Code from your home directory, with no project folder to pick.")
163
+ p.add_argument("--version", action="version", version=__version__)
164
+ sub = p.add_subparsers(dest="cmd", required=True)
165
+ sub.add_parser("install", help="add the hooks to Claude Code's settings.json (a backup is taken first)").set_defaults(fn=do_install)
166
+ sub.add_parser("undo", help="remove the hooks again").set_defaults(fn=do_undo)
167
+ sub.add_parser("doctor", help="check the install and print what was found").set_defaults(fn=do_doctor)
168
+ s = sub.add_parser("sessions", help="list recent sessions by topic, with the command that reopens each")
169
+ s.add_argument("--limit", type=int, default=15)
170
+ s.set_defaults(fn=do_sessions)
171
+ s = sub.add_parser("search", help="search your memory notes")
172
+ s.add_argument("query", nargs="+")
173
+ s.add_argument("--limit", type=int, default=10)
174
+ s.set_defaults(fn=do_search)
175
+ args = p.parse_args(argv)
176
+ return args.fn(args)
177
+
178
+
179
+ if __name__ == "__main__":
180
+ sys.exit(main())
@@ -0,0 +1,75 @@
1
+ """Shared helpers. Standard library only; every hook fails open (a broken hook must never block the user)."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+
12
+ def base_dir() -> Path:
13
+ """Where raynsis-concierge keeps its config, state and logs. Override with RAYNSIS_CONCIERGE_HOME."""
14
+ return Path(os.environ.get("RAYNSIS_CONCIERGE_HOME") or Path.home() / ".raynsis-concierge")
15
+
16
+
17
+ def claude_dir() -> Path:
18
+ """Claude Code's config directory. Honors CLAUDE_CONFIG_DIR."""
19
+ return Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
20
+
21
+
22
+ def read_event() -> dict:
23
+ """The hook payload Claude Code writes to stdin. Empty dict when there is none."""
24
+ try:
25
+ raw = sys.stdin.read()
26
+ data = json.loads(raw) if raw.strip() else {}
27
+ return data if isinstance(data, dict) else {}
28
+ except Exception:
29
+ return {}
30
+
31
+
32
+ def log(name: str, record: dict) -> None:
33
+ """Append one JSON line to ~/.raynsis-concierge/log/<name>.jsonl. Logs are append-only so the cost of every hook can be measured later."""
34
+ try:
35
+ d = base_dir() / "log"
36
+ d.mkdir(parents=True, exist_ok=True)
37
+ record = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), **record}
38
+ with open(d / f"{name}.jsonl", "a", encoding="utf-8") as f:
39
+ f.write(json.dumps(record, ensure_ascii=False) + "\n")
40
+ except Exception:
41
+ pass
42
+
43
+
44
+ def load_json(path: Path, default):
45
+ try:
46
+ return json.loads(path.read_text(encoding="utf-8"))
47
+ except Exception:
48
+ return default
49
+
50
+
51
+ def save_json(path: Path, data) -> None:
52
+ path.parent.mkdir(parents=True, exist_ok=True)
53
+ tmp = path.with_suffix(path.suffix + ".tmp")
54
+ tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
55
+ os.replace(tmp, path)
56
+
57
+
58
+ _WORD = re.compile(r"[^\W\d_]{3,}", re.UNICODE)
59
+
60
+ # Small, language-neutral stop list; extend it in ~/.raynsis-concierge/config.json ("stopwords").
61
+ STOPWORDS = {
62
+ "the", "and", "for", "with", "that", "this", "from", "have", "has", "are", "was", "will", "can", "you", "your", "our",
63
+ "please", "need", "want", "make", "what", "when", "where", "which", "how", "about", "into", "should", "would", "could",
64
+ "bir", "ile", "için", "ama", "gibi", "daha", "olan", "var", "yok", "bunu", "şunu", "nasıl", "neden",
65
+ }
66
+
67
+
68
+ def words(text: str, extra_stop: frozenset = frozenset()) -> list:
69
+ """Lower-cased content words of 3+ letters, in order, without stop words."""
70
+ return [w for w in (m.group(0).casefold() for m in _WORD.finditer(text or "")) if w not in STOPWORDS and w not in extra_stop]
71
+
72
+
73
+ def config() -> dict:
74
+ cfg = load_json(base_dir() / "config.json", {})
75
+ return cfg if isinstance(cfg, dict) else {}
@@ -0,0 +1,79 @@
1
+ """PreToolUse hook for the Glob tool: never let a file search start at the home directory or above it.
2
+
3
+ Working from the home directory has one real cost. A glob rooted at ~ walks everything under it, including
4
+ ~/Library on macOS (which raises "access data from other apps" permission prompts) and every cache and dependency
5
+ tree on any system. The search is slow, noisy and almost never what was meant.
6
+
7
+ Rule: if the search root is the home directory or one of its ancestors, the call is denied with a hint that names
8
+ a narrower root. A path that points inside the home directory is always allowed.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import sys
14
+
15
+ from ..common import log, read_event
16
+
17
+ WILDCARDS = set("*?[{")
18
+
19
+
20
+ def resolve(path: str, cwd: str) -> str:
21
+ path = os.path.expandvars(os.path.expanduser(path))
22
+ if not os.path.isabs(path):
23
+ path = os.path.join(cwd, path)
24
+ return os.path.realpath(path)
25
+
26
+
27
+ def search_root(tool_input: dict, cwd: str) -> tuple:
28
+ """(root, pattern relative to root). For an absolute pattern the fixed prefix is the root."""
29
+ pattern = str(tool_input.get("pattern") or "")
30
+ root = resolve(str(tool_input.get("path") or "") or cwd, cwd)
31
+ if pattern.startswith(("/", "~")) or os.path.isabs(pattern):
32
+ parts = os.path.expanduser(pattern).replace("\\", "/").split("/")
33
+ fixed = []
34
+ for part in parts:
35
+ if WILDCARDS & set(part):
36
+ break
37
+ fixed.append(part)
38
+ if len(fixed) < len(parts):
39
+ root = resolve("/".join(fixed) or "/", cwd)
40
+ pattern = "/".join(parts[len(fixed):])
41
+ return root, pattern
42
+
43
+
44
+ def too_wide(root: str, home: str) -> bool:
45
+ r, h = os.path.normcase(os.path.normpath(root)), os.path.normcase(os.path.normpath(home))
46
+ if r == h or os.path.dirname(r) == r: # the home directory itself, or a filesystem root (/ or C:\\)
47
+ return True
48
+ try:
49
+ return os.path.commonpath([r, h]) == r # an ancestor of the home directory
50
+ except ValueError: # different drives on Windows
51
+ return False
52
+
53
+
54
+ def hint(root: str, pattern: str, home: str) -> str:
55
+ head, _, rest = pattern.partition("/")
56
+ if root == home and head and not (WILDCARDS & set(head)) and os.path.isdir(os.path.join(home, head)):
57
+ return f'Search inside that folder instead: path="{os.path.join(home, head)}", pattern="{rest or "*"}".'
58
+ return "Name the folder to search (path=...), or use a content search limited to a folder."
59
+
60
+
61
+ def main() -> int:
62
+ try:
63
+ event = read_event()
64
+ if event.get("tool_name") != "Glob":
65
+ return 0
66
+ home = os.path.realpath(os.path.expanduser("~"))
67
+ cwd = str(event.get("cwd") or os.getcwd())
68
+ root, pattern = search_root(event.get("tool_input") or {}, cwd)
69
+ if not too_wide(root, home):
70
+ return 0
71
+ log("guard_glob", {"session": event.get("session_id"), "root": root, "pattern": pattern})
72
+ sys.stderr.write(f"raynsis-concierge: a file search rooted at {root} would walk the whole home directory. {hint(root, pattern, home)}\n")
73
+ return 2
74
+ except Exception:
75
+ return 0
76
+
77
+
78
+ if __name__ == "__main__":
79
+ sys.exit(main())
@@ -0,0 +1,111 @@
1
+ """UserPromptSubmit hook: bring the memory notes that fit the request into the context.
2
+
3
+ Claude Code keeps a memory directory per working directory. Started from the home directory, every session shares
4
+ one: ~/.claude/projects/<encoded home path>/memory/*.md. Each note has front matter with `name` and `description`.
5
+
6
+ Recall is deliberately strict, because every recalled note is paid for on every later turn:
7
+ - a note is recalled only if it shares at least MIN_SHARED content words with the prompt
8
+ - at most MAX_NOTES notes and MAX_CHARS characters per prompt
9
+ - a note is recalled once per session
10
+ - every decision is logged (recalled or skipped), so precision can be measured from the log
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ from ..common import base_dir, claude_dir, config, load_json, log, read_event, save_json, words
19
+
20
+ MIN_SHARED = 2
21
+ MAX_NOTES = 2
22
+ MAX_CHARS = 700
23
+
24
+
25
+ def encode_cwd(cwd: str) -> str:
26
+ """Claude Code names a project's directory after its path, every non-alphanumeric character replaced by a dash."""
27
+ return re.sub(r"[^A-Za-z0-9]", "-", cwd)
28
+
29
+
30
+ def memory_dir(cwd: str) -> Path:
31
+ override = config().get("memory_dir")
32
+ if override:
33
+ return Path(str(override)).expanduser()
34
+ return claude_dir() / "projects" / encode_cwd(cwd) / "memory"
35
+
36
+
37
+ def parse_note(path: Path) -> dict:
38
+ """name, description and body of one note. Notes without front matter use the file name and first line."""
39
+ text = path.read_text(encoding="utf-8", errors="replace")
40
+ name, description, body = path.stem, "", text
41
+ m = re.match(r"^---\s*\n(.*?)\n---\s*\n?(.*)$", text, re.S)
42
+ if m:
43
+ body = m.group(2)
44
+ for line in m.group(1).splitlines():
45
+ key, _, value = line.partition(":")
46
+ value = value.strip().strip("\"'")
47
+ if key.strip() == "name" and value:
48
+ name = value
49
+ elif key.strip() == "description" and value:
50
+ description = value
51
+ if not description:
52
+ description = next((line.strip("# ").strip() for line in body.splitlines() if line.strip()), "")
53
+ return {"file": path.name, "name": name, "description": description, "body": body.strip()}
54
+
55
+
56
+ def rank(prompt: str, notes: list, min_shared: int = MIN_SHARED) -> list:
57
+ """Notes sharing at least `min_shared` content words with the prompt, best first. Word prefixes count
58
+ (invoice ~ invoices) so inflected languages still match."""
59
+ asked = set(words(prompt))
60
+ ranked = []
61
+ for note in notes:
62
+ have = set(words(note["name"].replace("-", " ").replace("_", " ") + " " + note["description"]))
63
+ shared = {a for a in asked for h in have if a == h or (len(a) >= 5 and len(h) >= 5 and (a.startswith(h[:5]) and h.startswith(a[:5])))}
64
+ if len(shared) >= min_shared:
65
+ ranked.append((len(shared), note, sorted(shared)))
66
+ ranked.sort(key=lambda r: (-r[0], r[1]["file"]))
67
+ return [(n, s) for _, n, s in ranked]
68
+
69
+
70
+ def render(picked: list, budget: int = MAX_CHARS) -> str:
71
+ out = ["Memory (raynsis-concierge): notes that match this request."]
72
+ left = budget
73
+ for note, _ in picked:
74
+ piece = f'- {note["name"]}: {note["description"]}'
75
+ body = " ".join(note["body"].split())
76
+ if body and body != note["description"]:
77
+ piece += " · " + body
78
+ piece = piece[: max(0, left)]
79
+ if not piece:
80
+ break
81
+ out.append(piece + f' ({note["file"]})')
82
+ left -= len(piece)
83
+ return "\n".join(out)
84
+
85
+
86
+ def main() -> int:
87
+ try:
88
+ event = read_event()
89
+ prompt = str(event.get("prompt") or "")
90
+ cwd = str(event.get("cwd") or Path.cwd())
91
+ session = str(event.get("session_id") or "nosession")
92
+ if not prompt.strip() or prompt.lstrip().startswith("/"):
93
+ return 0
94
+ d = memory_dir(cwd)
95
+ if not d.is_dir():
96
+ return 0
97
+ notes = [parse_note(p) for p in sorted(d.glob("*.md")) if p.name != "MEMORY.md"]
98
+ state_file = base_dir() / "state" / f"recalled-{session}.json"
99
+ seen = set(load_json(state_file, []))
100
+ picked = [(n, s) for n, s in rank(prompt, notes) if n["file"] not in seen][:MAX_NOTES]
101
+ log("recall", {"session": session, "notes": len(notes), "recalled": [n["file"] for n, _ in picked], "shared": [s for _, s in picked]})
102
+ if picked:
103
+ print(render(picked))
104
+ save_json(state_file, sorted(seen | {n["file"] for n, _ in picked}))
105
+ except Exception:
106
+ pass
107
+ return 0
108
+
109
+
110
+ if __name__ == "__main__":
111
+ sys.exit(main())
@@ -0,0 +1,62 @@
1
+ """UserPromptSubmit hook: suggest the skills and agents that fit the request.
2
+
3
+ The user never picks a folder or names a tool. A routing table (~/.raynsis-concierge/routing.json) maps phrases to skills
4
+ and agents; when a phrase appears in the prompt the match is written into the context, so the model sees it before
5
+ it answers. At most three suggestions, each logged with the phrase that triggered it.
6
+
7
+ Routing table entry: {"name": "invoice-chaser", "kind": "skill", "phrases": ["overdue invoice", "chase payment"]}
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+
13
+ from ..common import base_dir, load_json, log, read_event
14
+
15
+ MAX_SUGGESTIONS = 3
16
+
17
+
18
+ def match(prompt: str, table: list) -> list:
19
+ """Entries whose phrase occurs in the prompt, longest matching phrase first (a longer phrase is a more specific hit)."""
20
+ text = " " + " ".join((prompt or "").casefold().split()) + " "
21
+ hits = []
22
+ for entry in table:
23
+ if not isinstance(entry, dict) or not entry.get("name"):
24
+ continue
25
+ best = ""
26
+ for phrase in entry.get("phrases") or []:
27
+ p = " ".join(str(phrase).casefold().split())
28
+ if p and p in text and len(p) > len(best):
29
+ best = p
30
+ if best:
31
+ hits.append((len(best), entry, best))
32
+ hits.sort(key=lambda h: -h[0])
33
+ return [(e, p) for _, e, p in hits[:MAX_SUGGESTIONS]]
34
+
35
+
36
+ def render(hits: list) -> str:
37
+ lines = ["Routing (raynsis-concierge): this request matches the following tools."]
38
+ for entry, phrase in hits:
39
+ kind = "agent" if entry.get("kind") == "agent" else "skill"
40
+ lines.append(f'- `{entry["name"]}` ({kind}) · matched phrase: "{phrase}"')
41
+ lines.append("Use them if they fit the job. Not using one is your call; no need to explain it.")
42
+ return "\n".join(lines)
43
+
44
+
45
+ def main() -> int:
46
+ try:
47
+ event = read_event()
48
+ prompt = str(event.get("prompt") or "")
49
+ if not prompt.strip() or prompt.lstrip().startswith("/"):
50
+ return 0
51
+ table = load_json(base_dir() / "routing.json", [])
52
+ hits = match(prompt, table if isinstance(table, list) else [])
53
+ if hits:
54
+ print(render(hits))
55
+ log("route", {"session": event.get("session_id"), "suggested": [e["name"] for e, _ in hits], "phrases": [p for _, p in hits]})
56
+ except Exception:
57
+ pass
58
+ return 0
59
+
60
+
61
+ if __name__ == "__main__":
62
+ sys.exit(main())
@@ -0,0 +1,53 @@
1
+ """UserPromptSubmit hook: name each session after its work, not after its folder.
2
+
3
+ When every session starts in the home directory, the folder name tells you nothing. This hook derives a topic of
4
+ up to three words from the first prompt (no model call), stores it in ~/.raynsis-concierge/sessions/<id>.json and keeps the
5
+ last prompt time fresh. `raynsis-concierge sessions` lists them with the command that reopens each one.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ import time
11
+ from collections import Counter
12
+
13
+ from ..common import base_dir, load_json, read_event, save_json, words
14
+
15
+ MAX_WORDS = 3
16
+
17
+
18
+ def topic(prompt: str) -> str:
19
+ """Up to three content words: the most repeated first, ties in order of appearance."""
20
+ ws = words(prompt)
21
+ if not ws:
22
+ return "untitled"
23
+ count = Counter(ws)
24
+ first = {w: i for i, w in reversed(list(enumerate(ws)))}
25
+ chosen = sorted(count, key=lambda w: (-count[w], first[w]))[:MAX_WORDS]
26
+ chosen.sort(key=lambda w: first[w])
27
+ return " ".join(chosen)
28
+
29
+
30
+ def main() -> int:
31
+ try:
32
+ event = read_event()
33
+ session = str(event.get("session_id") or "")
34
+ prompt = str(event.get("prompt") or "")
35
+ if not session or not prompt.strip():
36
+ return 0
37
+ path = base_dir() / "sessions" / f"{session}.json"
38
+ record = load_json(path, {})
39
+ if not isinstance(record, dict):
40
+ record = {}
41
+ if not record.get("topic") and not prompt.lstrip().startswith("/"):
42
+ record["topic"] = topic(prompt)
43
+ record["started"] = time.strftime("%Y-%m-%dT%H:%M:%S")
44
+ record.update({"session": session, "cwd": event.get("cwd"), "last": time.strftime("%Y-%m-%dT%H:%M:%S"),
45
+ "prompts": int(record.get("prompts") or 0) + 1})
46
+ save_json(path, record)
47
+ except Exception:
48
+ pass
49
+ return 0
50
+
51
+
52
+ if __name__ == "__main__":
53
+ sys.exit(main())
@@ -0,0 +1,22 @@
1
+ # CLAUDE.md · home directory router
2
+
3
+ This file is loaded in every session started from the home directory. Keep it short: it is paid for on every turn.
4
+ It tells the assistant what lives where, so you never have to open a folder yourself.
5
+
6
+ ## Where things are
7
+
8
+ ~/work/company-a main business (invoices, customers, stock)
9
+ ~/work/site website; publish only with ./publish.sh
10
+ ~/notes personal notes
11
+
12
+ If a folder has its own CLAUDE.md, read that one before working there.
13
+
14
+ ## How to work
15
+
16
+ - I state the job in plain words. Find the folder, the file and the tool yourself; do not ask me which folder.
17
+ - Before saying something does not exist, search the memory notes (`raynsis-concierge search <words>`).
18
+ - Never start a file search at the home directory; name the folder.
19
+
20
+ ## Wait for me before
21
+
22
+ - deleting anything, spending money, or sending anything to another person
@@ -0,0 +1,6 @@
1
+ [
2
+ {"name": "invoice-chaser", "kind": "skill", "phrases": ["overdue invoice", "chase payment", "who owes us"]},
3
+ {"name": "customer-reply", "kind": "skill", "phrases": ["reply to the customer", "draft a response", "complaint"]},
4
+ {"name": "site-publish", "kind": "skill", "phrases": ["publish the site", "update the landing page"]},
5
+ {"name": "lawyer", "kind": "agent", "phrases": ["contract", "legal notice", "terms of service"]}
6
+ ]
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: raynsis-concierge
3
+ Version: 0.1.0
4
+ Summary: Run Claude Code from your home directory: no project folder to pick. Prompt routing, memory recall and guard rails as plain Python hooks.
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 Concierge
13
+
14
+ **Open one terminal. Say what you need. No project folder, no setup per task.**
15
+
16
+ raynsis-concierge turns Claude Code into a single home-directory assistant. You start `claude` in your home directory and
17
+ state the job in plain words. Four small hooks do the rest:
18
+
19
+ | Hook | When it runs | What it does |
20
+ |---|---|---|
21
+ | `route_prompt` | every prompt | Finds the skills and agents whose trigger phrases appear in your request and puts them in front of the model. |
22
+ | `memory_recall` | every prompt | Adds the memory notes that match the request: at most 2 notes and 700 characters, once per session, every decision logged. |
23
+ | `session_topic` | every prompt | Names the session after the work (three words, no model call) so you can find and reopen it later. |
24
+ | `guard_home_glob` | before a file search | Stops a search rooted at the home directory before it walks every folder you own. |
25
+
26
+ Pure Python standard library. No database, no model calls, no network.
27
+
28
+ ## Install
29
+
30
+ ```
31
+ pip install raynsis-concierge
32
+ raynsis-concierge install
33
+ raynsis-concierge doctor
34
+ ```
35
+
36
+ `install` backs up `~/.claude/settings.json`, adds four hook entries and leaves every other setting alone.
37
+ `raynsis-concierge undo` removes them again. `doctor` prints what it found and what is missing.
38
+
39
+ Then:
40
+
41
+ 1. Edit `~/.raynsis-concierge/routing.json`: one entry per skill or agent, with the phrases that should trigger it.
42
+ 2. Copy `~/.raynsis-concierge/CLAUDE.home.md` to `~/CLAUDE.md` and describe where your things live.
43
+ 3. Start `claude` in your home directory.
44
+
45
+ ## Daily use
46
+
47
+ ```
48
+ raynsis-concierge sessions
49
+ raynsis-concierge search supplier payment
50
+ ```
51
+
52
+ `sessions` lists recent sessions by topic with the command that reopens each one. `search` looks through your
53
+ memory notes with the same matcher the hook uses.
54
+
55
+ ## What "no folder" means
56
+
57
+ Your work still lives in folders. The difference is that you never choose one: the router file says what lives
58
+ where, the routing table says which tool fits which request, and memory notes carry what was decided before.
59
+ The assistant navigates; you describe the job.
60
+
61
+ ## Measured, not assumed
62
+
63
+ Every hook appends one JSON line per decision to `~/.raynsis-concierge/log/`. Memory recall is strict on purpose: a
64
+ recalled note costs context on every later turn. In the system this was extracted from, loosening the matcher
65
+ to one shared word made 41% of recalled notes irrelevant on 179 real prompts; requiring two brought it to 8%.
66
+ Read your own log before changing the thresholds.
67
+
68
+ ## Limits
69
+
70
+ - Tested on macOS with Python 3.9. Linux should work; Windows is not tested yet.
71
+ - The memory directory name is derived from the working directory the way Claude Code does it today. If that
72
+ changes, set `"memory_dir"` in `~/.raynsis-concierge/config.json`.
73
+ - Hooks fail open: if one breaks, your prompt still goes through.
74
+
75
+ ## Tests
76
+
77
+ ```
78
+ python -m unittest discover tests
79
+ ```
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ NOTICE
3
+ README.md
4
+ pyproject.toml
5
+ raynsis_concierge/__init__.py
6
+ raynsis_concierge/cli.py
7
+ raynsis_concierge/common.py
8
+ raynsis_concierge.egg-info/PKG-INFO
9
+ raynsis_concierge.egg-info/SOURCES.txt
10
+ raynsis_concierge.egg-info/dependency_links.txt
11
+ raynsis_concierge.egg-info/entry_points.txt
12
+ raynsis_concierge.egg-info/top_level.txt
13
+ raynsis_concierge/hooks/__init__.py
14
+ raynsis_concierge/hooks/guard_home_glob.py
15
+ raynsis_concierge/hooks/memory_recall.py
16
+ raynsis_concierge/hooks/route_prompt.py
17
+ raynsis_concierge/hooks/session_topic.py
18
+ raynsis_concierge/templates/CLAUDE.home.md
19
+ raynsis_concierge/templates/routing.example.json
20
+ tests/test_concierge.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ raynsis-concierge = raynsis_concierge.cli:main
@@ -0,0 +1 @@
1
+ raynsis_concierge
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,146 @@
1
+ import io
2
+ import json
3
+ import os
4
+ import sys
5
+ import tempfile
6
+ import unittest
7
+ from contextlib import redirect_stderr, redirect_stdout
8
+ from pathlib import Path
9
+ from unittest import mock
10
+
11
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
12
+
13
+ from raynsis_concierge import cli # noqa: E402
14
+ from raynsis_concierge.hooks import guard_home_glob, memory_recall, route_prompt, session_topic # noqa: E402
15
+
16
+
17
+ def run(module, event, env):
18
+ out, err = io.StringIO(), io.StringIO()
19
+ with mock.patch.dict(os.environ, env), mock.patch("sys.stdin", io.StringIO(json.dumps(event))), redirect_stdout(out), redirect_stderr(err):
20
+ code = module.main()
21
+ return code, out.getvalue(), err.getvalue()
22
+
23
+
24
+ class Base(unittest.TestCase):
25
+ def setUp(self):
26
+ self.tmp = tempfile.TemporaryDirectory()
27
+ self.root = Path(self.tmp.name)
28
+ self.env = {"RAYNSIS_CONCIERGE_HOME": str(self.root / "hr"), "CLAUDE_CONFIG_DIR": str(self.root / "claude"), "HOME": str(self.root / "home"), "USERPROFILE": str(self.root / "home")}
29
+ (self.root / "home").mkdir()
30
+ (self.root / "hr").mkdir()
31
+
32
+ def tearDown(self):
33
+ self.tmp.cleanup()
34
+
35
+
36
+ class Route(Base):
37
+ def test_suggests_matching_tool_and_logs_it(self):
38
+ (self.root / "hr" / "routing.json").write_text(json.dumps([
39
+ {"name": "invoice-chaser", "kind": "skill", "phrases": ["overdue invoice"]},
40
+ {"name": "lawyer", "kind": "agent", "phrases": ["contract"]}]))
41
+ code, out, _ = run(route_prompt, {"prompt": "Who has an OVERDUE invoice this week?", "session_id": "s1"}, self.env)
42
+ self.assertEqual(code, 0)
43
+ self.assertIn("`invoice-chaser` (skill)", out)
44
+ self.assertNotIn("lawyer", out)
45
+ self.assertEqual(json.loads((self.root / "hr/log/route.jsonl").read_text().splitlines()[0])["suggested"], ["invoice-chaser"])
46
+
47
+ def test_silent_without_match_table_or_on_slash_command(self):
48
+ self.assertEqual(run(route_prompt, {"prompt": "hello"}, self.env)[1], "")
49
+ (self.root / "hr" / "routing.json").write_text("not json")
50
+ self.assertEqual(run(route_prompt, {"prompt": "contract"}, self.env)[:2], (0, ""))
51
+ (self.root / "hr" / "routing.json").write_text(json.dumps([{"name": "x", "phrases": ["help"]}]))
52
+ self.assertEqual(run(route_prompt, {"prompt": "/help"}, self.env)[1], "")
53
+
54
+ def test_at_most_three_most_specific_first(self):
55
+ table = [{"name": f"t{i}", "phrases": ["pay" + "x" * i]} for i in range(5)]
56
+ hits = route_prompt.match("pay payx payxx payxxx payxxxx", table)
57
+ self.assertEqual([e["name"] for e, _ in hits], ["t4", "t3", "t2"])
58
+
59
+
60
+ class Recall(Base):
61
+ def notes(self):
62
+ d = self.root / "claude" / "projects" / memory_recall.encode_cwd("/Users/me") / "memory"
63
+ d.mkdir(parents=True)
64
+ (d / "supplier_terms.md").write_text("---\nname: supplier-payment-terms\ndescription: Supplier invoices are paid on day 45\n---\nAgreed in March.")
65
+ (d / "holiday.md").write_text("---\nname: holiday-plan\ndescription: Office closed first week of August\n---\n")
66
+ (d / "MEMORY.md").write_text("index")
67
+ return d
68
+
69
+ def test_recalls_only_notes_sharing_two_words_once_per_session(self):
70
+ self.notes()
71
+ event = {"prompt": "When do we pay the supplier invoices?", "cwd": "/Users/me", "session_id": "s1"}
72
+ code, out, _ = run(memory_recall, event, self.env)
73
+ self.assertEqual(code, 0)
74
+ self.assertIn("supplier-payment-terms", out)
75
+ self.assertNotIn("holiday", out)
76
+ self.assertEqual(run(memory_recall, event, self.env)[1], "") # same session: not repeated
77
+ self.assertIn("supplier", run(memory_recall, {**event, "session_id": "s2"}, self.env)[1])
78
+
79
+ def test_one_shared_word_is_not_enough_and_budget_is_kept(self):
80
+ self.notes()
81
+ self.assertEqual(run(memory_recall, {"prompt": "Is the office open?", "cwd": "/Users/me", "session_id": "s3"}, self.env)[1], "")
82
+ big = [({"name": "n", "description": "d" * 2000, "body": "", "file": "n.md"}, [])]
83
+ self.assertLessEqual(len(memory_recall.render(big).splitlines()[1]), memory_recall.MAX_CHARS + len(" (n.md)"))
84
+
85
+ def test_path_encoding_matches_claude_code(self):
86
+ self.assertEqual(memory_recall.encode_cwd("/Users/jane.doe/my work"), "-Users-jane-doe-my-work")
87
+
88
+
89
+ class Guard(Base):
90
+ def glob(self, tool_input, cwd=None):
91
+ home = str((self.root / "home").resolve())
92
+ return run(guard_home_glob, {"tool_name": "Glob", "cwd": cwd or home, "tool_input": tool_input}, self.env)
93
+
94
+ def test_denies_search_rooted_at_home_or_above(self):
95
+ (self.root / "home" / "work").mkdir()
96
+ code, _, err = self.glob({"pattern": "work/**/*.md"})
97
+ self.assertEqual(code, 2)
98
+ self.assertIn("work", err)
99
+ self.assertEqual(self.glob({"pattern": "**/*.md", "path": "/"})[0], 2)
100
+ self.assertEqual(self.glob({"pattern": "~/**/notes.md"})[0], 2)
101
+
102
+ def test_allows_search_inside_a_folder_and_other_tools(self):
103
+ (self.root / "home" / "work").mkdir()
104
+ self.assertEqual(self.glob({"pattern": "**/*.md", "path": str(self.root / "home" / "work")})[0], 0)
105
+ self.assertEqual(self.glob({"pattern": "~/work/**/*.md"})[0], 0)
106
+ self.assertEqual(run(guard_home_glob, {"tool_name": "Read", "tool_input": {}}, self.env)[0], 0)
107
+
108
+
109
+ class Topic(Base):
110
+ def test_topic_is_three_content_words_and_survives_later_prompts(self):
111
+ t = session_topic.topic("chase overdue invoice; the invoice is three weeks overdue")
112
+ self.assertEqual(len(t.split()), 3)
113
+ self.assertIn("invoice", t)
114
+ run(session_topic, {"prompt": "chase the overdue invoice", "session_id": "abc", "cwd": "/Users/me"}, self.env)
115
+ run(session_topic, {"prompt": "now something else entirely", "session_id": "abc", "cwd": "/Users/me"}, self.env)
116
+ rec = json.loads((self.root / "hr/sessions/abc.json").read_text())
117
+ self.assertEqual((rec["topic"], rec["prompts"]), ("chase overdue invoice", 2))
118
+ self.assertEqual(session_topic.topic("???"), "untitled")
119
+
120
+
121
+ class Install(Base):
122
+ def test_install_keeps_other_hooks_takes_backup_and_undo_restores(self):
123
+ settings = self.root / "claude" / "settings.json"
124
+ settings.parent.mkdir(parents=True)
125
+ mine = {"model": "x", "hooks": {"Stop": [{"hooks": [{"type": "command", "command": "echo mine"}]}]}}
126
+ settings.write_text(json.dumps(mine))
127
+ with mock.patch.dict(os.environ, self.env), redirect_stdout(io.StringIO()):
128
+ self.assertEqual(cli.main(["install"]), 0)
129
+ self.assertEqual(cli.main(["install"]), 0) # twice: no duplicates
130
+ now = json.loads(settings.read_text())
131
+ self.assertEqual(len(cli.installed(now)), len(cli.HOOKS))
132
+ self.assertEqual(now["hooks"]["Stop"], mine["hooks"]["Stop"])
133
+ self.assertTrue(list(settings.parent.glob("settings.json.raynsis-concierge-backup-*")))
134
+ self.assertTrue((self.root / "hr" / "routing.json").exists())
135
+ self.assertEqual(cli.main(["undo"]), 0)
136
+ self.assertEqual(json.loads(settings.read_text()), mine)
137
+
138
+ def test_doctor_reports_missing_install(self):
139
+ out = io.StringIO()
140
+ with mock.patch.dict(os.environ, self.env), redirect_stdout(out):
141
+ self.assertEqual(cli.main(["doctor"]), 1)
142
+ self.assertIn("missing hooks", out.getvalue())
143
+
144
+
145
+ if __name__ == "__main__":
146
+ unittest.main()