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.
Files changed (105) hide show
  1. taskcarry/__init__.py +3 -0
  2. taskcarry/__main__.py +4 -0
  3. taskcarry/adapter_contracts.py +166 -0
  4. taskcarry/agy_turns.py +282 -0
  5. taskcarry/api.py +111 -0
  6. taskcarry/board.py +313 -0
  7. taskcarry/board_assets/board.css +1087 -0
  8. taskcarry/board_assets/board.js +1187 -0
  9. taskcarry/board_assets/browse.js +214 -0
  10. taskcarry/board_assets/index.html +43 -0
  11. taskcarry/board_assets/taskcarry-icon.ico +0 -0
  12. taskcarry/board_assets/taskcarry-mark.svg +28 -0
  13. taskcarry/board_data.py +466 -0
  14. taskcarry/chat_joins.py +157 -0
  15. taskcarry/cli.py +119 -0
  16. taskcarry/codex_capture.py +184 -0
  17. taskcarry/codex_host.py +293 -0
  18. taskcarry/collaboration_exchange.py +316 -0
  19. taskcarry/connection.py +159 -0
  20. taskcarry/continuity.py +300 -0
  21. taskcarry/contracts.py +165 -0
  22. taskcarry/conversation_capture.py +669 -0
  23. taskcarry/core.py +896 -0
  24. taskcarry/cycle_contracts.py +73 -0
  25. taskcarry/discovery.py +434 -0
  26. taskcarry/discovery_contracts.py +52 -0
  27. taskcarry/exchange_contracts.py +67 -0
  28. taskcarry/exchange_endpoint.py +377 -0
  29. taskcarry/exchange_packets.py +142 -0
  30. taskcarry/experience_contracts.py +129 -0
  31. taskcarry/experience_exchange.py +214 -0
  32. taskcarry/experience_notes.py +433 -0
  33. taskcarry/experience_storage.py +125 -0
  34. taskcarry/experience_tools.py +26 -0
  35. taskcarry/feishu/__init__.py +1 -0
  36. taskcarry/feishu/display.py +122 -0
  37. taskcarry/feishu/project_watch.py +145 -0
  38. taskcarry/feishu/review_sets.py +80 -0
  39. taskcarry/feishu/sender.py +42 -0
  40. taskcarry/feishu/subscription.py +193 -0
  41. taskcarry/feishu/windows_agent.py +287 -0
  42. taskcarry/feishu/windows_secret.py +34 -0
  43. taskcarry/gitops.py +170 -0
  44. taskcarry/governance.py +88 -0
  45. taskcarry/governance_cycle.py +775 -0
  46. taskcarry/identification.py +82 -0
  47. taskcarry/integration.py +663 -0
  48. taskcarry/maintenance.py +118 -0
  49. taskcarry/mcp.py +183 -0
  50. taskcarry/member_join.py +184 -0
  51. taskcarry/member_routing.py +145 -0
  52. taskcarry/onboarding.py +272 -0
  53. taskcarry/onboarding_complete.py +252 -0
  54. taskcarry/path_batches.py +19 -0
  55. taskcarry/preservation.py +257 -0
  56. taskcarry/project_collaboration.py +453 -0
  57. taskcarry/project_history.py +166 -0
  58. taskcarry/project_identity.py +51 -0
  59. taskcarry/project_recovery.py +824 -0
  60. taskcarry/recovery_contracts.py +25 -0
  61. taskcarry/recovery_files.py +153 -0
  62. taskcarry/recovery_git.py +234 -0
  63. taskcarry/remote_capture.py +89 -0
  64. taskcarry/remote_transfer.py +356 -0
  65. taskcarry/role_connection.py +215 -0
  66. taskcarry/setup.py +597 -0
  67. taskcarry/shared_workbench.py +480 -0
  68. taskcarry/skill_data/taskcarry-experience-recovery/SKILL.md +37 -0
  69. taskcarry/skill_data/taskcarry-governance-reconcile/SKILL.md +47 -0
  70. taskcarry/skill_data/taskcarry-governance-reconcile/references/daily-governance.md +72 -0
  71. taskcarry/skill_data/taskcarry-project-setup/SKILL.md +48 -0
  72. taskcarry/skill_data/taskcarry-project-setup/references/onboarding.md +198 -0
  73. taskcarry/skill_data/taskcarry-task-delivery/SKILL.md +32 -0
  74. taskcarry/skill_data/taskcarry-task-delivery/references/conditional-experience.md +93 -0
  75. taskcarry/skill_data/taskcarry-task-delivery/references/worker-channel.md +41 -0
  76. taskcarry/source_review_set.py +80 -0
  77. taskcarry/state_format.py +47 -0
  78. taskcarry/store.py +472 -0
  79. taskcarry/task_context.py +141 -0
  80. taskcarry/text_handback.py +98 -0
  81. taskcarry/transfer_contracts.py +18 -0
  82. taskcarry/updates.py +351 -0
  83. taskcarry/workbench.py +625 -0
  84. taskcarry/workbench_contracts.py +32 -0
  85. taskcarry/workbuddy_capture.py +451 -0
  86. taskcarry/workbuddy_setup.py +212 -0
  87. taskcarry/worker_channel.py +859 -0
  88. taskcarry/worker_contracts.py +190 -0
  89. taskcarry/worker_storage.py +60 -0
  90. taskcarry/worker_tools.py +111 -0
  91. taskcarry-0.3.2.dist-info/METADATA +203 -0
  92. taskcarry-0.3.2.dist-info/RECORD +105 -0
  93. taskcarry-0.3.2.dist-info/WHEEL +5 -0
  94. taskcarry-0.3.2.dist-info/entry_points.txt +5 -0
  95. taskcarry-0.3.2.dist-info/licenses/LICENSE +21 -0
  96. taskcarry-0.3.2.dist-info/licenses/LICENSE_SCOPE.md +31 -0
  97. taskcarry-0.3.2.dist-info/top_level.txt +2 -0
  98. taskcarry_https/__init__.py +1 -0
  99. taskcarry_https/consent.py +207 -0
  100. taskcarry_https/reader.py +132 -0
  101. taskcarry_https/review.py +116 -0
  102. taskcarry_https/server.py +163 -0
  103. taskcarry_https/team.py +335 -0
  104. taskcarry_https/team_host.py +109 -0
  105. taskcarry_https/web_host.py +82 -0
