taskcarry 0.3.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- taskcarry/__init__.py +3 -0
- taskcarry/__main__.py +4 -0
- taskcarry/adapter_contracts.py +166 -0
- taskcarry/agy_turns.py +282 -0
- taskcarry/api.py +111 -0
- taskcarry/board.py +313 -0
- taskcarry/board_assets/board.css +1087 -0
- taskcarry/board_assets/board.js +1187 -0
- taskcarry/board_assets/browse.js +214 -0
- taskcarry/board_assets/index.html +43 -0
- taskcarry/board_assets/taskcarry-icon.ico +0 -0
- taskcarry/board_assets/taskcarry-mark.svg +28 -0
- taskcarry/board_data.py +466 -0
- taskcarry/chat_joins.py +157 -0
- taskcarry/cli.py +119 -0
- taskcarry/codex_capture.py +184 -0
- taskcarry/codex_host.py +293 -0
- taskcarry/collaboration_exchange.py +316 -0
- taskcarry/connection.py +159 -0
- taskcarry/continuity.py +300 -0
- taskcarry/contracts.py +165 -0
- taskcarry/conversation_capture.py +669 -0
- taskcarry/core.py +896 -0
- taskcarry/cycle_contracts.py +73 -0
- taskcarry/discovery.py +434 -0
- taskcarry/discovery_contracts.py +52 -0
- taskcarry/exchange_contracts.py +67 -0
- taskcarry/exchange_endpoint.py +377 -0
- taskcarry/exchange_packets.py +142 -0
- taskcarry/experience_contracts.py +129 -0
- taskcarry/experience_exchange.py +214 -0
- taskcarry/experience_notes.py +433 -0
- taskcarry/experience_storage.py +125 -0
- taskcarry/experience_tools.py +26 -0
- taskcarry/feishu/__init__.py +1 -0
- taskcarry/feishu/display.py +122 -0
- taskcarry/feishu/project_watch.py +145 -0
- taskcarry/feishu/review_sets.py +80 -0
- taskcarry/feishu/sender.py +42 -0
- taskcarry/feishu/subscription.py +193 -0
- taskcarry/feishu/windows_agent.py +287 -0
- taskcarry/feishu/windows_secret.py +34 -0
- taskcarry/gitops.py +170 -0
- taskcarry/governance.py +88 -0
- taskcarry/governance_cycle.py +775 -0
- taskcarry/identification.py +82 -0
- taskcarry/integration.py +663 -0
- taskcarry/maintenance.py +118 -0
- taskcarry/mcp.py +183 -0
- taskcarry/member_join.py +184 -0
- taskcarry/member_routing.py +145 -0
- taskcarry/onboarding.py +272 -0
- taskcarry/onboarding_complete.py +252 -0
- taskcarry/path_batches.py +19 -0
- taskcarry/preservation.py +257 -0
- taskcarry/project_collaboration.py +453 -0
- taskcarry/project_history.py +166 -0
- taskcarry/project_identity.py +51 -0
- taskcarry/project_recovery.py +824 -0
- taskcarry/recovery_contracts.py +25 -0
- taskcarry/recovery_files.py +153 -0
- taskcarry/recovery_git.py +234 -0
- taskcarry/remote_capture.py +89 -0
- taskcarry/remote_transfer.py +356 -0
- taskcarry/role_connection.py +215 -0
- taskcarry/setup.py +597 -0
- taskcarry/shared_workbench.py +480 -0
- taskcarry/skill_data/taskcarry-experience-recovery/SKILL.md +37 -0
- taskcarry/skill_data/taskcarry-governance-reconcile/SKILL.md +47 -0
- taskcarry/skill_data/taskcarry-governance-reconcile/references/daily-governance.md +72 -0
- taskcarry/skill_data/taskcarry-project-setup/SKILL.md +48 -0
- taskcarry/skill_data/taskcarry-project-setup/references/onboarding.md +198 -0
- taskcarry/skill_data/taskcarry-task-delivery/SKILL.md +32 -0
- taskcarry/skill_data/taskcarry-task-delivery/references/conditional-experience.md +93 -0
- taskcarry/skill_data/taskcarry-task-delivery/references/worker-channel.md +41 -0
- taskcarry/source_review_set.py +80 -0
- taskcarry/state_format.py +47 -0
- taskcarry/store.py +472 -0
- taskcarry/task_context.py +141 -0
- taskcarry/text_handback.py +98 -0
- taskcarry/transfer_contracts.py +18 -0
- taskcarry/updates.py +351 -0
- taskcarry/workbench.py +625 -0
- taskcarry/workbench_contracts.py +32 -0
- taskcarry/workbuddy_capture.py +451 -0
- taskcarry/workbuddy_setup.py +212 -0
- taskcarry/worker_channel.py +859 -0
- taskcarry/worker_contracts.py +190 -0
- taskcarry/worker_storage.py +60 -0
- taskcarry/worker_tools.py +111 -0
- taskcarry-0.3.2.dist-info/METADATA +203 -0
- taskcarry-0.3.2.dist-info/RECORD +105 -0
- taskcarry-0.3.2.dist-info/WHEEL +5 -0
- taskcarry-0.3.2.dist-info/entry_points.txt +5 -0
- taskcarry-0.3.2.dist-info/licenses/LICENSE +21 -0
- taskcarry-0.3.2.dist-info/licenses/LICENSE_SCOPE.md +31 -0
- taskcarry-0.3.2.dist-info/top_level.txt +2 -0
- taskcarry_https/__init__.py +1 -0
- taskcarry_https/consent.py +207 -0
- taskcarry_https/reader.py +132 -0
- taskcarry_https/review.py +116 -0
- taskcarry_https/server.py +163 -0
- taskcarry_https/team.py +335 -0
- taskcarry_https/team_host.py +109 -0
- taskcarry_https/web_host.py +82 -0
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Manage one project's Feishu subscription for the signed-in Windows user."""
|
|
2
|
+
import argparse
|
|
3
|
+
from contextlib import contextmanager
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from getpass import getpass
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import sqlite3
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
if __name__ == "__main__" and not __package__:
|
|
17
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
|
18
|
+
from taskcarry.feishu.project_watch import ProjectWatch
|
|
19
|
+
from taskcarry.feishu.display import names_path
|
|
20
|
+
from taskcarry.feishu.sender import send_text, valid_webhook
|
|
21
|
+
from taskcarry.feishu.windows_secret import transform
|
|
22
|
+
from taskcarry.core import Core
|
|
23
|
+
from taskcarry.store import GovernanceError
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def local_dir(control):
|
|
27
|
+
key = hashlib.sha256(os.path.normcase(str(control.resolve())).encode()).hexdigest()[:16]
|
|
28
|
+
return Path(os.environ["LOCALAPPDATA"]) / "TaskCarry" / "notifications" / "feishu" / key
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@contextmanager
|
|
32
|
+
def instance(directory, *, owner=False):
|
|
33
|
+
import msvcrt
|
|
34
|
+
with (directory / "listener.lock").open("a+b") as lock:
|
|
35
|
+
if lock.seek(0, os.SEEK_END) == 0:
|
|
36
|
+
lock.write(b"1")
|
|
37
|
+
lock.flush()
|
|
38
|
+
lock.seek(0)
|
|
39
|
+
try:
|
|
40
|
+
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
|
|
41
|
+
except OSError:
|
|
42
|
+
yield False
|
|
43
|
+
else:
|
|
44
|
+
try:
|
|
45
|
+
if owner:
|
|
46
|
+
(directory / "listener.pid").write_text(str(os.getpid()), encoding="ascii")
|
|
47
|
+
yield True
|
|
48
|
+
finally:
|
|
49
|
+
if owner:
|
|
50
|
+
(directory / "listener.pid").unlink(missing_ok=True)
|
|
51
|
+
lock.seek(0)
|
|
52
|
+
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def running_pid(directory):
|
|
56
|
+
# Probe a pre-existing OS lock. A stale PID file after a crash is insufficient.
|
|
57
|
+
if not (directory / "listener.lock").is_file():
|
|
58
|
+
return None
|
|
59
|
+
with instance(directory) as alone:
|
|
60
|
+
if alone:
|
|
61
|
+
return None
|
|
62
|
+
try:
|
|
63
|
+
return int((directory / "listener.pid").read_text(encoding="ascii"))
|
|
64
|
+
except (FileNotFoundError, ValueError):
|
|
65
|
+
return 0 # The owner is still starting.
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def command(control):
|
|
69
|
+
interpreter = Path(sys.executable).with_name("pythonw.exe")
|
|
70
|
+
if not interpreter.is_file():
|
|
71
|
+
interpreter = Path(sys.executable) # CREATE_NO_WINDOW also supports console Python.
|
|
72
|
+
return [str(interpreter), "-I", "-X", "utf8", str(Path(__file__).resolve()), "run", str(control)]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def login_start(control, enable):
|
|
76
|
+
import winreg
|
|
77
|
+
name = "TaskCarry-Feishu-" + local_dir(control).name
|
|
78
|
+
with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Run",
|
|
79
|
+
access=winreg.KEY_SET_VALUE) as key:
|
|
80
|
+
if enable:
|
|
81
|
+
winreg.SetValueEx(key, name, 0, winreg.REG_SZ, subprocess.list2cmdline(command(control)))
|
|
82
|
+
else:
|
|
83
|
+
try:
|
|
84
|
+
winreg.DeleteValue(key, name)
|
|
85
|
+
except FileNotFoundError:
|
|
86
|
+
pass
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def start(control, directory):
|
|
90
|
+
running = running_pid(directory)
|
|
91
|
+
if running:
|
|
92
|
+
return running
|
|
93
|
+
child = subprocess.Popen(command(control), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
94
|
+
creationflags=subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP, close_fds=True)
|
|
95
|
+
# Reap the launcher if the manager stays open. Closing the manager still
|
|
96
|
+
# leaves the independently launched listener running.
|
|
97
|
+
threading.Thread(target=child.wait, daemon=True).start()
|
|
98
|
+
for _ in range(40):
|
|
99
|
+
time.sleep(0.15)
|
|
100
|
+
running = running_pid(directory)
|
|
101
|
+
if running:
|
|
102
|
+
return running
|
|
103
|
+
raise RuntimeError("后台程序未成功启动;重新打开管理入口可查看状态或再次启动。")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def run(control, directory, send=send_text):
|
|
107
|
+
dbfile = directory / "subscription.sqlite3"
|
|
108
|
+
if not dbfile.exists():
|
|
109
|
+
return
|
|
110
|
+
watch = ProjectWatch(dbfile)
|
|
111
|
+
with instance(directory, owner=True) as alone:
|
|
112
|
+
if not alone:
|
|
113
|
+
return
|
|
114
|
+
generation, credentials = None, None
|
|
115
|
+
while True:
|
|
116
|
+
try:
|
|
117
|
+
config = watch.settings()
|
|
118
|
+
if not config or not config["enabled"]:
|
|
119
|
+
return
|
|
120
|
+
if generation != config["generation"]:
|
|
121
|
+
credentials = json.loads(transform(config["sealed"], encrypt=False))
|
|
122
|
+
generation = config["generation"]
|
|
123
|
+
identity = Core(control).source()
|
|
124
|
+
if identity["source_id"] != config["project"] or identity.get("writer_state", "active") != "active":
|
|
125
|
+
raise ValueError("Project writer or identity changed.")
|
|
126
|
+
watch.collect(control)
|
|
127
|
+
watch.transmit_one(control, generation,
|
|
128
|
+
lambda text: send(credentials["url"], credentials["secret"], text))
|
|
129
|
+
watch.health()
|
|
130
|
+
except (ValueError, OSError, sqlite3.Error, GovernanceError) as error:
|
|
131
|
+
# Never persist exception text: an HTTP client may include the recipient URL.
|
|
132
|
+
watch.health(type(error).__name__)
|
|
133
|
+
time.sleep(3)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def show(directory):
|
|
137
|
+
path = directory / "subscription.sqlite3"
|
|
138
|
+
if not path.exists():
|
|
139
|
+
print("状态:尚未启用。")
|
|
140
|
+
return
|
|
141
|
+
watch = ProjectWatch(path, inspect_only=True)
|
|
142
|
+
cfg = watch.settings()
|
|
143
|
+
running = running_pid(directory)
|
|
144
|
+
print("订阅:", "已开启" if cfg and cfg["enabled"] else "已关闭",
|
|
145
|
+
" | 后台:", f"正在运行(PID {running})" if running else "已停止")
|
|
146
|
+
if cfg:
|
|
147
|
+
print("项目:", cfg["project"], " | 已检查至事件序号:", cfg["position"])
|
|
148
|
+
if cfg["sealed"]:
|
|
149
|
+
print("本群展示名称文件:", names_path(directory, cfg["sealed"]))
|
|
150
|
+
successful = watch.last_success()
|
|
151
|
+
print("最近成功:", datetime.fromtimestamp(successful).astimezone().strftime("%Y-%m-%d %H:%M:%S %z")
|
|
152
|
+
if successful else "尚无")
|
|
153
|
+
counts = watch.counts()
|
|
154
|
+
print(f"飞书已接受 {counts.get('accepted',0)} 条,排队 {counts.get('pending',0)} 条,"
|
|
155
|
+
f"失败 {counts.get('http_error',0)+counts.get('rejected',0)} 条,结果待核实 {counts.get('unknown',0)} 条。")
|
|
156
|
+
if cfg and cfg["last_error"]:
|
|
157
|
+
print("最近一次读取异常:", cfg["last_error"])
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def login_registered(directory):
|
|
161
|
+
import winreg
|
|
162
|
+
try:
|
|
163
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Run") as key:
|
|
164
|
+
return bool(winreg.QueryValueEx(key, "TaskCarry-Feishu-" + directory.name)[0])
|
|
165
|
+
except FileNotFoundError:
|
|
166
|
+
return False
|
|
167
|
+
except OSError:
|
|
168
|
+
return None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def reminder_status(control):
|
|
172
|
+
"""Return only operator-facing facts. Never return recipient credentials or paths."""
|
|
173
|
+
if os.name != "nt":
|
|
174
|
+
return {"supported": False}
|
|
175
|
+
directory = local_dir(control)
|
|
176
|
+
path = directory / "subscription.sqlite3"
|
|
177
|
+
watch = ProjectWatch(path, inspect_only=True) if path.is_file() else None
|
|
178
|
+
cfg = watch.settings() if watch else None
|
|
179
|
+
counts = watch.counts() if cfg else {}
|
|
180
|
+
pid = running_pid(directory) if cfg else None
|
|
181
|
+
return {"supported": True, "configured": bool(cfg and cfg["sealed"]),
|
|
182
|
+
"enabled": bool(cfg and cfg["enabled"]), "running": pid is not None, "pid": pid,
|
|
183
|
+
"login_start": login_registered(directory) if cfg else False,
|
|
184
|
+
"position": cfg["position"] if cfg else None,
|
|
185
|
+
"discussions": watch.discussion_mode(cfg["sealed"]) if cfg else "off", "accepted": counts.get("accepted", 0),
|
|
186
|
+
"failed": counts.get("http_error", 0) + counts.get("rejected", 0),
|
|
187
|
+
"unknown": counts.get("unknown", 0), "last_success": watch.last_success() if cfg else None}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def change_reminders(control, action, url="", secret=""):
|
|
191
|
+
"""Shared operations for the terminal and local board. Explicit user action only."""
|
|
192
|
+
if os.name != "nt" or action not in ("enable", "resume", "pause", "forget"):
|
|
193
|
+
raise ValueError("This reminder action is unavailable.")
|
|
194
|
+
core = Core(control)
|
|
195
|
+
identity = core.source()
|
|
196
|
+
project = identity["source_id"]
|
|
197
|
+
if identity.get("writer_state", "active") != "active":
|
|
198
|
+
raise ValueError("Reminders are managed on the active project computer.")
|
|
199
|
+
if action == "enable" and not (valid_webhook(url) and 0 < len(secret.strip()) <= 1024):
|
|
200
|
+
raise ValueError("Check the robot address and signing key.")
|
|
201
|
+
directory = local_dir(control)
|
|
202
|
+
path = directory / "subscription.sqlite3"
|
|
203
|
+
if not path.exists() and action != "enable":
|
|
204
|
+
if action == "resume":
|
|
205
|
+
raise ValueError("Configure a robot first.")
|
|
206
|
+
return reminder_status(control)
|
|
207
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
208
|
+
watch = ProjectWatch(path)
|
|
209
|
+
cfg = watch.settings()
|
|
210
|
+
if cfg and cfg["project"] != project:
|
|
211
|
+
raise ValueError("The saved subscription belongs to a different project.")
|
|
212
|
+
if action in ("pause", "forget"):
|
|
213
|
+
watch.disable(forget=action == "forget")
|
|
214
|
+
login_start(control, False)
|
|
215
|
+
return reminder_status(control)
|
|
216
|
+
sealed = cfg["sealed"] if cfg else None
|
|
217
|
+
if action == "enable":
|
|
218
|
+
credentials = {"url": url, "secret": secret.strip()}
|
|
219
|
+
try:
|
|
220
|
+
saved = json.loads(transform(sealed, encrypt=False)) if sealed else None
|
|
221
|
+
except (ValueError, OSError):
|
|
222
|
+
saved = None
|
|
223
|
+
if credentials != saved:
|
|
224
|
+
sealed = transform(json.dumps(credentials).encode(), encrypt=True)
|
|
225
|
+
try:
|
|
226
|
+
with names_path(directory, sealed).open("x", encoding="utf-8") as names:
|
|
227
|
+
json.dump({"project_id": project, "use_task_titles": True, "use_document_titles": False,
|
|
228
|
+
"workers": {}, "tasks": {}, "sources": {}}, names, indent=2)
|
|
229
|
+
except FileExistsError:
|
|
230
|
+
pass
|
|
231
|
+
if not sealed:
|
|
232
|
+
raise ValueError("Configure a robot first.")
|
|
233
|
+
replace = bool(cfg and sealed != cfg["sealed"])
|
|
234
|
+
watch.enable(control, project, sealed, replace=replace)
|
|
235
|
+
try:
|
|
236
|
+
login_start(control, True)
|
|
237
|
+
except OSError:
|
|
238
|
+
pass # The current session can still send; expose actual login registration separately.
|
|
239
|
+
start(control, directory)
|
|
240
|
+
return reminder_status(control)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def manage(control, directory):
|
|
244
|
+
if not sys.stdin.isatty():
|
|
245
|
+
raise ValueError("请在本机交互窗口配置。")
|
|
246
|
+
core = Core(control)
|
|
247
|
+
project = core.source()["source_id"]
|
|
248
|
+
name = core.store.get("config", "project").get("name", "") or control.name
|
|
249
|
+
print(f"TaskCarry · 飞书群通知\n项目:{name}\n治理目录:{control}")
|
|
250
|
+
show(directory)
|
|
251
|
+
print("\n开启后,这个项目中所有成员新共享的资料都会提醒你选定的群。"
|
|
252
|
+
"\n群里显示工作者、任务和成果名称,并附版次与短指纹。Windows 登录后自动启动,关闭窗口仍然有效。"
|
|
253
|
+
"\n1 开启或恢复 2 暂停 3 更换机器人或签名 4 停用并清除已保存的凭据 Enter 退出")
|
|
254
|
+
selected = input("请选择:").strip()
|
|
255
|
+
if selected not in ("1", "2", "3", "4"):
|
|
256
|
+
return
|
|
257
|
+
action = {"1": "resume", "2": "pause", "3": "enable", "4": "forget"}[selected]
|
|
258
|
+
url = secret = ""
|
|
259
|
+
if action == "enable" or (action == "resume" and not reminder_status(control)["configured"]):
|
|
260
|
+
action = "enable"
|
|
261
|
+
url = getpass("粘贴群机器人的 Webhook 地址,按 Enter(输入隐藏):").strip()
|
|
262
|
+
secret = getpass("粘贴签名密钥,按 Enter(输入隐藏):").strip()
|
|
263
|
+
state = change_reminders(control, action, url, secret)
|
|
264
|
+
if state["enabled"] and not state["login_start"]:
|
|
265
|
+
print("本次登录可使用,Windows 登录后自动启动尚未登记。")
|
|
266
|
+
show(directory)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def main():
|
|
270
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
271
|
+
parser.add_argument("action", choices=("manage", "run", "status"))
|
|
272
|
+
parser.add_argument("control", type=Path)
|
|
273
|
+
args = parser.parse_args()
|
|
274
|
+
if os.name != "nt":
|
|
275
|
+
parser.error("此后台入口适用于 Windows。")
|
|
276
|
+
control = args.control.resolve()
|
|
277
|
+
directory = local_dir(control)
|
|
278
|
+
if args.action == "run":
|
|
279
|
+
run(control, directory)
|
|
280
|
+
elif args.action == "status":
|
|
281
|
+
show(directory)
|
|
282
|
+
else:
|
|
283
|
+
manage(control, directory)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
if __name__ == "__main__":
|
|
287
|
+
main()
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Protect operator configuration with Windows DPAPI in current-user scope."""
|
|
2
|
+
import ctypes
|
|
3
|
+
from ctypes import wintypes
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class DataBlob(ctypes.Structure):
|
|
8
|
+
_fields_ = [("size", wintypes.DWORD), ("data", ctypes.c_void_p)]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def transform(data, *, encrypt):
|
|
12
|
+
if os.name != "nt":
|
|
13
|
+
raise OSError("This credential store requires Windows.")
|
|
14
|
+
crypt = ctypes.WinDLL("crypt32", use_last_error=True)
|
|
15
|
+
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
16
|
+
buffer = ctypes.create_string_buffer(data)
|
|
17
|
+
incoming = DataBlob(len(data), ctypes.addressof(buffer))
|
|
18
|
+
outgoing = DataBlob()
|
|
19
|
+
function = crypt.CryptProtectData if encrypt else crypt.CryptUnprotectData
|
|
20
|
+
function.argtypes = [ctypes.POINTER(DataBlob), ctypes.c_void_p, ctypes.POINTER(DataBlob),
|
|
21
|
+
ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(DataBlob)]
|
|
22
|
+
function.restype = wintypes.BOOL
|
|
23
|
+
kernel.LocalFree.argtypes = [ctypes.c_void_p]
|
|
24
|
+
kernel.LocalFree.restype = ctypes.c_void_p
|
|
25
|
+
try:
|
|
26
|
+
# CRYPTPROTECT_UI_FORBIDDEN; no machine-wide protection flag.
|
|
27
|
+
if not function(ctypes.byref(incoming), None, None, None, None, 1, ctypes.byref(outgoing)):
|
|
28
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
29
|
+
return ctypes.string_at(outgoing.data, outgoing.size)
|
|
30
|
+
finally:
|
|
31
|
+
ctypes.memset(ctypes.addressof(buffer), 0, ctypes.sizeof(buffer))
|
|
32
|
+
if outgoing.data:
|
|
33
|
+
ctypes.memset(outgoing.data, 0, outgoing.size)
|
|
34
|
+
kernel.LocalFree(outgoing.data)
|
taskcarry/gitops.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Bounded local Git helpers. No remote transport, arbitrary shell, or force reset."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path, PurePosixPath
|
|
6
|
+
import subprocess
|
|
7
|
+
import tempfile
|
|
8
|
+
|
|
9
|
+
from .store import GovernanceError
|
|
10
|
+
from .core import _linked, validate_relative_path
|
|
11
|
+
from .path_batches import path_batches
|
|
12
|
+
|
|
13
|
+
MAX_DELIVERY_PATHS = 500
|
|
14
|
+
MAX_BLOB_BYTES = 32 * 1024 * 1024
|
|
15
|
+
MAX_DELIVERY_BYTES = 128 * 1024 * 1024
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def digest(value):
|
|
19
|
+
data = value if isinstance(value, bytes) else json.dumps(value, sort_keys=True, ensure_ascii=False).encode()
|
|
20
|
+
return hashlib.sha256(data).hexdigest()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def git(path, *args, data=None, check=True, timeout=60):
|
|
24
|
+
env = os.environ.copy()
|
|
25
|
+
# Git environment variables inherited from hooks must not redirect our scope.
|
|
26
|
+
for key in list(env):
|
|
27
|
+
if key.startswith("GIT_"):
|
|
28
|
+
env.pop(key, None)
|
|
29
|
+
env.update({"GIT_TERMINAL_PROMPT": "0", "GIT_AUTHOR_NAME": "TaskCarry",
|
|
30
|
+
"GIT_AUTHOR_EMAIL": "toolkit@localhost", "GIT_COMMITTER_NAME": "TaskCarry",
|
|
31
|
+
"GIT_COMMITTER_EMAIL": "toolkit@localhost"})
|
|
32
|
+
argv = ["git", "-c", "core.hooksPath=" + os.devnull, "-c", "commit.gpgsign=false",
|
|
33
|
+
"-c", "merge.autoStash=false", "-c", "core.quotePath=false", "-C", str(path), *map(str, args)]
|
|
34
|
+
try:
|
|
35
|
+
cp = subprocess.run(argv, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
36
|
+
env=env, timeout=timeout, shell=False)
|
|
37
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
38
|
+
raise GovernanceError("GIT_UNAVAILABLE", str(exc)) from exc
|
|
39
|
+
if check and cp.returncode:
|
|
40
|
+
raise GovernanceError("GIT_FAILED", cp.stderr.decode("utf-8", "replace").strip(), {"args": list(args), "returncode": cp.returncode})
|
|
41
|
+
return cp
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def out(path, *args):
|
|
45
|
+
return git(path, *args).stdout.decode("utf-8", "strict").strip()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def repo(path):
|
|
49
|
+
raw = Path(path).expanduser().absolute()
|
|
50
|
+
if any(_linked(x) for x in [raw, *raw.parents]):
|
|
51
|
+
raise GovernanceError("UNSUPPORTED_FILE_TYPE", "Workspace roots cannot traverse symlinks or junctions")
|
|
52
|
+
p = raw.resolve()
|
|
53
|
+
if not p.is_dir():
|
|
54
|
+
raise GovernanceError("WORKSPACE_MISSING", "Workspace does not exist")
|
|
55
|
+
actual = Path(out(p, "rev-parse", "--show-toplevel")).resolve()
|
|
56
|
+
if actual != p:
|
|
57
|
+
raise GovernanceError("WORKSPACE_ROOT_REQUIRED", "Use the exact Git workspace root")
|
|
58
|
+
if out(p, "rev-parse", "--is-bare-repository") != "false":
|
|
59
|
+
raise GovernanceError("BARE_REPOSITORY", "A working tree is required")
|
|
60
|
+
return p
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def commit(path, value):
|
|
64
|
+
if not isinstance(value, str) or value.startswith("-") or not value or len(value) > 256:
|
|
65
|
+
raise GovernanceError("INVALID_COMMIT", "Invalid commit identifier")
|
|
66
|
+
return out(path, "rev-parse", "--verify", "--end-of-options", value + "^{commit}")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def ancestor(path, older, newer):
|
|
70
|
+
result = git(path, "merge-base", "--is-ancestor", older, newer, check=False)
|
|
71
|
+
if result.returncode not in (0, 1):
|
|
72
|
+
raise GovernanceError("GIT_FAILED", "Could not check commit ancestry")
|
|
73
|
+
return result.returncode == 0
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def pathsafe(value):
|
|
77
|
+
if not isinstance(value, str) or "\\" in value or "\0" in value or ":" in value:
|
|
78
|
+
raise GovernanceError("INVALID_PATH", "Use a repository-relative POSIX path")
|
|
79
|
+
p = PurePosixPath(value)
|
|
80
|
+
if not value or p.is_absolute() or any(x in {"", ".", ".."} for x in value.split("/")):
|
|
81
|
+
raise GovernanceError("INVALID_PATH", "Path must stay inside the workspace")
|
|
82
|
+
lower = [x.lower() for x in p.parts]
|
|
83
|
+
if any(x in {".git", ".taskcarry", ".ssh"} for x in lower):
|
|
84
|
+
raise GovernanceError("RESERVED_PATH", "Governance and Git internals are not deliverables")
|
|
85
|
+
name = lower[-1]
|
|
86
|
+
if name == ".env" or name.startswith(".env.") and name not in {".env.example", ".env.sample"} or name in {"id_rsa", "id_ed25519", "credentials.json", "auth.json"} or name.endswith((".pfx", ".p12", ".key")):
|
|
87
|
+
raise GovernanceError("SENSITIVE_PATH", "This credential-like path requires a separate workflow")
|
|
88
|
+
return value
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def changed(path, base, head):
|
|
92
|
+
data = git(path, "diff", "--no-renames", "--name-only", "-z", base, head, "--").stdout
|
|
93
|
+
return sorted(x.decode("utf-8") for x in data.split(b"\0") if x)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def assert_tree_types(path, ref, paths):
|
|
97
|
+
if len(paths) > MAX_DELIVERY_PATHS:
|
|
98
|
+
raise GovernanceError("DELIVERY_TOO_LARGE", "Split stable stages with more than 500 paths")
|
|
99
|
+
if not paths:
|
|
100
|
+
return 0
|
|
101
|
+
data = b''.join(git(path, "--literal-pathspecs", "ls-tree", "-z", "-l", ref, "--", *batch).stdout
|
|
102
|
+
for batch in path_batches(paths))
|
|
103
|
+
total = 0
|
|
104
|
+
for entry in data.split(b"\0"):
|
|
105
|
+
if not entry:
|
|
106
|
+
continue
|
|
107
|
+
header, _, rel = entry.partition(b"\t")
|
|
108
|
+
fields = header.split()
|
|
109
|
+
if fields[0] not in {b"100644", b"100755"}:
|
|
110
|
+
raise GovernanceError("UNSUPPORTED_FILE_TYPE", "Symlinks, directories and submodules cannot be submitted", {"path": rel.decode("utf-8")})
|
|
111
|
+
size = int(fields[3])
|
|
112
|
+
total += size
|
|
113
|
+
if size > MAX_BLOB_BYTES or total > MAX_DELIVERY_BYTES:
|
|
114
|
+
raise GovernanceError("DELIVERY_TOO_LARGE", "Use artifact references for oversized binary or aggregate delivery content")
|
|
115
|
+
return total
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def identity(path):
|
|
119
|
+
return {"path": str(path), "common_dir": str(Path(out(path, "rev-parse", "--path-format=absolute", "--git-common-dir")).resolve()),
|
|
120
|
+
"branch": out(path, "symbolic-ref", "--quiet", "HEAD")}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def fingerprint(path):
|
|
124
|
+
raw = git(path, "status", "--porcelain=v1", "-z", "--untracked-files=all").stdout
|
|
125
|
+
untracked = git(path, "ls-files", "--others", "--exclude-standard", "-z").stdout
|
|
126
|
+
extras = {}
|
|
127
|
+
for item in untracked.split(b"\0"):
|
|
128
|
+
if not item:
|
|
129
|
+
continue
|
|
130
|
+
rel = item.decode("utf-8")
|
|
131
|
+
p = validate_relative_path(path, rel, allow_missing=False)
|
|
132
|
+
if p.stat().st_size > 64 * 1024 * 1024:
|
|
133
|
+
raise GovernanceError("FILE_TOO_LARGE", "Use artifact references for files over 64 MiB")
|
|
134
|
+
extras[rel] = digest(p.read_bytes())
|
|
135
|
+
return {"head": commit(path, "HEAD"), "status": raw.hex(),
|
|
136
|
+
"index": digest(git(path, "ls-files", "--stage", "-z").stdout),
|
|
137
|
+
"work_diff": digest(git(path, "diff", "--binary", "--no-ext-diff", "--no-textconv", "--").stdout),
|
|
138
|
+
"untracked": extras}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def clean(path):
|
|
142
|
+
return not git(path, "status", "--porcelain=v1", "--untracked-files=all").stdout.strip()
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def import_commit(destination, source, sha):
|
|
146
|
+
source = repo(source)
|
|
147
|
+
git(destination, "-c", "protocol.file.allow=always", "fetch", "--no-tags", "--no-write-fetch-head", str(source), sha)
|
|
148
|
+
if commit(destination, sha) != sha:
|
|
149
|
+
raise GovernanceError("COMMIT_CHANGED", "Imported commit did not match the frozen commit")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class Scratch:
|
|
153
|
+
def __init__(self, repository, scratch_root, ref):
|
|
154
|
+
self.repository = repository
|
|
155
|
+
raw_root = Path(scratch_root).absolute()
|
|
156
|
+
if any(_linked(x) for x in [raw_root, *raw_root.parents]):
|
|
157
|
+
raise GovernanceError("UNSUPPORTED_FILE_TYPE", "Scratch storage cannot traverse symlinks or junctions")
|
|
158
|
+
self.scratch_root = raw_root.resolve()
|
|
159
|
+
self.scratch_root.mkdir(parents=True, exist_ok=True)
|
|
160
|
+
self.path = Path(tempfile.mkdtemp(prefix="git-", dir=self.scratch_root))
|
|
161
|
+
self.ref = ref
|
|
162
|
+
|
|
163
|
+
def __enter__(self):
|
|
164
|
+
git(self.repository, "worktree", "add", "--detach", str(self.path), self.ref)
|
|
165
|
+
return self.path
|
|
166
|
+
|
|
167
|
+
def __exit__(self, *exc):
|
|
168
|
+
# Only an exact directory created by this object, inside its private scratch root.
|
|
169
|
+
if self.path.resolve().is_relative_to(self.scratch_root) and self.path.parent == self.scratch_root:
|
|
170
|
+
git(self.repository, "worktree", "remove", "--force", str(self.path), check=False)
|
taskcarry/governance.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Observe a governance composition and retain explicit, content-bound reviews.
|
|
2
|
+
|
|
3
|
+
The installed package, managed methods and user rules have independent identity.
|
|
4
|
+
Recording a review never installs a package or certifies another host process.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
|
|
10
|
+
from .core import Core, _id, digest_bytes, read_file_bytes, validate_relative_path
|
|
11
|
+
from .maintenance import _revision, _text
|
|
12
|
+
from .setup import runtime_info
|
|
13
|
+
from .store import GovernanceError, now
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _fingerprint(value):
|
|
17
|
+
return digest_bytes(json.dumps(value, sort_keys=True, ensure_ascii=False,
|
|
18
|
+
separators=(',', ':')).encode('utf-8'))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Governance(Core):
|
|
22
|
+
def governance(self, mode='inspect', rule_paths=None, record_id=None,
|
|
23
|
+
expected_fingerprint=None, evidence_refs=None, expected_revision=None):
|
|
24
|
+
if mode not in ('inspect', 'record'):
|
|
25
|
+
raise GovernanceError('INVALID_ARGUMENT', 'Use inspect or record.')
|
|
26
|
+
paths = [] if rule_paths is None else rule_paths
|
|
27
|
+
if (not isinstance(paths, list) or len(paths) > 100
|
|
28
|
+
or any(not isinstance(path, str) for path in paths)
|
|
29
|
+
or len({path.casefold() for path in paths}) != len(paths)):
|
|
30
|
+
raise GovernanceError('INVALID_ARGUMENT', 'Select at most 100 unique project-relative rule files.')
|
|
31
|
+
rules = []
|
|
32
|
+
for path in sorted(paths):
|
|
33
|
+
content = read_file_bytes(validate_relative_path(self.root, path, allow_missing=False))
|
|
34
|
+
rules.append({'path': path, 'sha256': digest_bytes(content), 'size': len(content),
|
|
35
|
+
'origin': 'user_project', 'update_policy': 'preserve_and_review_conflicts'})
|
|
36
|
+
runtime = runtime_info(self.root)
|
|
37
|
+
loaded = runtime.get('loaded_runtime', {})
|
|
38
|
+
composition = {
|
|
39
|
+
'schema_version': 1, 'control': str(self.root),
|
|
40
|
+
'core': {key: loaded.get(key) for key in
|
|
41
|
+
('version', 'interpreter', 'module_root', 'source_sha256')},
|
|
42
|
+
'methods': {'version': runtime.get('managed_setup_version'),
|
|
43
|
+
'status': runtime.get('setup_status'),
|
|
44
|
+
'files': runtime.get('files', []),
|
|
45
|
+
'managed_files_match': runtime.get('managed_files_match'),
|
|
46
|
+
'pending_installation': runtime.get('pending_installation')},
|
|
47
|
+
'user_rules': rules,
|
|
48
|
+
'identity_scope': 'current_process_location_and_on_disk_content',
|
|
49
|
+
}
|
|
50
|
+
fingerprint = _fingerprint(composition)
|
|
51
|
+
result = {'composition': composition, 'fingerprint': fingerprint,
|
|
52
|
+
'host_loading_verified': False, 'loaded_code_verified': False,
|
|
53
|
+
'package_upgrade_performed': False,
|
|
54
|
+
'meaning': 'Observed composition; user rules remain separate from package methods. '
|
|
55
|
+
'A saved review is not installation, host reload, or problem resolution.'}
|
|
56
|
+
if mode == 'inspect':
|
|
57
|
+
if any(value is not None for value in (record_id, expected_fingerprint, evidence_refs, expected_revision)):
|
|
58
|
+
raise GovernanceError('INVALID_ARGUMENT', 'Review fields are only valid in record mode.')
|
|
59
|
+
return result
|
|
60
|
+
key = _id(record_id, 'Governance review ID')
|
|
61
|
+
if expected_fingerprint != fingerprint:
|
|
62
|
+
raise GovernanceError('COMPOSITION_CHANGED', 'Inspect the current composition before recording its review.',
|
|
63
|
+
{'current_fingerprint': fingerprint})
|
|
64
|
+
if not isinstance(evidence_refs, list) or not evidence_refs or len(evidence_refs) > 50:
|
|
65
|
+
raise GovernanceError('INVALID_ARGUMENT', 'Provide 1-50 reviewed evidence references.')
|
|
66
|
+
for ref in evidence_refs:
|
|
67
|
+
_text(ref, 'evidence_refs item')
|
|
68
|
+
body = {'record_id': key, 'fingerprint': fingerprint, 'composition': composition,
|
|
69
|
+
'evidence_refs': sorted(set(evidence_refs)), 'evidence_scope': 'host_reviewed_references',
|
|
70
|
+
'host_loading_verified': False, 'package_upgrade_performed': False}
|
|
71
|
+
with self.store.transaction():
|
|
72
|
+
# Recheck disk identities inside the guard before publishing a review.
|
|
73
|
+
current = self.governance(rule_paths=paths)
|
|
74
|
+
if current['fingerprint'] != fingerprint:
|
|
75
|
+
raise GovernanceError('COMPOSITION_CHANGED', 'The composition changed before recording.')
|
|
76
|
+
previous = self.store.get('governance_reviews', key)
|
|
77
|
+
if previous and all(previous.get(k) == v for k, v in body.items()):
|
|
78
|
+
result.update(review=previous, reused=True)
|
|
79
|
+
return result
|
|
80
|
+
revision = _revision(expected_revision, previous)
|
|
81
|
+
record = dict(body, revision=revision,
|
|
82
|
+
created_at=previous['created_at'] if previous else now(), updated_at=now())
|
|
83
|
+
self.store.put('governance_reviews', key, record)
|
|
84
|
+
self.store.put('governance_review_history', key + '.' + str(revision), record)
|
|
85
|
+
self.store.event('governance_review_recorded', {'record_id': key, 'fingerprint': fingerprint,
|
|
86
|
+
'revision': revision})
|
|
87
|
+
result.update(review=record, reused=False)
|
|
88
|
+
return result
|