eq-layer 0.1.0__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.
@@ -0,0 +1,393 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class GoalCandidate:
9
+ """A structurally observable prior turn that may anchor a short reference.
10
+
11
+ Candidate does not mean semantically unresolved or correct. It only means
12
+ the turn is eligible for conservative reference resolution.
13
+ """
14
+
15
+ turn_index: int
16
+ role: str
17
+ kind: str
18
+ excerpt: str
19
+ evidence: tuple[str, ...] = ()
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class DialogueReferenceState:
24
+ """Conservative structural state for short deictic/continuation turns."""
25
+
26
+ active: bool
27
+ form: str = "none"
28
+ resolved: bool = False
29
+ target_turn_index: int | None = None
30
+ target_role: str = ""
31
+ target_excerpt: str = ""
32
+ anchor_turn_index: int | None = None
33
+ anchor_excerpt: str = ""
34
+ candidate_stack: tuple[GoalCandidate, ...] = ()
35
+ requires_clarification: bool = False
36
+ confidence: float = 0.0
37
+ evidence_level: str = "structural"
38
+ evidence: tuple[str, ...] = ()
39
+
40
+
41
+ _CONTINUE_FORMS = {
42
+ "devam",
43
+ "devam et",
44
+ "continue",
45
+ "go on",
46
+ "keep going",
47
+ }
48
+
49
+ _EXECUTE_REFERENCE_FORMS = {
50
+ "yap",
51
+ "bunu yap",
52
+ "şunu yap",
53
+ "onu yap",
54
+ "do it",
55
+ "do this",
56
+ "do that",
57
+ }
58
+
59
+ _REVISE_REFERENCE_FORMS = {
60
+ "düzelt",
61
+ "bunu düzelt",
62
+ "şunu düzelt",
63
+ "onu düzelt",
64
+ "fix it",
65
+ "fix this",
66
+ "fix that",
67
+ }
68
+
69
+ _ASSISTANT_OFFER_MARKERS = (
70
+ "istersen",
71
+ "yapabilirim",
72
+ "yapayım",
73
+ "yapabiliriz",
74
+ "devam edebilirim",
75
+ "geçebilirim",
76
+ "would you like me to",
77
+ "shall i",
78
+ )
79
+
80
+ _USER_GOAL_MARKERS = (
81
+ "yap",
82
+ "ekle",
83
+ "düzelt",
84
+ "kontrol et",
85
+ "bak",
86
+ "gönder",
87
+ "oluştur",
88
+ "sil",
89
+ "çalıştır",
90
+ "araştır",
91
+ "incele",
92
+ "durum ne",
93
+ "son durum",
94
+ "neden",
95
+ "nasıl",
96
+ "anlat",
97
+ "açıkla",
98
+ "do",
99
+ "fix",
100
+ "check",
101
+ "run",
102
+ "explain",
103
+ "why",
104
+ "how",
105
+ )
106
+
107
+
108
+ def _normalise(text: str) -> str:
109
+ lowered = text.lower().replace("\u0307", "")
110
+ return " ".join(re.sub(r"[^\w\s]", " ", lowered).split())
111
+
112
+
113
+ def _excerpt(text: str) -> str:
114
+ return " ".join(text.strip().split())[:280]
115
+
116
+
117
+ def _previous_index(
118
+ messages: list[dict],
119
+ before: int,
120
+ *,
121
+ role: str | None = None,
122
+ ) -> int | None:
123
+ for index in range(before - 1, -1, -1):
124
+ if role is None or messages[index].get("role") == role:
125
+ return index
126
+ return None
127
+
128
+
129
+ def _contains_phrase(text: str, phrase: str) -> bool:
130
+ normalised = _normalise(text)
131
+ needle = _normalise(phrase)
132
+ if not normalised or not needle:
133
+ return False
134
+ return f" {needle} " in f" {normalised} "
135
+
136
+
137
+ _ENGLISH_OFFER_ACTION_RE = re.compile(
138
+ r"\b(?:i can|i could)\s+"
139
+ r"(?:add|check|run|fix|review|test|continue|create|generate|compare|"
140
+ r"audit|search|inspect|update|remove|write|draft|explain|summarize|"
141
+ r"summarise|analyze|analyse|rerun|evaluate|help)\b",
142
+ re.IGNORECASE,
143
+ )
144
+
145
+ _NEXT_STEP_OFFER_RE = re.compile(
146
+ r"\b(?:next step|sıradaki adım|sonraki adım)\s*[:\-]",
147
+ re.IGNORECASE,
148
+ )
149
+
150
+
151
+ def _has_offer(text: str) -> bool:
152
+ if any(
153
+ _contains_phrase(text, marker)
154
+ for marker in _ASSISTANT_OFFER_MARKERS
155
+ ):
156
+ return True
157
+ return bool(
158
+ _ENGLISH_OFFER_ACTION_RE.search(text)
159
+ or _NEXT_STEP_OFFER_RE.search(text)
160
+ )
161
+
162
+
163
+ def _looks_like_user_goal(text: str) -> bool:
164
+ if not text.strip():
165
+ return False
166
+ return any(
167
+ _contains_phrase(text, marker)
168
+ for marker in _USER_GOAL_MARKERS
169
+ )
170
+
171
+
172
+ def _candidate_stack(
173
+ messages: list[dict],
174
+ current_user_index: int,
175
+ ) -> tuple[GoalCandidate, ...]:
176
+ candidates: list[GoalCandidate] = []
177
+
178
+ assistant_index = _previous_index(
179
+ messages,
180
+ current_user_index,
181
+ role="assistant",
182
+ )
183
+ if assistant_index is not None:
184
+ assistant_text = str(messages[assistant_index].get("content", ""))
185
+ if _has_offer(assistant_text):
186
+ candidates.append(
187
+ GoalCandidate(
188
+ turn_index=assistant_index,
189
+ role="assistant",
190
+ kind="assistant_offer",
191
+ excerpt=_excerpt(assistant_text),
192
+ evidence=("recent_assistant_offer_marker",),
193
+ )
194
+ )
195
+
196
+ for index in range(current_user_index - 1, -1, -1):
197
+ if messages[index].get("role") != "user":
198
+ continue
199
+ text = str(messages[index].get("content", ""))
200
+ if _looks_like_user_goal(text):
201
+ candidates.append(
202
+ GoalCandidate(
203
+ turn_index=index,
204
+ role="user",
205
+ kind="prior_user_goal",
206
+ excerpt=_excerpt(text),
207
+ evidence=("recent_user_goal_marker",),
208
+ )
209
+ )
210
+ break
211
+
212
+ return tuple(
213
+ sorted(
214
+ candidates,
215
+ key=lambda item: item.turn_index,
216
+ reverse=True,
217
+ )
218
+ )
219
+
220
+
221
+ def _resolve(
222
+ *,
223
+ form: str,
224
+ target_index: int,
225
+ messages: list[dict],
226
+ stack: tuple[GoalCandidate, ...],
227
+ evidence: tuple[str, ...],
228
+ ) -> DialogueReferenceState:
229
+ target = messages[target_index]
230
+ anchor_index = None
231
+ anchor_excerpt = ""
232
+ if target.get("role") == "assistant":
233
+ anchor_index = _previous_index(messages, target_index, role="user")
234
+ if anchor_index is not None:
235
+ anchor_excerpt = _excerpt(
236
+ str(messages[anchor_index].get("content", ""))
237
+ )
238
+
239
+ return DialogueReferenceState(
240
+ active=True,
241
+ form=form,
242
+ resolved=True,
243
+ target_turn_index=target_index,
244
+ target_role=str(target.get("role", "")),
245
+ target_excerpt=_excerpt(str(target.get("content", ""))),
246
+ anchor_turn_index=anchor_index,
247
+ anchor_excerpt=anchor_excerpt,
248
+ candidate_stack=stack,
249
+ requires_clarification=False,
250
+ confidence=1.0,
251
+ evidence=("short_reference_form", *evidence),
252
+ )
253
+
254
+
255
+ def _unresolved(
256
+ *,
257
+ form: str,
258
+ stack: tuple[GoalCandidate, ...],
259
+ evidence: tuple[str, ...],
260
+ ) -> DialogueReferenceState:
261
+ return DialogueReferenceState(
262
+ active=True,
263
+ form=form,
264
+ resolved=False,
265
+ candidate_stack=stack,
266
+ requires_clarification=True,
267
+ confidence=0.0,
268
+ evidence=("short_reference_form", *evidence),
269
+ )
270
+
271
+
272
+ def infer_dialogue_reference(messages: list[dict]) -> DialogueReferenceState:
273
+ """Resolve only a narrow set of short references with structural evidence.
274
+
275
+ This is QUD-inspired bookkeeping, not a full semantic QUD model. It refuses
276
+ to resolve stale/ambiguous `do it` forms and never uses a candidate as proof
277
+ that a goal is truly unresolved.
278
+ """
279
+
280
+ if not messages:
281
+ return DialogueReferenceState(
282
+ active=False,
283
+ evidence=("empty_transcript",),
284
+ )
285
+
286
+ current_user_index = _previous_index(
287
+ messages,
288
+ len(messages),
289
+ role="user",
290
+ )
291
+ if current_user_index is None:
292
+ return DialogueReferenceState(
293
+ active=False,
294
+ evidence=("no_user_turn",),
295
+ )
296
+
297
+ current = _normalise(
298
+ str(messages[current_user_index].get("content", ""))
299
+ )
300
+ stack = _candidate_stack(messages, current_user_index)
301
+
302
+ if current in _CONTINUE_FORMS:
303
+ form = "continue"
304
+ elif current in _EXECUTE_REFERENCE_FORMS:
305
+ form = "execute_reference"
306
+ elif current in _REVISE_REFERENCE_FORMS:
307
+ form = "revise_reference"
308
+ else:
309
+ return DialogueReferenceState(
310
+ active=False,
311
+ candidate_stack=stack,
312
+ evidence=("no_supported_short_reference",),
313
+ )
314
+
315
+ assistant_index = _previous_index(
316
+ messages,
317
+ current_user_index,
318
+ role="assistant",
319
+ )
320
+ prior_user_index = _previous_index(
321
+ messages,
322
+ current_user_index,
323
+ role="user",
324
+ )
325
+
326
+ if assistant_index is None:
327
+ return _unresolved(
328
+ form=form,
329
+ stack=stack,
330
+ evidence=("no_prior_assistant_turn",),
331
+ )
332
+
333
+ assistant_text = str(messages[assistant_index].get("content", ""))
334
+ assistant_has_offer = _has_offer(assistant_text)
335
+
336
+ if form == "execute_reference":
337
+ if assistant_has_offer:
338
+ return _resolve(
339
+ form=form,
340
+ target_index=assistant_index,
341
+ messages=messages,
342
+ stack=stack,
343
+ evidence=("immediate_assistant_offer",),
344
+ )
345
+ return _unresolved(
346
+ form=form,
347
+ stack=stack,
348
+ evidence=("no_immediate_assistant_offer",),
349
+ )
350
+
351
+ if form == "revise_reference":
352
+ return _resolve(
353
+ form=form,
354
+ target_index=assistant_index,
355
+ messages=messages,
356
+ stack=stack,
357
+ evidence=("immediate_assistant_output",),
358
+ )
359
+
360
+ if assistant_has_offer:
361
+ return _resolve(
362
+ form=form,
363
+ target_index=assistant_index,
364
+ messages=messages,
365
+ stack=stack,
366
+ evidence=("immediate_assistant_offer",),
367
+ )
368
+
369
+ if "?" in assistant_text:
370
+ return _unresolved(
371
+ form=form,
372
+ stack=stack,
373
+ evidence=("assistant_question_blocks_implicit_continue",),
374
+ )
375
+
376
+ if prior_user_index is not None:
377
+ prior_user_text = str(
378
+ messages[prior_user_index].get("content", "")
379
+ )
380
+ if _looks_like_user_goal(prior_user_text):
381
+ return _resolve(
382
+ form=form,
383
+ target_index=prior_user_index,
384
+ messages=messages,
385
+ stack=stack,
386
+ evidence=("recent_prior_user_goal",),
387
+ )
388
+
389
+ return _unresolved(
390
+ form=form,
391
+ stack=stack,
392
+ evidence=("no_safe_goal_anchor",),
393
+ )
eq_layer/intent.py ADDED
@@ -0,0 +1,199 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from typing import Protocol
6
+
7
+ from .intent_belief import IntentBelief, IntentRiskDecision
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class IntentState:
12
+ """Conservative, inspectable representation of what the user is asking for."""
13
+
14
+ kind: str
15
+ canonical_request: str
16
+ response_mode: str
17
+ confidence: float
18
+ explicit: bool
19
+ needs_clarification: bool
20
+ constraints: tuple[str, ...] = ()
21
+ evidence: tuple[str, ...] = ()
22
+ belief: IntentBelief | None = None
23
+ risk_decision: IntentRiskDecision | None = None
24
+
25
+
26
+ class IntentAdapter(Protocol):
27
+ name: str
28
+
29
+ def infer(self, messages: list[dict]) -> IntentState: ...
30
+
31
+
32
+ ACTION_MARKERS = (
33
+ "yap",
34
+ "ekle",
35
+ "düzelt",
36
+ "kontrol et",
37
+ "bak",
38
+ "gönder",
39
+ "oluştur",
40
+ "sil",
41
+ "devam et",
42
+ "çalıştır",
43
+ "araştır",
44
+ "incele",
45
+ )
46
+
47
+ STATUS_MARKERS = (
48
+ "durum ne",
49
+ "son durum",
50
+ "ne kadar kaldı",
51
+ "bitti mi",
52
+ "oluyor mu",
53
+ "çalışıyor mu",
54
+ )
55
+
56
+ EXPLANATION_MARKERS = (
57
+ "neden",
58
+ "niçin",
59
+ "nasıl",
60
+ "anlat",
61
+ "açıkla",
62
+ "ne demek",
63
+ )
64
+
65
+ VAGUE_FORMS = (
66
+ "bu",
67
+ "bunu",
68
+ "şu",
69
+ "şunu",
70
+ "onu",
71
+ "şey",
72
+ )
73
+
74
+ CONSTRAINT_MARKERS = (
75
+ ("kısa", "brief"),
76
+ ("net", "direct"),
77
+ ("sadece", "scope_limited"),
78
+ ("detaylı", "detailed"),
79
+ ("tahmin etme", "no_guess"),
80
+ ("uydurma", "no_guess"),
81
+ )
82
+
83
+
84
+ @dataclass
85
+ class HeuristicIntent:
86
+ name: str = "heuristic"
87
+
88
+ def infer(self, messages: list[dict]) -> IntentState:
89
+ user_turns = [m.get("content", "") for m in messages if m.get("role") == "user"]
90
+ current = user_turns[-1].strip() if user_turns else ""
91
+ low = self._normalise(current)
92
+ constraints = self._constraints(low)
93
+
94
+ if not current:
95
+ return self._state(
96
+ "unknown", current, "clarify", 0.0,
97
+ explicit=False, needs_clarification=True,
98
+ constraints=constraints, evidence=("empty_user_turn",),
99
+ )
100
+
101
+ if self._is_vague(low):
102
+ return self._state(
103
+ "unknown", current, "clarify", 0.2,
104
+ explicit=False, needs_clarification=True,
105
+ constraints=constraints, evidence=("vague_deictic",),
106
+ )
107
+
108
+ marker = self._first_marker(low, STATUS_MARKERS)
109
+ if marker:
110
+ return self._state(
111
+ "status_check", current, "direct", 0.94,
112
+ explicit=True, needs_clarification=False,
113
+ constraints=constraints, evidence=(f"status:{marker}",),
114
+ )
115
+
116
+ marker = self._first_marker(low, ACTION_MARKERS)
117
+ if marker:
118
+ return self._state(
119
+ "action_request", current, "execute", 0.90,
120
+ explicit=True, needs_clarification=False,
121
+ constraints=constraints, evidence=(f"action:{marker}",),
122
+ )
123
+
124
+ marker = self._first_marker(low, EXPLANATION_MARKERS)
125
+ if marker:
126
+ return self._state(
127
+ "explanation", current, "explain", 0.86,
128
+ explicit=True, needs_clarification=False,
129
+ constraints=constraints, evidence=(f"explain:{marker}",),
130
+ )
131
+
132
+ if current.rstrip().endswith("?"):
133
+ return self._state(
134
+ "question", current, "direct", 0.74,
135
+ explicit=True, needs_clarification=False,
136
+ constraints=constraints, evidence=("question_mark",),
137
+ )
138
+
139
+ return self._state(
140
+ "statement", current, "contextual", 0.50,
141
+ explicit=False, needs_clarification=False,
142
+ constraints=constraints, evidence=("no_explicit_request_marker",),
143
+ )
144
+
145
+ def _state(
146
+ self,
147
+ kind: str,
148
+ original: str,
149
+ response_mode: str,
150
+ confidence: float,
151
+ *,
152
+ explicit: bool,
153
+ needs_clarification: bool,
154
+ constraints: tuple[str, ...],
155
+ evidence: tuple[str, ...],
156
+ ) -> IntentState:
157
+ return IntentState(
158
+ kind=kind,
159
+ canonical_request=self._canonical(kind, original, constraints),
160
+ response_mode=response_mode,
161
+ confidence=confidence,
162
+ explicit=explicit,
163
+ needs_clarification=needs_clarification,
164
+ constraints=constraints,
165
+ evidence=evidence,
166
+ )
167
+
168
+ def _canonical(self, kind: str, original: str, constraints: tuple[str, ...]) -> str:
169
+ prefix = {
170
+ "action_request": "Perform the explicit user request",
171
+ "status_check": "Check the current status and report the result",
172
+ "explanation": "Explain the requested point",
173
+ "question": "Answer the user's question directly",
174
+ "statement": "Respond to the user's statement without inventing a request",
175
+ "unknown": "Clarify what the user wants before acting",
176
+ }[kind]
177
+ request = original.strip() or "<empty>"
178
+ suffix = f" Constraints: {', '.join(constraints)}." if constraints else ""
179
+ return f'{prefix}: "{request}".{suffix}'
180
+
181
+ def _normalise(self, text: str) -> str:
182
+ return " ".join(text.lower().split())
183
+
184
+ def _first_marker(self, text: str, markers: tuple[str, ...]) -> str | None:
185
+ for marker in markers:
186
+ if re.search(rf"(?<!\w){re.escape(marker)}(?!\w)", text):
187
+ return marker
188
+ return None
189
+
190
+ def _is_vague(self, text: str) -> bool:
191
+ bare = text.strip(" ?!.,;:")
192
+ return bare in VAGUE_FORMS and len(bare.split()) <= 2
193
+
194
+ def _constraints(self, text: str) -> tuple[str, ...]:
195
+ found = []
196
+ for marker, constraint in CONSTRAINT_MARKERS:
197
+ if marker in text and constraint not in found:
198
+ found.append(constraint)
199
+ return tuple(found)