@@ -0,0 +1,122 @@
1
+ """Display names for a group's notifications. Keep locators separate from titles."""
2
+ import hashlib
3
+ from io import BytesIO
4
+ import json
5
+ from pathlib import Path, PurePosixPath
6
+ import re
7
+
8
+ from taskcarry.core import _linked, read_file_bytes
9
+ from taskcarry.store import GovernanceError
10
+
11
+
12
+ def names_path(directory, sealed):
13
+ # Replacing the recipient creates a new sealed blob. A different group
14
+ # must opt into its own titles instead of inheriting the old group's choices.
15
+ return directory / ("display-names-" + hashlib.sha256(sealed).hexdigest()[:20] + ".json")
16
+
17
+
18
+ def group_names(directory, project, sealed):
19
+ """A local group's aliases never grant access to a source or follow it to another project."""
20
+ try:
21
+ data = json.loads(read_file_bytes(names_path(directory, sealed), max_bytes=128 * 1024))
22
+ except (OSError, ValueError, GovernanceError):
23
+ return {}
24
+ return data if isinstance(data, dict) and data.get("project_id") == project else {}
25
+
26
+
27
+ def label(value):
28
+ if not isinstance(value, str) or len(value) > 96 or not value.isprintable():
29
+ return ""
30
+ # Feishu gets one plain label, never a mention, link, filesystem path or credential assignment.
31
+ if re.search(r"[@<>\\/]|(?:https?:|file:|www\.)|(?:bearer\s+|(?:token|password|secret|authorization|密钥|密码|口令)\s*[=::])",
32
+ value, re.IGNORECASE):
33
+ return ""
34
+ return value.strip()
35
+
36
+
37
+ def lookup(names, section, key):
38
+ entries = names.get(section)
39
+ return entries.get(key) if isinstance(entries, dict) else None
40
+
41
+
42
+ def readable_id(key):
43
+ return re.sub(r"[-_.]+", " ", key).strip() or key
44
+
45
+
46
+ def registered_name(db, collection, key, field):
47
+ row = db.execute("SELECT json_extract(value,?) FROM records WHERE collection=? AND key=?",
48
+ ("$." + field, collection, key)).fetchone()
49
+ return label(row[0]) if row else ""
50
+
51
+
52
+ def document_title(control, version):
53
+ """Older publishers have no title field. Use only an explicit first H1 of this exact shared snapshot."""
54
+ digest = version["content_sha256"]
55
+ if version["media_type"] != "text/markdown" or version["size"] > 512 * 1024 or not re.fullmatch("[0-9a-f]{64}", digest):
56
+ return ""
57
+ objects = Path(control) / ".taskcarry" / "objects"
58
+ try:
59
+ if _linked(objects) or _linked(objects.parent):
60
+ return ""
61
+ data = read_file_bytes(objects / digest, max_bytes=512 * 1024)
62
+ if len(data) != version["size"] or hashlib.sha256(data).hexdigest() != digest:
63
+ return ""
64
+ lines = BytesIO(data.removeprefix(b'\xef\xbb\xbf'))
65
+ first = next((line.rstrip(b"\r\n") for line in lines if line.strip()), b"")
66
+ if not first.startswith(b"# ") or len(first) > 400:
67
+ return ""
68
+ return label(first[2:].decode("utf-8").strip())
69
+ except (OSError, UnicodeError, GovernanceError):
70
+ return ""
71
+
72
+
73
+ def notice_fields(db, actor, versions, names):
74
+ """Resolve ledger metadata inside the read snapshot. File reads and formatting happen after it closes."""
75
+ worker = (label(lookup(names, "workers", actor)) or registered_name(db, "worker_bindings", actor, "display_name")
76
+ or readable_id(actor))
77
+ items = []
78
+ for version in versions[:8]:
79
+ rid, task_id = version["reference_id"], version["task_id"]
80
+ source = lookup(names, "sources", rid)
81
+ source = source if isinstance(source, dict) else {}
82
+ task = label(source.get("task")) or label(lookup(names, "tasks", task_id))
83
+ if not task and names.get("use_task_titles") is True:
84
+ task = registered_name(db, "tasks", task_id, "title")
85
+ items.append({"version": version, "task": task or readable_id(task_id),
86
+ "title": label(version.get("display_title")) or label(source.get("title"))})
87
+ return worker, items
88
+
89
+
90
+ def format_notice(control, worker, items, total, *, use_document_titles=False, governor_set=False):
91
+ titles = []
92
+ for item in items:
93
+ v = item["version"]
94
+ title = item["title"]
95
+ if not title and use_document_titles:
96
+ title = document_title(control, v)
97
+ if not title:
98
+ path = v.get("origin", {}).get("path", "")
99
+ kind = "配图" if v["media_type"].startswith("image/") else "资料"
100
+ title = label(PurePosixPath(path).name) or f"{readable_id(v['reference_id'])}({kind})"
101
+ locator = f"{v['reference_id']} · 第 {v['revision']} 版 · 指纹 {v['content_sha256'][:8]}"
102
+ titles.append((item["task"], title, locator))
103
+ if total == 1:
104
+ task, title, locator = titles[0]
105
+ verb = "共享了" if items[0]["version"]["revision"] == 1 else "更新了"
106
+ return f"{worker} {verb}《{title}》\n任务 · {task}\nTaskCarry 资料共享 · {locator}"
107
+ if governor_set:
108
+ lines = [f"{worker}|本轮治理更新({total} 份资料)"]
109
+ for task, title, locator in titles:
110
+ lines.extend([f"• {task} · 《{title}》", f" {locator}"])
111
+ else:
112
+ lines = [f"{worker} 共享了 {total} 份资料"]
113
+ tasks = {}
114
+ for task, title, locator in titles:
115
+ tasks.setdefault(task, []).append((title, locator))
116
+ for task, artifacts in tasks.items():
117
+ lines.append(f"任务 · {task}")
118
+ for title, locator in artifacts:
119
+ lines.extend([f"• 《{title}》", f" {locator}"])
120
+ remainder = f"另有 {total - len(items)} 份资料," if total > len(items) else ""
121
+ lines.append(f"TaskCarry 资料共享 · {remainder}可在项目工作台查看。")
122
+ return "\n".join(lines)
@@ -0,0 +1,145 @@
1
+ """Durable, opt-in notification subscription. All writes go to the local listener state."""
2
+ from contextlib import closing
3
+ import json
4
+ from pathlib import Path
5
+ import sqlite3
6
+ from time import time
7
+
8
+ from .display import format_notice, group_names, label, notice_fields, registered_name
9
+ from .subscription import last_sequence, project_connection, publications, visible_version, visible_discussion
10
+ import hashlib
11
+
12
+
13
+ class ProjectWatch:
14
+ def __init__(self, database, *, inspect_only=False):
15
+ self.database = database
16
+ self.inspect_only = inspect_only
17
+ if inspect_only:
18
+ return
19
+ with closing(self.connect()) as db, db:
20
+ db.executescript("""
21
+ CREATE TABLE IF NOT EXISTS settings(
22
+ id INTEGER PRIMARY KEY CHECK(id=1), project TEXT NOT NULL, enabled INTEGER NOT NULL,
23
+ position INTEGER NOT NULL, generation INTEGER NOT NULL, sealed BLOB,
24
+ heartbeat REAL, last_error TEXT);
25
+ CREATE TABLE IF NOT EXISTS notices(
26
+ id TEXT PRIMARY KEY, seq INTEGER NOT NULL, event TEXT NOT NULL,
27
+ state TEXT NOT NULL, code INTEGER, attempted_at REAL, finished_at REAL);
28
+ CREATE INDEX IF NOT EXISTS notices_due ON notices(state,seq);
29
+ CREATE TABLE IF NOT EXISTS discussion_preferences(group_key TEXT PRIMARY KEY, mode TEXT NOT NULL);
30
+ """)
31
+ if "finished_at" not in {r["name"] for r in db.execute("PRAGMA table_info(notices)")}:
32
+ db.execute("ALTER TABLE notices ADD COLUMN finished_at REAL")
33
+
34
+ def connect(self):
35
+ if self.inspect_only:
36
+ db = sqlite3.connect(self.database.resolve().as_uri() + "?mode=ro", timeout=8, uri=True)
37
+ else:
38
+ db = sqlite3.connect(self.database, timeout=8)
39
+ db.row_factory = sqlite3.Row
40
+ return db
41
+
42
+ def settings(self):
43
+ with closing(self.connect()) as db:
44
+ return db.execute("SELECT * FROM settings WHERE id=1").fetchone()
45
+
46
+ def discussion_mode(self, sealed, update=None):
47
+ if not sealed:
48
+ return "off"
49
+ group = hashlib.sha256(sealed).hexdigest()
50
+ with closing(self.connect()) as db, db:
51
+ if update is not None:
52
+ if update not in ("off","mentions","all"):
53
+ raise ValueError("Unknown discussion notice preference.")
54
+ db.execute("INSERT OR REPLACE INTO discussion_preferences VALUES(?,?)", (group,update))
55
+ if not db.execute("SELECT 1 FROM sqlite_master WHERE name='discussion_preferences'").fetchone():
56
+ return "off"
57
+ row = db.execute("SELECT mode FROM discussion_preferences WHERE group_key=?", (group,)).fetchone()
58
+ return row[0] if row else "off"
59
+
60
+ def enable(self, control, project, sealed, *, replace=False):
61
+ with closing(self.connect()) as db, db:
62
+ db.execute("BEGIN IMMEDIATE")
63
+ old = db.execute("SELECT * FROM settings WHERE id=1").fetchone()
64
+ if old and old["project"] != project:
65
+ raise ValueError("This subscription belongs to a different project.")
66
+ if old and old["enabled"] and not replace:
67
+ return
68
+ with closing(project_connection(control)) as source:
69
+ position = last_sequence(source)
70
+ db.execute("UPDATE notices SET state='skipped' WHERE state='pending'")
71
+ db.execute("INSERT OR REPLACE INTO settings VALUES(1,?,1,?,?,?,NULL,NULL)",
72
+ (project, position, old["generation"] + 1 if old else 1, sealed))
73
+
74
+ def disable(self, *, forget=False):
75
+ with closing(self.connect()) as db, db:
76
+ db.execute("UPDATE settings SET enabled=0,generation=generation+1,heartbeat=NULL,last_error=NULL, "
77
+ "sealed=CASE WHEN ? THEN NULL ELSE sealed END WHERE id=1", (forget,))
78
+ db.execute("UPDATE notices SET state='skipped' WHERE state='pending'")
79
+
80
+ def collect(self, control):
81
+ sub = self.settings()
82
+ if not sub or not sub["enabled"]:
83
+ return
84
+ position, events = publications(control, sub["project"], sub["position"], window=128,
85
+ discussions=self.discussion_mode(sub["sealed"]))
86
+ if position == sub["position"]:
87
+ return
88
+ with closing(self.connect()) as db, db:
89
+ guard = db.execute("UPDATE settings SET position=? WHERE id=1 AND enabled=1 AND generation=? AND position=?",
90
+ (position, sub["generation"], sub["position"]))
91
+ if guard.rowcount:
92
+ db.executemany("INSERT OR IGNORE INTO notices(id,seq,event,state) VALUES(?,?,?,'pending')",
93
+ [(e["event_id"], e["sequence"], json.dumps(e, ensure_ascii=False)) for e in events])
94
+
95
+ def transmit_one(self, control, generation, send):
96
+ with closing(self.connect()) as db:
97
+ with db:
98
+ db.execute("BEGIN IMMEDIATE")
99
+ row = db.execute("SELECT n.id,n.event,s.project,s.sealed FROM notices n JOIN settings s ON s.id=1 "
100
+ "WHERE n.state='pending' AND s.enabled=1 AND s.generation=? ORDER BY n.seq LIMIT 1",
101
+ (generation,)).fetchone()
102
+ if not row:
103
+ return None
104
+ event = json.loads(row["event"])
105
+ names = group_names(Path(self.database).parent, row["project"], row["sealed"])
106
+ with closing(project_connection(control)) as source:
107
+ source.execute("BEGIN")
108
+ discussion = None
109
+ if event["event_kind"] == "discussion" and self.discussion_mode(row["sealed"]) != "off":
110
+ discussion = visible_discussion(source,event,row["project"])
111
+ versions = [v for r in event.get("refs",[]) if (v := visible_version(source, row["project"], event["actor"], r))]
112
+ worker, items = notice_fields(source, event["actor"], versions, names)
113
+ governor_set = (len(versions) > 1 and
114
+ registered_name(source, "worker_bindings", event["actor"], "role") == "governor")
115
+ if not versions and not discussion:
116
+ db.execute("UPDATE notices SET state='skipped' WHERE id=?", (row["id"],))
117
+ return "skipped"
118
+ # A crash after the request leaves an honest ambiguous result.
119
+ db.execute("UPDATE notices SET state='unknown',attempted_at=? WHERE id=?", (time(), row["id"]))
120
+ if discussion:
121
+ title = label(discussion["title"]) or "项目讨论"
122
+ text = (f"{worker} 更新了讨论《{title}》\n第 {discussion['revision']} 版 · 指纹 {event['sha256'][:8]}"
123
+ "\n可在项目看板的讨论纪要查看。")
124
+ else:
125
+ text = format_notice(control, worker, items, len(versions),
126
+ use_document_titles=names.get("use_document_titles") is True, governor_set=governor_set)
127
+ result = send(text)
128
+ with db:
129
+ db.execute("UPDATE notices SET state=?,code=?,finished_at=? WHERE id=?",
130
+ (result["state"], result.get("provider_code", result.get("http_status")), time(), row["id"]))
131
+ return result["state"]
132
+
133
+ def health(self, error=None):
134
+ with closing(self.connect()) as db, db:
135
+ db.execute("UPDATE settings SET heartbeat=?,last_error=? WHERE id=1 AND enabled=1 AND "
136
+ "(heartbeat IS NULL OR heartbeat<? OR last_error IS NOT ?)",
137
+ (time(), error, time() - 30, error))
138
+
139
+ def counts(self):
140
+ with closing(self.connect()) as db:
141
+ return dict(db.execute("SELECT state,count(*) FROM notices GROUP BY state"))
142
+
143
+ def last_success(self):
144
+ with closing(self.connect()) as db:
145
+ return db.execute("SELECT max(finished_at) FROM notices WHERE state='accepted'").fetchone()[0]
@@ -0,0 +1,80 @@
1
+ """Recognize an older publisher's completed multi-file receipts in its per-file event stream."""
2
+ from collections import Counter, defaultdict
3
+ import hashlib
4
+ import json
5
+
6
+ from taskcarry.worker_channel import packed
7
+
8
+ MAX_SET_FILES = 64
9
+
10
+
11
+ def completed_sets(db, project, rows, window):
12
+ """Return (first index, last index, publication) without reading any draft or changing the ledger."""
13
+ native = {(e["actor"], r["reference_id"], r["revision"]) for _, kind, e in rows
14
+ if kind == "project_sources_shared" and e["project_id"] == project for r in e["references"]}
15
+ keys = []
16
+ for _, kind, event in rows:
17
+ key = (event["actor"], event["id"], event["revision"]) if kind == "worker_source" else None
18
+ keys.append(None if key in native else key)
19
+ # A legacy set emits consecutive child events inside one transaction. A
20
+ # lone publication (and an idle poll) needs no historical plan lookup.
21
+ limit = len(keys) if window is None else min(window, len(keys))
22
+ actors = {key[0] for i, key in enumerate(keys[:limit]) if key and i + 1 < len(keys)
23
+ and keys[i + 1] and keys[i + 1][0] == key[0] and rows[i + 1][0] == rows[i][0] + 1}
24
+ if not actors:
25
+ return []
26
+ scope = (" FROM records WHERE collection='worker_plans' AND json_extract(value,'$.project_id')=? "
27
+ "AND json_extract(value,'$.actor') IN (SELECT value FROM json_each(?)) "
28
+ "AND json_extract(value,'$.state')='completed' ")
29
+ params = (project, json.dumps(sorted(actors)))
30
+ receipts = defaultdict(lambda: defaultdict(set))
31
+ for actor, intent, effect in db.execute(
32
+ "SELECT json_extract(value,'$.actor'),json_extract(value,'$.payload'),json_extract(value,'$.result')" +
33
+ scope + "AND json_extract(value,'$.action')='source_share_set' "
34
+ "AND json_extract(value,'$.result.published')=1 AND json_extract(value,'$.result.effects_executed')=1", params):
35
+ plan, result = json.loads(intent), json.loads(effect)
36
+ manifest, count = plan.get("manifest"), plan.get("file_count")
37
+ if (isinstance(manifest, dict) and isinstance(manifest.get("sha256"), str) and type(manifest.get("size")) is int
38
+ and type(count) is int and 2 <= count <= MAX_SET_FILES
39
+ and result.get("manifest") == manifest and result.get("file_count") == count):
40
+ receipts[actor][count].add((manifest["sha256"], manifest["size"]))
41
+ if not receipts:
42
+ return []
43
+
44
+ wanted = {key for key in keys if key and key[0] in receipts}
45
+ children = {}
46
+ ids = sorted({key[1] for key in wanted})
47
+ for pid, actor, raw in db.execute(
48
+ "SELECT key,json_extract(value,'$.actor'),json_extract(value,'$.result.reference')" + scope +
49
+ "AND json_extract(value,'$.action')='source_share' AND json_extract(value,'$.result.published')=1 "
50
+ "AND json_extract(value,'$.result.reference.reference_id') IN (SELECT value FROM json_each(?))",
51
+ (*params, json.dumps(ids))):
52
+ ref = json.loads(raw)
53
+ key = (actor, ref["reference_id"], ref["revision"])
54
+ if key in wanted:
55
+ children[key] = (pid, ref) if key not in children else None
56
+
57
+ matches = []
58
+ for first, key in enumerate(keys):
59
+ if not children.get(key):
60
+ continue
61
+ for count, manifests in receipts[key[0]].items():
62
+ last = first + count - 1
63
+ if last >= len(keys) or rows[last][0] != rows[first][0] + count - 1:
64
+ continue
65
+ member_keys = keys[first:last + 1]
66
+ if not all(k and k[0] == key[0] and children.get(k) for k in member_keys):
67
+ continue
68
+ block = [children[k] for k in member_keys]
69
+ # The original manifest is the canonical JSON array of ordered
70
+ # child plan IDs. Matching both receipts proves this exact set.
71
+ data = packed([child[0] for child in block])
72
+ digest = hashlib.sha256(data).hexdigest()
73
+ if (digest, len(data)) in manifests:
74
+ matches.append((first, last, {"actor": key[0], "project_id": project,
75
+ "event_id": "legacy-set:" + digest, "references": [child[1] for child in block]}))
76
+ # Reused child plans can occur in overlapping historical sets. If the
77
+ # receipts do not establish a unique grouping, keep those file notices.
78
+ covered = Counter(i for first, last, _ in matches for i in range(first, last + 1))
79
+ return [(first, last, event) for first, last, event in matches
80
+ if first < limit and all(covered[i] == 1 for i in range(first, last + 1))]
@@ -0,0 +1,42 @@
1
+ """Send a signed text notification, without putting the webhook in logs or following redirects."""
2
+ import base64
3
+ import hmac
4
+ import json
5
+ import re
6
+ import time
7
+ from urllib.error import HTTPError
8
+ from urllib.parse import urlsplit
9
+ from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
10
+
11
+
12
+ def valid_webhook(url):
13
+ return bool(re.fullmatch(r"https://open\.feishu\.cn/open-apis/bot/v2/hook/[A-Za-z0-9-]+", url))
14
+
15
+
16
+ class NoRedirect(HTTPRedirectHandler):
17
+ def redirect_request(self, *args):
18
+ return None
19
+
20
+
21
+ def send_text(url, secret, text, *, mock=False):
22
+ parts = urlsplit(url)
23
+ local = mock and parts.scheme == "http" and parts.hostname == "127.0.0.1"
24
+ if not (local or valid_webhook(url)) or not secret:
25
+ raise ValueError("Unexpected Feishu recipient or empty signing key.")
26
+ timestamp = str(int(time.time()))
27
+ signature = base64.b64encode(hmac.digest((timestamp + "\n" + secret).encode(), b"", "sha256")).decode()
28
+ data = json.dumps({"timestamp": timestamp, "sign": signature, "msg_type": "text", "content": {"text": text}},
29
+ ensure_ascii=False).encode()
30
+ opener = build_opener(ProxyHandler({}), NoRedirect()) if local else build_opener(NoRedirect())
31
+ req = Request(url, data=data, headers={"Content-Type": "application/json; charset=utf-8"})
32
+ try:
33
+ with opener.open(req, timeout=6) as response:
34
+ reply = json.loads(response.read(16384))
35
+ except HTTPError as error:
36
+ return {"state": "http_error", "http_status": error.code}
37
+ except (OSError, ValueError):
38
+ return {"state": "unknown"}
39
+ code = reply.get("code", reply.get("StatusCode")) if isinstance(reply, dict) else None
40
+ if type(code) is not int:
41
+ return {"state": "unknown"}
42
+ return {"state": "accepted" if code == 0 else "rejected", "provider_code": code}
@@ -0,0 +1,193 @@
1
+ """Observe selected committed project shares and deliver one notice per revision.
2
+
3
+ The project ledger is opened read-only. Delivery attempts belong to the
4
+ operator's separate subscription, so a network failure cannot undo a share.
5
+ """
6
+ from contextlib import closing
7
+ from datetime import datetime, timezone
8
+ import json
9
+ from pathlib import Path
10
+ import sqlite3
11
+
12
+ from .review_sets import MAX_SET_FILES, completed_sets
13
+
14
+
15
+ def project_connection(control):
16
+ path = (Path(control) / ".taskcarry" / "state.sqlite3").resolve(strict=True)
17
+ return sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)
18
+
19
+
20
+ def last_sequence(db):
21
+ return db.execute("SELECT coalesce(max(sequence),0) FROM events").fetchone()[0]
22
+
23
+
24
+ def discussion_events(db, project, after, end, mode):
25
+ if mode not in ("mentions", "all"):
26
+ return []
27
+ kind = "discussion_attention" if mode == "mentions" else "discussion_shared"
28
+ result = []
29
+ for seq, raw in db.execute("SELECT sequence,payload FROM events WHERE kind=? AND sequence>? AND sequence<=? ORDER BY sequence",
30
+ (kind,after,end)):
31
+ value = json.loads(raw)
32
+ if value.get("project_id") == project:
33
+ result.append({**value, "event_kind":"discussion", "sequence":seq,
34
+ "event_id":"discussion:" + value["sha256"]})
35
+ return result
36
+
37
+
38
+ def visible_discussion(db, event, project):
39
+ """Only an explicitly enrolled internal group receives discussion metadata."""
40
+ from taskcarry.worker_channel import fingerprint
41
+ if event.get("project_id") != project:
42
+ return None
43
+ key = event["topic_id"]
44
+ pair = db.execute("SELECT v.value,c.value FROM records v JOIN records c ON c.collection='discussion_topics' AND c.key=? "
45
+ "WHERE v.collection='discussion_versions' AND v.key=?",(key,f"{key}:{event['revision']}")).fetchone()
46
+ if not pair:
47
+ return None
48
+ version, current = map(json.loads,pair)
49
+ if fingerprint(version) != event["sha256"] or version["author"] != event["actor"]:
50
+ return None
51
+ for ref in version["sources"] + current["sources"]:
52
+ owner = db.execute("SELECT json_extract(value,'$.owner_binding_id') FROM records WHERE collection='worker_sources' "
53
+ "AND key=?", (ref["reference_id"],)).fetchone()
54
+ if not owner or not visible_version(db, project, owner[0], ref):
55
+ return None
56
+ return version
57
+
58
+
59
+ def visible_version(db, project_id, actor, ref):
60
+ """An old worker_source event may mean a private save or a revocation."""
61
+ rid, revision = ref["reference_id"], ref["revision"]
62
+ pair = db.execute(
63
+ "SELECT v.value,c.value FROM records v JOIN records c ON c.collection='worker_sources' AND c.key=? "
64
+ "WHERE v.collection='worker_versions' AND v.key=?", (rid, f"source:{rid}:{revision}")
65
+ ).fetchone()
66
+ if not pair:
67
+ return None
68
+ version, current = map(json.loads, pair)
69
+ if any((s["project_id"], s["owner_binding_id"], s["visibility"], s["state"])
70
+ != (project_id, actor, "project", "active") for s in (version, current)):
71
+ return None
72
+ digest = version["content_sha256"]
73
+ if version["revision"] != revision or ref.get("content_sha256", digest) != digest:
74
+ return None
75
+ return version
76
+
77
+
78
+ def publications(control, project_id, after, selected=None, *, window=None, discussions="off"):
79
+ """Read one committed snapshot. Prefer a single batch event over its child records."""
80
+ groups = []
81
+ legacy = {}
82
+ grouped = set()
83
+ with closing(project_connection(control)) as db:
84
+ db.execute("BEGIN")
85
+ end = last_sequence(db)
86
+ if end < after:
87
+ raise ValueError("Project history no longer contains the subscription cursor.")
88
+ # Read through a set crossing the page boundary and any competing
89
+ # legacy manifest that overlaps it. The cursor still advances by events.
90
+ query = ("SELECT sequence,kind,payload FROM events WHERE sequence>? AND sequence<=? "
91
+ "AND kind IN ('worker_source','project_sources_shared') ORDER BY sequence LIMIT ?")
92
+ rows = [(seq, kind, json.loads(raw)) for seq, kind, raw in db.execute(
93
+ query, (after, end, window + 2 * MAX_SET_FILES if window else -1))]
94
+ sets = completed_sets(db, project_id, rows, window)
95
+ if window and len(rows) > window:
96
+ head = {(e["actor"], e["id"], e["revision"]) for _, kind, e in rows[:window] if kind == "worker_source"}
97
+ take = window
98
+ for i, (_, kind, e) in enumerate(rows[window:], window):
99
+ if kind == "project_sources_shared" and any(
100
+ (e["actor"], r["reference_id"], r["revision"]) in head for r in e["references"]):
101
+ take = i + 1
102
+ break
103
+ for first, last, _ in sets:
104
+ if first < take:
105
+ take = max(take, last + 1)
106
+ rows = rows[:take]
107
+ end = rows[-1][0]
108
+ # Keep each original event for visibility checks and partial selections.
109
+ # The verified set receipt suppresses only the member versions it covers.
110
+ batch_rows = [(rows[last][0], "completed_source_share_set", event)
111
+ for _, last, event in sets if last < len(rows)]
112
+ rows.extend(batch_rows)
113
+ for seq, kind, event in rows:
114
+ actor = event["actor"]
115
+ if kind == "worker_source":
116
+ refs = [{"reference_id": event["id"], "revision": event["revision"]}]
117
+ event_id = f"legacy:{actor}:{event['id']}:{event['revision']}"
118
+ else:
119
+ if event["project_id"] != project_id:
120
+ continue
121
+ refs = event["references"]
122
+ event_id = event["event_id"]
123
+ group = {"event_id": event_id, "event_kind": kind, "sequence": seq, "actor": actor, "refs": []}
124
+ for ref in refs:
125
+ key = (actor, ref["reference_id"], ref["revision"])
126
+ if selected is not None and key not in selected:
127
+ continue
128
+ source = visible_version(db, project_id, actor, ref)
129
+ if source is None:
130
+ continue
131
+ group["refs"].append({k: source[k] for k in ("reference_id", "revision", "content_sha256")})
132
+ if kind == "worker_source":
133
+ legacy[key] = group
134
+ else:
135
+ grouped.add(key)
136
+ if kind != "worker_source" and group["refs"]:
137
+ groups.append(group)
138
+ if selected is None:
139
+ groups.extend(discussion_events(db, project_id, after, end, discussions))
140
+ groups.extend(group for key, group in legacy.items() if key not in grouped)
141
+ return end, sorted(groups, key=lambda group: group["sequence"])
142
+
143
+
144
+ def matching_shares(control, project_id, after, targets):
145
+ """Return only the actor/version selections of a finite trial."""
146
+ selected = {(t["actor"], t["reference_id"], t["revision"]): t for t in targets}
147
+ _, groups = publications(control, project_id, after, selected)
148
+ return [{**selected[group["actor"], ref["reference_id"], ref["revision"]],
149
+ "sha256": ref["content_sha256"], "sequence": group["sequence"], "event_kind": group["event_kind"]}
150
+ for group in groups for ref in group["refs"]]
151
+
152
+
153
+ def notice(item):
154
+ return (f"TaskCarry 资料共享 · {item['label']}\n"
155
+ f"{item['reference_id']} · 第 {item['revision']} 版 · 指纹 {item['sha256'][:8]}\n"
156
+ "可在项目工作台查看。")
157
+
158
+
159
+ class DeliveryLog:
160
+ """One file per subscription. Claim before POST, never replay an ambiguous result."""
161
+
162
+ def __init__(self, path):
163
+ self.path = path
164
+ with closing(sqlite3.connect(path)) as db, db:
165
+ db.execute("CREATE TABLE IF NOT EXISTS attempts (actor TEXT, reference_id TEXT, "
166
+ "revision INTEGER, sha256 TEXT, sequence INTEGER, event_kind TEXT, "
167
+ "state TEXT, code INTEGER, utc TEXT, PRIMARY KEY(actor,reference_id,revision))")
168
+
169
+ def deliver(self, item, send, *, retry_rejected=False):
170
+ key = (item["actor"], item["reference_id"], item["revision"])
171
+ with closing(sqlite3.connect(self.path)) as db:
172
+ with db:
173
+ stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
174
+ claim = db.execute("INSERT OR IGNORE INTO attempts VALUES(?,?,?,?,?,?,'unknown',NULL,?)",
175
+ (*key, item["sha256"], item["sequence"], item["event_kind"], stamp))
176
+ if claim.rowcount == 0 and retry_rejected:
177
+ claim = db.execute("UPDATE attempts SET state='unknown',code=NULL,utc=? "
178
+ "WHERE actor=? AND reference_id=? AND revision=? AND sha256=? AND state='rejected'",
179
+ (stamp, *key, item["sha256"]))
180
+ if claim.rowcount != 1:
181
+ return None
182
+ # A crash or timeout can leave an unknown result. Re-running the
183
+ # subscription must not send a second copy to the same group.
184
+ result = send(notice(item))
185
+ with db:
186
+ db.execute("UPDATE attempts SET state=?,code=? WHERE actor=? AND reference_id=? AND revision=?",
187
+ (result["state"], result.get("provider_code", result.get("http_status")), *key))
188
+ return result
189
+
190
+ def receipts(self):
191
+ with closing(sqlite3.connect(self.path)) as db:
192
+ db.row_factory = sqlite3.Row
193
+ return [dict(row) for row in db.execute("SELECT * FROM attempts ORDER BY sequence")]