hidden-moves-workspace 0.1.0a2__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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ella Inng
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.4
2
+ Name: hidden-moves-workspace
3
+ Version: 0.1.0a2
4
+ Summary: Bounded typed context over explicitly selected local text files.
5
+ Keywords: workspace,context,capabilities,plugins,agents
6
+ Author: Ella Inng
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Requires-Dist: hidden-moves-mcp>=0.1,<0.2 ; extra == 'host'
16
+ Requires-Dist: hidden-moves>=0.1.1,<0.2 ; extra == 'moves'
17
+ Maintainer: wispsy
18
+ Requires-Python: >=3.11
19
+ Project-URL: Homepage, https://github.com/wispsy/hidden_moves
20
+ Project-URL: Source, https://github.com/wispsy/hidden_moves
21
+ Project-URL: Issues, https://github.com/wispsy/hidden_moves/issues
22
+ Project-URL: Documentation, https://github.com/wispsy/hidden_moves/blob/main/packages/hidden-moves-workspace/README.md
23
+ Provides-Extra: host
24
+ Provides-Extra: moves
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Workspace context
28
+
29
+ Bounded context over an exact selection of local UTF-8 text files. The ordinary
30
+ Python client uses only the standard library and does not import Hidden Moves.
31
+ This package is experimental and source-only; no package publication is implied.
32
+
33
+ ```python
34
+ from hidden_moves_workspace import Workspace
35
+
36
+ workspace = Workspace("/path/to/project", ["README.md", "src/example.py"])
37
+ paths = workspace.files(limit=20)
38
+ page = workspace.search("src/example.py", "def ", max_matches=5)
39
+ excerpt = workspace.read("src/example.py", start_line=1, line_count=30)
40
+ ```
41
+
42
+ Configuration fixes the canonical root, exact relative-file selection, and
43
+ `max_file_bytes` (262,144 by default; at most 1,048,576). At most 512 path entries
44
+ are accepted. Paths use forward slashes. No globbing, recursive directory scan,
45
+ or implicit hidden-file selection occurs. `files` lists the declared selection,
46
+ including files that may currently be missing; it does not inspect content.
47
+ Construction resolves the root but does not open selected files.
48
+
49
+ `read` returns the path, SHA-256 of the raw bytes read, total line count, numbered
50
+ text fragments, and `next_line`/`next_column`. Each call returns at most 200 lines
51
+ and 16,384 text characters. A long physical line continues at the reported
52
+ column. Line and column numbers start at one; columns count Unicode characters.
53
+ Python `str.splitlines()` defines lines; line-ending characters are omitted.
54
+ An empty file returns no lines. Starting one line beyond EOF returns an empty
55
+ completed excerpt; positions beyond that are rejected.
56
+
57
+ `search` is case-sensitive literal search within one selected file, with one
58
+ match per matching line. It returns at most 100 matches, 320-character previews,
59
+ and an explicit `next_line` when further matches exist. Follow that position
60
+ rather than assuming a page contains all matches. An empty result with no next
61
+ position means no matches remain in that file from the requested start.
62
+
63
+ For either operation, pass the prior `sha256` as `expected_sha256` on continuation
64
+ to reject content changes with `StaleContentError`. Digests describe the bytes
65
+ actually read, not a transactional snapshot across files or concurrent edits.
66
+
67
+ Absolute paths, traversal, unselected paths, symlink/reparse components,
68
+ non-regular files, invalid UTF-8, NUL content, oversized files, and invalid bounds
69
+ are rejected. Exceptions do not echo absolute host paths or file content.
70
+ Explicit selection is trusted configuration: it can intentionally include
71
+ sensitive files, so configure it only with content appropriate for the consumer.
72
+ These checks reduce accidental escapes; this local library is not an OS sandbox
73
+ against hostile concurrent filesystem replacement, hard links, or mount changes.
74
+
75
+ The client never writes files, invokes commands, or accesses a network. Importing
76
+ `hidden_moves_workspace` does not import Hidden Moves or a protocol adapter.
77
+
78
+ ## Install and inspect the provider
79
+
80
+ From the repository checkout, install the local packages into your environment:
81
+
82
+ ```sh
83
+ uv pip install . ./packages/hidden-moves-mcp ./packages/hidden-moves-openai \
84
+ './packages/hidden-moves-workspace[host]'
85
+ hidden-moves plugins list
86
+ hidden-moves --plugin workspace moves show workspace.read
87
+ ```
88
+
89
+ The ordinary package has no mandatory dependencies. The `[moves]` extra enables
90
+ the provider and configured JSON CLI; `[host]` also enables local MCP. The
91
+ function-tool adapter is installed separately. Discovery and unbound inspection
92
+ do not open selected files, and the generic CLI cannot infer a workspace target.
93
+
94
+ The installed `workspace` provider advertises `workspace.files`, `workspace.read`,
95
+ and `workspace.search`. They are target-bound wrappers, annotated read-only,
96
+ non-destructive, and idempotent. Their external-system hint reflects the mutable
97
+ local filesystem, not network access. Hints do not authorize exposure.
98
+
99
+ ## Configured CLI and local MCP
100
+
101
+ Run a useful read-only context workflow from a checkout:
102
+
103
+ ```sh
104
+ hidden-moves-workspace --root . --file README.md --file src/hidden_moves/core/moves.py \
105
+ --move workspace.files call workspace.files
106
+ hidden-moves-workspace --root . --file src/hidden_moves/core/moves.py \
107
+ --move workspace.search call workspace.search \
108
+ --arguments '{"path":"src/hidden_moves/core/moves.py","query":"def learn","max_matches":3}'
109
+ hidden-moves-workspace --root . --file src/hidden_moves/core/moves.py \
110
+ --move workspace.read call workspace.read \
111
+ --arguments '{"path":"src/hidden_moves/core/moves.py","start_line":1,"line_count":12}'
112
+ ```
113
+
114
+ `--root`, repeated `--file`, and repeated `--move` are required; no root, file,
115
+ or capability is selected by default. `--max-file-bytes` can lower the content
116
+ ceiling. Only selected moves can dispatch. The CLI prints validated finite JSON;
117
+ input and domain errors exit with status 2 and omit host paths/content.
118
+
119
+ For a local MCP client, launch the same executable with `serve`:
120
+
121
+ ```sh
122
+ hidden-moves-workspace --root /absolute/project --file README.md \
123
+ --move workspace.files --move workspace.read --move workspace.search serve
124
+ ```
125
+
126
+ Use these tokens as the client's executable/argument array. Configuration belongs
127
+ to the local host, outside tool arguments. The server serves the selected catalog
128
+ over stdio and offloads synchronous reads from its event loop. Startup emits no
129
+ application output to stdout. MCP failures identify the exception type without
130
+ leaking file content; `StaleContentError` means restart from current content.
131
+
132
+ This is a Python entry-point plugin and local MCP host. It does not create a
133
+ hosted marketplace package, remote identity service, or public endpoint.
134
+
135
+ ## Python composition and offline function tools
136
+
137
+ ```python
138
+ import asyncio
139
+ import json
140
+
141
+ from hidden_moves_openai import FunctionToolAdapter
142
+ from hidden_moves_workspace import Workspace
143
+ from hidden_moves_workspace.host import build_catalog
144
+
145
+ workspace = Workspace("/path/to/project", ["README.md"])
146
+ catalog = build_catalog(workspace, ["workspace.read"])
147
+ arguments = {"path": "README.md", "line_count": 12}
148
+ value = catalog.serialize_result("workspace.read", catalog.invoke("workspace.read", arguments))
149
+ functions = FunctionToolAdapter(catalog)
150
+ assert json.loads(asyncio.run(functions.call("workspace__read", arguments))) == value
151
+ ```
152
+
153
+ `functions.tools()` exports tool definitions. Offline dispatch makes no model API
154
+ call. Defaults retain ordinary Python omission semantics; the adapter's default
155
+ `strict=False` preserves these optional arguments. For MCP in an application,
156
+ pass the same catalog to `MCPAdapter` from `hidden_moves_mcp`.
157
+
158
+ ## Verification
159
+
160
+ ```sh
161
+ PYTHONPATH=packages/hidden-moves-workspace/src python -S -m unittest discover \
162
+ -s packages/hidden-moves-workspace/tests -v
163
+ python -m unittest discover -s packages/hidden-moves-workspace/integration_tests -v
164
+ ```
165
+
166
+ Integration tests use synthetic temporary files and compare Python, catalog,
167
+ MCP, and function-tool results. Actual stdio tests start the installed module,
168
+ initialize a client, list/call tools, continue pages, and reject unselected moves.
@@ -0,0 +1,142 @@
1
+ # Workspace context
2
+
3
+ Bounded context over an exact selection of local UTF-8 text files. The ordinary
4
+ Python client uses only the standard library and does not import Hidden Moves.
5
+ This package is experimental and source-only; no package publication is implied.
6
+
7
+ ```python
8
+ from hidden_moves_workspace import Workspace
9
+
10
+ workspace = Workspace("/path/to/project", ["README.md", "src/example.py"])
11
+ paths = workspace.files(limit=20)
12
+ page = workspace.search("src/example.py", "def ", max_matches=5)
13
+ excerpt = workspace.read("src/example.py", start_line=1, line_count=30)
14
+ ```
15
+
16
+ Configuration fixes the canonical root, exact relative-file selection, and
17
+ `max_file_bytes` (262,144 by default; at most 1,048,576). At most 512 path entries
18
+ are accepted. Paths use forward slashes. No globbing, recursive directory scan,
19
+ or implicit hidden-file selection occurs. `files` lists the declared selection,
20
+ including files that may currently be missing; it does not inspect content.
21
+ Construction resolves the root but does not open selected files.
22
+
23
+ `read` returns the path, SHA-256 of the raw bytes read, total line count, numbered
24
+ text fragments, and `next_line`/`next_column`. Each call returns at most 200 lines
25
+ and 16,384 text characters. A long physical line continues at the reported
26
+ column. Line and column numbers start at one; columns count Unicode characters.
27
+ Python `str.splitlines()` defines lines; line-ending characters are omitted.
28
+ An empty file returns no lines. Starting one line beyond EOF returns an empty
29
+ completed excerpt; positions beyond that are rejected.
30
+
31
+ `search` is case-sensitive literal search within one selected file, with one
32
+ match per matching line. It returns at most 100 matches, 320-character previews,
33
+ and an explicit `next_line` when further matches exist. Follow that position
34
+ rather than assuming a page contains all matches. An empty result with no next
35
+ position means no matches remain in that file from the requested start.
36
+
37
+ For either operation, pass the prior `sha256` as `expected_sha256` on continuation
38
+ to reject content changes with `StaleContentError`. Digests describe the bytes
39
+ actually read, not a transactional snapshot across files or concurrent edits.
40
+
41
+ Absolute paths, traversal, unselected paths, symlink/reparse components,
42
+ non-regular files, invalid UTF-8, NUL content, oversized files, and invalid bounds
43
+ are rejected. Exceptions do not echo absolute host paths or file content.
44
+ Explicit selection is trusted configuration: it can intentionally include
45
+ sensitive files, so configure it only with content appropriate for the consumer.
46
+ These checks reduce accidental escapes; this local library is not an OS sandbox
47
+ against hostile concurrent filesystem replacement, hard links, or mount changes.
48
+
49
+ The client never writes files, invokes commands, or accesses a network. Importing
50
+ `hidden_moves_workspace` does not import Hidden Moves or a protocol adapter.
51
+
52
+ ## Install and inspect the provider
53
+
54
+ From the repository checkout, install the local packages into your environment:
55
+
56
+ ```sh
57
+ uv pip install . ./packages/hidden-moves-mcp ./packages/hidden-moves-openai \
58
+ './packages/hidden-moves-workspace[host]'
59
+ hidden-moves plugins list
60
+ hidden-moves --plugin workspace moves show workspace.read
61
+ ```
62
+
63
+ The ordinary package has no mandatory dependencies. The `[moves]` extra enables
64
+ the provider and configured JSON CLI; `[host]` also enables local MCP. The
65
+ function-tool adapter is installed separately. Discovery and unbound inspection
66
+ do not open selected files, and the generic CLI cannot infer a workspace target.
67
+
68
+ The installed `workspace` provider advertises `workspace.files`, `workspace.read`,
69
+ and `workspace.search`. They are target-bound wrappers, annotated read-only,
70
+ non-destructive, and idempotent. Their external-system hint reflects the mutable
71
+ local filesystem, not network access. Hints do not authorize exposure.
72
+
73
+ ## Configured CLI and local MCP
74
+
75
+ Run a useful read-only context workflow from a checkout:
76
+
77
+ ```sh
78
+ hidden-moves-workspace --root . --file README.md --file src/hidden_moves/core/moves.py \
79
+ --move workspace.files call workspace.files
80
+ hidden-moves-workspace --root . --file src/hidden_moves/core/moves.py \
81
+ --move workspace.search call workspace.search \
82
+ --arguments '{"path":"src/hidden_moves/core/moves.py","query":"def learn","max_matches":3}'
83
+ hidden-moves-workspace --root . --file src/hidden_moves/core/moves.py \
84
+ --move workspace.read call workspace.read \
85
+ --arguments '{"path":"src/hidden_moves/core/moves.py","start_line":1,"line_count":12}'
86
+ ```
87
+
88
+ `--root`, repeated `--file`, and repeated `--move` are required; no root, file,
89
+ or capability is selected by default. `--max-file-bytes` can lower the content
90
+ ceiling. Only selected moves can dispatch. The CLI prints validated finite JSON;
91
+ input and domain errors exit with status 2 and omit host paths/content.
92
+
93
+ For a local MCP client, launch the same executable with `serve`:
94
+
95
+ ```sh
96
+ hidden-moves-workspace --root /absolute/project --file README.md \
97
+ --move workspace.files --move workspace.read --move workspace.search serve
98
+ ```
99
+
100
+ Use these tokens as the client's executable/argument array. Configuration belongs
101
+ to the local host, outside tool arguments. The server serves the selected catalog
102
+ over stdio and offloads synchronous reads from its event loop. Startup emits no
103
+ application output to stdout. MCP failures identify the exception type without
104
+ leaking file content; `StaleContentError` means restart from current content.
105
+
106
+ This is a Python entry-point plugin and local MCP host. It does not create a
107
+ hosted marketplace package, remote identity service, or public endpoint.
108
+
109
+ ## Python composition and offline function tools
110
+
111
+ ```python
112
+ import asyncio
113
+ import json
114
+
115
+ from hidden_moves_openai import FunctionToolAdapter
116
+ from hidden_moves_workspace import Workspace
117
+ from hidden_moves_workspace.host import build_catalog
118
+
119
+ workspace = Workspace("/path/to/project", ["README.md"])
120
+ catalog = build_catalog(workspace, ["workspace.read"])
121
+ arguments = {"path": "README.md", "line_count": 12}
122
+ value = catalog.serialize_result("workspace.read", catalog.invoke("workspace.read", arguments))
123
+ functions = FunctionToolAdapter(catalog)
124
+ assert json.loads(asyncio.run(functions.call("workspace__read", arguments))) == value
125
+ ```
126
+
127
+ `functions.tools()` exports tool definitions. Offline dispatch makes no model API
128
+ call. Defaults retain ordinary Python omission semantics; the adapter's default
129
+ `strict=False` preserves these optional arguments. For MCP in an application,
130
+ pass the same catalog to `MCPAdapter` from `hidden_moves_mcp`.
131
+
132
+ ## Verification
133
+
134
+ ```sh
135
+ PYTHONPATH=packages/hidden-moves-workspace/src python -S -m unittest discover \
136
+ -s packages/hidden-moves-workspace/tests -v
137
+ python -m unittest discover -s packages/hidden-moves-workspace/integration_tests -v
138
+ ```
139
+
140
+ Integration tests use synthetic temporary files and compare Python, catalog,
141
+ MCP, and function-tool results. Actual stdio tests start the installed module,
142
+ initialize a client, list/call tools, continue pages, and reject unselected moves.
@@ -0,0 +1,53 @@
1
+ [project]
2
+ name = "hidden-moves-workspace"
3
+ version = "0.1.0a2"
4
+ description = "Bounded typed context over explicitly selected local text files."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ keywords = [
10
+ "workspace",
11
+ "context",
12
+ "capabilities",
13
+ "plugins",
14
+ "agents",
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ ]
24
+ dependencies = []
25
+
26
+ [[project.authors]]
27
+ name = "Ella Inng"
28
+
29
+ [[project.maintainers]]
30
+ name = "wispsy"
31
+
32
+ [project.optional-dependencies]
33
+ moves = ["hidden-moves>=0.1.1,<0.2"]
34
+ host = ["hidden-moves-mcp>=0.1,<0.2"]
35
+
36
+ [project.entry-points."hidden_moves.moves"]
37
+ workspace = "hidden_moves_workspace.integration:provide_moves"
38
+
39
+ [project.scripts]
40
+ hidden-moves-workspace = "hidden_moves_workspace.host:main"
41
+
42
+ [project.urls]
43
+ Homepage = "https://github.com/wispsy/hidden_moves"
44
+ Source = "https://github.com/wispsy/hidden_moves"
45
+ Issues = "https://github.com/wispsy/hidden_moves/issues"
46
+ Documentation = "https://github.com/wispsy/hidden_moves/blob/main/packages/hidden-moves-workspace/README.md"
47
+
48
+ [build-system]
49
+ requires = ["uv_build>=0.12.1,<0.13.0"]
50
+ build-backend = "uv_build"
51
+
52
+ [tool.uv.build-backend]
53
+ source-exclude = ["**/.DS_Store"]
@@ -0,0 +1,43 @@
1
+ [project]
2
+ name = "hidden-moves-workspace"
3
+ version = "0.1.0a2"
4
+ description = "Bounded typed context over explicitly selected local text files."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Ella Inng" }]
10
+ maintainers = [{ name = "wispsy" }]
11
+ keywords = ["workspace", "context", "capabilities", "plugins", "agents"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Developers",
15
+ "Programming Language :: Python :: 3 :: Only",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: 3.13",
18
+ "Topic :: Software Development :: Libraries :: Python Modules",
19
+ ]
20
+ dependencies = []
21
+
22
+ [project.optional-dependencies]
23
+ moves = ["hidden-moves>=0.1.1,<0.2"]
24
+ host = ["hidden-moves-mcp>=0.1,<0.2"]
25
+
26
+ [project.entry-points."hidden_moves.moves"]
27
+ workspace = "hidden_moves_workspace.integration:provide_moves"
28
+
29
+ [project.scripts]
30
+ hidden-moves-workspace = "hidden_moves_workspace.host:main"
31
+
32
+ [project.urls]
33
+ Homepage = "https://github.com/wispsy/hidden_moves"
34
+ Source = "https://github.com/wispsy/hidden_moves"
35
+ Issues = "https://github.com/wispsy/hidden_moves/issues"
36
+ Documentation = "https://github.com/wispsy/hidden_moves/blob/main/packages/hidden-moves-workspace/README.md"
37
+
38
+ [build-system]
39
+ requires = ["uv_build>=0.12.1,<0.13.0"]
40
+ build-backend = "uv_build"
41
+
42
+ [tool.uv.build-backend]
43
+ source-exclude = ["**/.DS_Store"]
@@ -0,0 +1,10 @@
1
+ """Bounded workspace context, usable without Hidden Moves or its adapters."""
2
+
3
+ from .client import Workspace
4
+ from .errors import ContentError, PathAccessError, StaleContentError, WorkspaceError
5
+ from .models import Excerpt, FilePage, SearchMatch, SearchPage, TextLine
6
+
7
+ __all__ = [
8
+ "ContentError", "Excerpt", "FilePage", "PathAccessError", "SearchMatch",
9
+ "SearchPage", "StaleContentError", "TextLine", "Workspace", "WorkspaceError",
10
+ ]
@@ -0,0 +1,6 @@
1
+ """Run the explicitly configured local workspace host."""
2
+
3
+ from .host import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,189 @@
1
+ """Read-only context over an explicit, bounded file selection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ import re
8
+ import stat
9
+ from collections.abc import Iterable
10
+ from pathlib import Path
11
+
12
+ from .errors import ContentError, PathAccessError, StaleContentError
13
+ from .models import Excerpt, FilePage, SearchMatch, SearchPage, TextLine
14
+
15
+ _EXCERPT_CHARS = 16_384
16
+ _PREVIEW_CHARS = 320
17
+
18
+
19
+ def _integer(value: int, minimum: int, maximum: int, name: str) -> None:
20
+ if isinstance(value, bool) or not isinstance(value, int) or not minimum <= value <= maximum:
21
+ raise ValueError(f"{name} must be an integer between {minimum} and {maximum}.")
22
+
23
+
24
+ def _relative_path(value: str) -> str:
25
+ # One portable spelling prevents traversal and platform-specific aliases.
26
+ if (
27
+ not isinstance(value, str) or not value or len(value) > 1024
28
+ or any(char in value for char in ("\\", ":", "\x00"))
29
+ or any(ord(char) < 32 for char in value)
30
+ or any(part in ("", ".", "..") or part.endswith((" ", ".")) for part in value.split("/"))
31
+ ):
32
+ raise PathAccessError("Use a selected relative path with forward-slash separators.")
33
+ return value
34
+
35
+
36
+ def _is_link(info: os.stat_result) -> bool:
37
+ return stat.S_ISLNK(info.st_mode) or bool(
38
+ getattr(info, "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)
39
+ )
40
+
41
+
42
+ class Workspace:
43
+ """Bind trusted configuration; read selected content only when called.
44
+
45
+ Symlink checks reduce accidental escapes. This is not a filesystem sandbox
46
+ against concurrent replacement of parent directories or other hostile edits.
47
+ """
48
+
49
+ def __init__(
50
+ self, root: str | os.PathLike[str], files: Iterable[str], *, max_file_bytes: int = 262_144,
51
+ ) -> None:
52
+ _integer(max_file_bytes, 1, 1_048_576, "max_file_bytes")
53
+ if isinstance(files, (str, bytes)):
54
+ raise TypeError("files must be an iterable of relative paths.")
55
+ selected: set[str] = set()
56
+ for index, path in enumerate(files):
57
+ if index >= 512:
58
+ raise ValueError("Select at most 512 file paths.")
59
+ selected.add(_relative_path(path))
60
+ try:
61
+ location = Path(root).resolve(strict=True)
62
+ if not location.is_dir():
63
+ raise ValueError
64
+ except (OSError, RuntimeError, TypeError, ValueError):
65
+ raise PathAccessError("The configured workspace root must be an existing directory.") from None
66
+ self._root = location
67
+ self._paths = tuple(sorted(selected))
68
+ self._selected = frozenset(selected)
69
+ self._max_file_bytes = max_file_bytes
70
+
71
+ def files(self, offset: int = 0, limit: int = 100) -> FilePage:
72
+ """List declared relative paths, not a live directory scan; no content is read."""
73
+ _integer(offset, 0, len(self._paths), "offset")
74
+ _integer(limit, 1, 200, "limit")
75
+ end = min(offset + limit, len(self._paths))
76
+ return FilePage(list(self._paths[offset:end]), end if end < len(self._paths) else None)
77
+
78
+ def _read(self, path: str, expected_sha256: str | None) -> tuple[list[str], str]:
79
+ path = _relative_path(path)
80
+ if path not in self._selected:
81
+ raise PathAccessError("The path is not selected in this workspace.")
82
+ if expected_sha256 is not None and (
83
+ not isinstance(expected_sha256, str) or re.fullmatch(r"[0-9a-f]{64}", expected_sha256) is None
84
+ ):
85
+ raise ValueError("expected_sha256 must be a lowercase SHA-256 digest.")
86
+ try:
87
+ current = self._root
88
+ for part in (None, *path.split("/")):
89
+ if part is not None:
90
+ current = current / part
91
+ info = current.lstat()
92
+ if _is_link(info):
93
+ raise PathAccessError("Symlinks and reparse points are not supported.")
94
+ current.resolve(strict=True).relative_to(self._root)
95
+ if not stat.S_ISREG(info.st_mode):
96
+ raise PathAccessError("Selected content must be a regular file.")
97
+ flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)
98
+ with os.fdopen(os.open(current, flags), "rb") as stream:
99
+ opened = os.fstat(stream.fileno())
100
+ if not stat.S_ISREG(opened.st_mode):
101
+ raise PathAccessError("Selected content must be a regular file.")
102
+ if opened.st_size > self._max_file_bytes:
103
+ raise ContentError("Selected content exceeds the configured byte limit.")
104
+ data = stream.read(self._max_file_bytes + 1)
105
+ except (OSError, RuntimeError, ValueError):
106
+ raise PathAccessError("The selected file is unavailable within the configured workspace.") from None
107
+ if len(data) > self._max_file_bytes:
108
+ raise ContentError("Selected content exceeds the configured byte limit.")
109
+ digest = hashlib.sha256(data).hexdigest()
110
+ if expected_sha256 is not None and digest != expected_sha256:
111
+ raise StaleContentError("Content changed; restart the read or search using the current file.")
112
+ try:
113
+ text = data.decode("utf-8")
114
+ except UnicodeError:
115
+ raise ContentError("Selected content must be UTF-8 text.") from None
116
+ if "\x00" in text:
117
+ raise ContentError("NUL-containing content is not supported text.")
118
+ return text.splitlines(), digest
119
+
120
+ def read(
121
+ self, path: str, start_line: int = 1, line_count: int = 80,
122
+ start_column: int = 1, expected_sha256: str | None = None,
123
+ ) -> Excerpt:
124
+ """Read numbered lines, bounded to 200 lines and 16,384 text characters.
125
+
126
+ Continue with next_line/next_column and expected_sha256. Columns count
127
+ Unicode characters from one, not UTF-8 bytes; newline characters are omitted.
128
+ """
129
+ _integer(start_line, 1, 1_048_577, "start_line")
130
+ _integer(line_count, 1, 200, "line_count")
131
+ _integer(start_column, 1, 1_048_577, "start_column")
132
+ lines, digest = self._read(path, expected_sha256)
133
+ if start_line > len(lines) + 1 or (start_line > len(lines) and start_column != 1):
134
+ raise ValueError("The start position is beyond the end of the file.")
135
+ result = []
136
+ remaining = _EXCERPT_CHARS
137
+ position = start_line - 1
138
+ column = start_column - 1
139
+ while position < len(lines) and len(result) < line_count:
140
+ line = lines[position]
141
+ if column > len(line):
142
+ raise ValueError("start_column is beyond the end of the line.")
143
+ fragment = line[column:column + remaining]
144
+ result.append(TextLine(position + 1, column + 1, fragment))
145
+ remaining -= len(fragment)
146
+ column += len(fragment)
147
+ if column < len(line):
148
+ break
149
+ position += 1
150
+ column = 0
151
+ if remaining == 0:
152
+ break
153
+ has_more = position < len(lines)
154
+ return Excerpt(
155
+ path, digest, len(lines), result,
156
+ position + 1 if has_more else None, column + 1 if has_more else None,
157
+ )
158
+
159
+ def search(
160
+ self, path: str, query: str, start_line: int = 1,
161
+ max_matches: int = 20, expected_sha256: str | None = None,
162
+ ) -> SearchPage:
163
+ """Find the first case-sensitive literal occurrence on each matching line.
164
+
165
+ Return at most 100 matches with 320-character previews. Continue using
166
+ next_line and expected_sha256; a bounded page is not the whole file.
167
+ """
168
+ if not isinstance(query, str) or not 1 <= len(query) <= 256 or any(char in query for char in "\r\n\x00"):
169
+ raise ValueError("query must contain 1-256 characters without CR, LF, or NUL.")
170
+ _integer(start_line, 1, 1_048_577, "start_line")
171
+ _integer(max_matches, 1, 100, "max_matches")
172
+ lines, digest = self._read(path, expected_sha256)
173
+ if start_line > len(lines) + 1:
174
+ raise ValueError("start_line is beyond the end of the file.")
175
+ matches = []
176
+ next_line = None
177
+ for position in range(start_line - 1, len(lines)):
178
+ column = lines[position].find(query)
179
+ if column == -1:
180
+ continue
181
+ if len(matches) == max_matches:
182
+ next_line = position + 1
183
+ break
184
+ preview_start = max(0, column - 32)
185
+ matches.append(SearchMatch(
186
+ position + 1, column + 1, preview_start + 1,
187
+ lines[position][preview_start:preview_start + _PREVIEW_CHARS],
188
+ ))
189
+ return SearchPage(path, digest, len(lines), matches, next_line)
@@ -0,0 +1,17 @@
1
+ """Errors omit host paths and file content."""
2
+
3
+
4
+ class WorkspaceError(Exception):
5
+ """A configured workspace operation failed."""
6
+
7
+
8
+ class PathAccessError(WorkspaceError):
9
+ """A path is invalid, unselected, unavailable, or not a regular file."""
10
+
11
+
12
+ class ContentError(WorkspaceError):
13
+ """Selected content exceeds its budget or is not supported UTF-8 text."""
14
+
15
+
16
+ class StaleContentError(WorkspaceError):
17
+ """The content no longer matches an explicitly expected digest."""
@@ -0,0 +1,65 @@
1
+ """Explicit configuration and selection for JSON CLI and local stdio MCP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import json
8
+ from collections.abc import Iterable
9
+ from typing import TYPE_CHECKING
10
+
11
+ from .client import Workspace
12
+ from .errors import WorkspaceError
13
+
14
+ if TYPE_CHECKING:
15
+ from hidden_moves.adapters import CapabilityCatalog
16
+
17
+
18
+ def build_catalog(workspace: Workspace, names: Iterable[str]) -> CapabilityCatalog:
19
+ """Bind the configured workspace before selecting installed capabilities."""
20
+ from hidden_moves import Moves, discover_providers, load_provider
21
+ from hidden_moves.adapters import CapabilityCatalog
22
+
23
+ entries = [entry for entry in discover_providers() if entry.name == "workspace"]
24
+ if len(entries) != 1:
25
+ raise ValueError("Install exactly one workspace provider.")
26
+ moves = Moves(target=workspace)
27
+ load_provider(entries[0], moves.registry)
28
+ return CapabilityCatalog(moves, names)
29
+
30
+
31
+ def main(argv: list[str] | None = None) -> None:
32
+ parser = argparse.ArgumentParser(description="Read explicitly selected workspace text through JSON CLI or local MCP stdio.")
33
+ parser.add_argument("--root", required=True, help="Explicit workspace root; no default or directory scan.")
34
+ parser.add_argument("--file", action="append", required=True, help="Exact relative path; repeat to select files.")
35
+ parser.add_argument("--move", action="append", required=True, help="Qualified capability; repeat to select operations.")
36
+ parser.add_argument("--max-file-bytes", type=int, default=262_144, help="Per-file byte ceiling, at most 1,048,576.")
37
+ commands = parser.add_subparsers(dest="command", required=True)
38
+ call = commands.add_parser("call", help="Invoke one selected operation and print validated JSON.")
39
+ call.add_argument("name")
40
+ call.add_argument("--arguments", default="{}", help="JSON object; follows the selected move's schema.")
41
+ commands.add_parser("serve", help="Serve only the selected operations over local MCP stdio.")
42
+ args = parser.parse_args(argv)
43
+ try:
44
+ from hidden_moves import MoveError
45
+ except ImportError:
46
+ parser.error("Install the workspace package with its [moves] or [host] extra.")
47
+ try:
48
+ workspace = Workspace(args.root, args.file, max_file_bytes=args.max_file_bytes)
49
+ catalog = build_catalog(workspace, args.move)
50
+ if args.command == "call":
51
+ try:
52
+ arguments = json.loads(args.arguments)
53
+ except (ValueError, RecursionError):
54
+ parser.error("arguments must be a finite JSON object.")
55
+ value = catalog.invoke(args.name, arguments)
56
+ print(json.dumps(catalog.serialize_result(args.name, value), allow_nan=False))
57
+ return
58
+ try:
59
+ from hidden_moves_mcp import MCPAdapter, serve_stdio
60
+ except ImportError:
61
+ parser.error("Install the workspace package with its [host] extra.")
62
+ server = MCPAdapter(catalog, offload_sync=True).server("workspace")
63
+ except (WorkspaceError, MoveError, ValueError, TypeError) as error:
64
+ parser.error(str(error))
65
+ asyncio.run(serve_stdio(server))
@@ -0,0 +1,49 @@
1
+ """Optional definitions around an application-configured workspace."""
2
+
3
+ from hidden_moves import MoveAnnotations, MoveSpec
4
+
5
+ from .client import Workspace
6
+ from .models import Excerpt, FilePage, SearchPage
7
+
8
+ READ_CAPABILITIES = ("workspace.files", "workspace.read", "workspace.search")
9
+
10
+
11
+ def list_files(workspace: Workspace, offset: int = 0, limit: int = 100) -> FilePage:
12
+ """List one page of declared relative paths without scanning directories or reading content."""
13
+ return workspace.files(offset, limit)
14
+
15
+
16
+ def read_file(
17
+ workspace: Workspace, path: str, start_line: int = 1, line_count: int = 80,
18
+ start_column: int = 1, expected_sha256: str | None = None,
19
+ ) -> Excerpt:
20
+ """Read a selected UTF-8 file with numbered fragments and a digest.
21
+
22
+ At most 200 lines and 16,384 text characters; continue with next_line,
23
+ next_column, and expected_sha256. Columns count Unicode characters from one.
24
+ """
25
+ return workspace.read(path, start_line, line_count, start_column, expected_sha256)
26
+
27
+
28
+ def search_file(
29
+ workspace: Workspace, path: str, query: str, start_line: int = 1,
30
+ max_matches: int = 20, expected_sha256: str | None = None,
31
+ ) -> SearchPage:
32
+ """Find case-sensitive literal text in one selected UTF-8 file.
33
+
34
+ Return the first occurrence per matching line, at most 100 matches, with
35
+ 320-character previews. Continue with next_line and expected_sha256.
36
+ """
37
+ return workspace.search(path, query, start_line, max_matches, expected_sha256)
38
+
39
+
40
+ def provide_moves() -> tuple[MoveSpec, ...]:
41
+ """Advertise definitions without constructing a workspace or opening files."""
42
+ annotations = MoveAnnotations(read_only=True, destructive=False, idempotent=True, external=True)
43
+ return tuple(
44
+ MoveSpec(
45
+ name=name, namespace="workspace", func=operation,
46
+ bind_target=True, target_types=(Workspace,), annotations=annotations,
47
+ )
48
+ for name, operation in (("files", list_files), ("read", read_file), ("search", search_file))
49
+ )
@@ -0,0 +1,43 @@
1
+ """Finite result models shared by ordinary Python and structured consumers."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class FilePage:
8
+ paths: list[str]
9
+ next_offset: int | None
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class TextLine:
14
+ number: int
15
+ column: int
16
+ text: str
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Excerpt:
21
+ path: str
22
+ sha256: str
23
+ total_lines: int
24
+ lines: list[TextLine]
25
+ next_line: int | None
26
+ next_column: int | None
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class SearchMatch:
31
+ line: int
32
+ column: int
33
+ preview_column: int
34
+ preview: str
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class SearchPage:
39
+ path: str
40
+ sha256: str
41
+ total_lines: int
42
+ matches: list[SearchMatch]
43
+ next_line: int | None