"""Local, conservative scope admission. No model calls or industry defaults.""" import json import re import time import uuid from src.modules.skill.domain.models import SkillError, digest def outline(requirement): """Check four independent dimensions, never text length. Unknown domains deliberately require confirmation instead of guessing a complete industry schema. The full user text remains the binding scope. """ objects=list(dict.fromkeys(re.findall(r'订单|库存|客户|工单|设备|商品|员工|合同|运单|车辆|费用|任务|联系人',requirement))) matches=re.finditer(r'查询|检索|搜索|新增|添加|创建|修改|更新|调整|删除|出库|入库|占用|预采购|计算|校验|登记|跟踪|报表|审批|批量导入|多仓库',requirement) aliases={'检索':'查询','搜索':'查询','添加':'新增','创建':'新增','更新':'修改','调整':'修改'} operations=list(dict.fromkeys(aliases.get(m.group(),m.group()) for m in matches if not re.search(r'不(?:要|做|需要|包含)|暂不|下轮',requirement[max(0,m.start()-5):m.start()]))) rule=bool(re.search(r'不得|不能|不允许|仅|只能|必须|不超过|至少|大于|小于|不能为空|唯一|非负|找不到|不存在|未找到',requirement)) acceptance=bool(re.search(r'显示|返回|验收|测试|提示|查不到|未找到|拒绝',requirement)) sensitive_text=re.sub(r'(?:无需|不需要|不)(?:连接|接入|接|写入|修改)[^,,。;;\n]*','',requirement) sensitive=bool(re.search(r'权限|审批|真实.*(?:写入|修改|数据库)|生产.*(?:写入|修改)',sensitive_text)) dimensions={'business_objects':bool(objects),'core_operations':bool(operations),'key_rules':rule,'acceptance':acceptance} questions=[] if not objects:questions.append('首版要管理哪一种业务对象?') if not operations:questions.append('首版最重要的查询或操作是什么?') if not rule:questions.append('哪些输入或状态变化需要允许、拒绝?如有状态,请给出状态值和转换规则。') if not acceptance:questions.append('完成一个怎样的操作、看到什么结果,就算首版通过?') if sensitive:questions.insert(0,'涉及的角色权限、审批条件或真实数据写入范围是什么?这些能力未明确前不会连接或执行。') explicit=[] for feature in ['报表','审批','批量导入','多仓库','多角色','删除','新增','新建']: if feature in requirement:explicit.append(feature) return {'problem':requirement,'functions':operations or ['先确认一个主要业务操作'], 'objects':objects,'dimensions':dimensions, 'can_start':bool(objects and operations) and not sensitive, 'excluded':[label for label,words in [('报表',['报表']),('多角色审批',['审批','权限','多角色']),('批量导入',['导入']),('多仓库',['仓库']),('真实系统写入',['真实','生产'])] if not any(x in requirement for x in words)], 'explicit_features':explicit,'assumptions':[ '仅在本地隔离演示环境验证,合成数据量按用户明确要求保留;不接客户真实数据库。', '未明确的业务规则保持待定,不把知识库行业惯例变成已确认需求。'], 'questions':questions[:3], 'acceptance':['逐项验证原需求中的核心操作与结果,错误输入得到明确提示。', '未明确状态规则时,建议人工填写业务状态文本,不预设行业状态机;用户确认此假设后才实现。'] if not rule else ['按原需求逐项执行核心操作、关键规则及可见结果;原文要求全部保留。'], 'ready':all(dimensions.values()) and not sensitive, 'knowledge_policy':'规则和模板仅为候选,不构成需求授权', 'implementation_policy':'复用现有框架;本轮仅实现确认范围,后续新增进入新版本,以定向差异修改保留其他功能。'} def scope_estimate(text,functions,acceptance,limits): """Planning heuristic only; actual preflight and ledger stay authoritative.""" parts={'output_allowances':limits['design_output']+limits['code_output']+limits['repair_output']*limits['max_repairs'], 'requirement_and_envelopes':(len(text.encode('utf8'))+2048)*(2+limits['max_repairs']), 'feature_allowance':1800*len(functions),'acceptance_allowance':800*len(acceptance), 'data_generation_allowance':max([len(n)*512 for n in re.findall(r'(\d+)\s*条',text)] or [0])} return {'estimated_tokens':sum(parts.values()),'parts':parts,'method':'scope-planning-heuristic-v1', 'actual_tokens':None,'guaranteed':False} class BusinessScopes: def __init__(self,engine): self.engine=engine with engine.store.connect() as db: db.execute('CREATE TABLE IF NOT EXISTS business_scopes(id TEXT PRIMARY KEY,owner TEXT NOT NULL,request_key TEXT NOT NULL,body TEXT NOT NULL,UNIQUE(owner,request_key))') def get(self,actor,key): self.engine.spec(actor,'business-app') with self.engine.store.connect() as db: row=db.execute('SELECT body FROM business_scopes WHERE id=? AND owner=?',(key,actor.user_id)).fetchone() if not row:raise SkillError('SCOPE_NOT_FOUND','范围方案不存在或不可见。',404) return json.loads(row['body']) def limits(self,actor): limits=getattr(self.engine,'resource_limits',None) if not limits:return None limits=dict(limits) if hasattr(self.engine,'skills'): spec=self.engine.spec(actor,'business-app') budget=self.engine.skills.read_draft(self.engine.author,spec['skill'])['body']['budget'] for name in ('max_tokens','max_model_calls','max_repairs','max_seconds'): limits[name]=min(limits[name],budget[name]) return limits def prepare(self,actor,requirement,key,*,parent_id=None,base_run=None,supplement=None): self.engine.spec(actor,'business-app') parent=self.get(actor,parent_id) if parent_id else None if parent: if parent['original_requirement']!=requirement:raise SkillError('SCOPE_REQUIREMENT_CHANGED','原需求不可覆盖;补充内容另存新版本。',409) base_run=base_run or parent.get('base_run') prior=None if base_run: prior=self.engine.job(actor,base_run) original=self.engine.store.get(base_run) if original['owner_id']!=actor.user_id or prior['scenario']!='business-app':raise SkillError('SCOPE_BASELINE_INVALID','只能引用本人业务任务。',403) if prior['status'] not in {'verified','failed','cancelled'} or any(c['state'] in {'unknown','reserved'} for c in prior['model_calls']): raise SkillError('SCOPE_BASELINE_UNCERTAIN','运行中或结果未知的任务不能借调整范围重放;先核对原结果与预留。',409) supplements=[*(parent.get('supplements',[]) if parent else []),*([supplement] if supplement else [])] text=requirement+''.join('\n用户补充:'+s for s in supplements) if len(text.encode('utf8'))>6000:raise SkillError('SCOPE_TOO_LARGE','本轮需求与补充合计超出6000 UTF-8字节,请拆分下一轮;原文保留,未截断。',409) card=outline(text) for entry in reversed(supplements): only=re.search(r'本轮(?:只|仅)(?:做|实现|保留)?([^,,。;;\n]+)',entry) if only: selected=[f for f in outline(only.group(1))['functions'] if f!='先确认一个主要业务操作'] if selected: deferred=[f for f in card['functions'] if f not in selected] card.update(functions=selected,deferred_by_user=deferred,phases=[selected,*([deferred] if deferred else [])]) break limits=self.limits(actor) if limits: card['all_functions']=list(card['functions']) card['deferred_functions']=card.get('deferred_by_user',[]) acceptance_section=re.split(r'验收(?:点|条件|标准)?[::]',text,maxsplit=1) stated=[] if len(acceptance_section)>1: stated=[p.strip(' \n-;;') for p in re.split(r'[;;\n]+',acceptance_section[1]) if p.strip(' \n-;;')] if '订单' in card['objects'] and '查询' in card['functions'] and '修改' in card['functions']: card['acceptance']=['按订单号查询当前状态。','人工填写并提交本轮确认的订单状态。','再次查询同一订单,状态必须等于刚提交的新值。','空订单号、未知订单号和空状态得到明确提示且不写入。'] if not card['dimensions']['key_rules']:card['assumptions'].append('本阶段由人工填写状态文本,不预设状态枚举或自动流转;后续确认业务规则后再增量实现。') data_counts=re.findall(r'(\d+)\s*条',text) data_acceptance=['核对原需求中 '+n+' 条数据的总记录数、表格展示或分页回读,不用少量样例代替。' for n in dict.fromkeys(data_counts)] card['data_requirements']=data_acceptance current_points=[];later_points=[] for point in stated: related=[f for f in card['functions']+card['deferred_functions'] if f in point or (f=='预采购' and '采购' in point) or (f=='查询' and re.search('检索|搜索',point)) or (f=='修改' and re.search('调整|更新',point))] if related and any(f in card['deferred_functions'] for f in related):later_points.append(point) else:current_points.append(point) if stated:card['acceptance']=current_points or ['验证当前阶段核心操作及必要的无效输入处理;后续功能的验收保留到对应阶段。'] card['acceptance']+=data_acceptance allowance=limits['max_tokens']*limits['scope_budget_percent']//100 full=scope_estimate(text,card['functions'],card['acceptance'],limits) adjusted=full['estimated_tokens']>allowance if adjusted: cap=min(limits['max_features'],len(card['functions'])) while cap>0 and scope_estimate(text,card['functions'][:cap],card['acceptance'][:limits['max_acceptance']],limits)['estimated_tokens']>allowance:cap-=1 card['deferred_functions']=card['functions'][cap:]+card['deferred_functions'] card['functions']=card['functions'][:cap] later_points=[];current_points=[] for point in stated or card['acceptance']: related=outline(point)['functions'] deferred=any(f in card['deferred_functions'] for f in related) or ('预采购' in card['deferred_functions'] and '采购' in point) (later_points if deferred else current_points).append(point) card['acceptance']=current_points[:limits['max_acceptance']] later_points+=current_points[limits['max_acceptance']:] card['deferred_acceptance']=later_points card['phases']=[card['functions']]+([card['deferred_functions']] if card['deferred_functions'] else []) card['execution_mode']='adjusted' if adjusted or card.get('deferred_by_user') else 'original' estimate=scope_estimate(text,card['functions'],card['acceptance'],limits) card['budget_estimate']={**estimate,'original_estimated_tokens':full['estimated_tokens'], 'planning_allowance':allowance,'task_token_limit':limits['max_tokens'], 'reserve_percent':100-limits['scope_budget_percent'], 'fits':bool(card['functions']) and estimate['estimated_tokens']<=allowance} if not card['budget_estimate']['fits']:card['can_start']=False card['resource_budget']=limits from src.modules.governance.resource_limits import timing_guidance card['timeout_guidance']=timing_guidance(self.engine.store) card['phase_rule']='预算可覆盖时完整保留原需求;只有预算不足或客户主动调整才分期,后续阶段需另行确认。' # Explicit exclusions require their own confirmation after a failed run; # never retroactively change that run, its tests or its acceptance. direct=card['ready'] and card.get('execution_mode','original')=='original' and card.get('budget_estimate',{}).get('fits',True) and not parent and not base_run value={'id':'scope-'+uuid.uuid4().hex,'original_requirement':requirement,'requirement':text, 'supplements':supplements,'parent_id':parent_id,'base_run':base_run, 'version':parent['version']+1 if parent else 1,'card':card, 'status':'confirmed' if direct else 'waiting_scope', 'confirmation':'explicit-requirement' if direct else None, 'new_acceptance_baseline':bool(base_run),'created_at':time.time(), 'prior_requirement':prior['requirement'] if prior else None, 'affected_tests':card['functions']+['原有未变更主流程回归'] if base_run else card['functions']} if prior: value['affected_tests']+=['上次失败点 '+f['path'] for f in (prior.get('diagnostics') or {}).get('failures',[]) if isinstance(f,dict) and isinstance(f.get('path'),str)] value['digest']=digest(value) fingerprint=digest({'requirement':requirement,'parent_id':parent_id,'base_run':base_run,'supplement':supplement}) value['request_digest']=fingerprint with self.engine.store.connect() as db: old=db.execute('SELECT body FROM business_scopes WHERE owner=? AND request_key=?',(actor.user_id,key)).fetchone() if old: old=json.loads(old['body']) if old['request_digest']!=fingerprint:raise SkillError('IDEMPOTENCY_CONFLICT','同一请求对应不同范围。',409) return old db.execute('INSERT INTO business_scopes VALUES(?,?,?,?)',(value['id'],actor.user_id,key,json.dumps(value,ensure_ascii=False))) return value def confirm(self,actor,key,expected): current=self.get(actor,key) if current['card'].get('resource_budget')!=self.limits(actor): updated=self.prepare(actor,current['original_requirement'],'budget-refresh:'+key+':'+digest(self.limits(actor)),parent_id=key) raise SkillError('SCOPE_BUDGET_CHANGED','预算配置已变化,请查看重新计算的范围和预算后确认。',409,details={'scope':updated}) with self.engine.store.connect() as db: row=db.execute('SELECT body FROM business_scopes WHERE id=? AND owner=?',(key,actor.user_id)).fetchone() current=json.loads(row['body']) if current['digest']!=expected:raise SkillError('SCOPE_CHANGED','范围版本已变化,请重新确认。',409) if not current['card'].get('can_start',outline(current['requirement'])['can_start']): raise SkillError('BUSINESS_SCOPE_INCOMPLETE','还缺少影响正确性的业务对象、操作或重要权限规则,请先补充;尚未调用模型。',409) if current['base_run'] and not current['supplements']: raise SkillError('SCOPE_CHANGE_REQUIRED','请先说明本轮新增或调整的范围,再确认新验收基线。',409) current.update(status='confirmed',confirmation='explicit-minimal-scope',confirmed_at=current.get('confirmed_at') or time.time()) db.execute('UPDATE business_scopes SET body=? WHERE id=?',(json.dumps(current,ensure_ascii=False),key)) return current def baseline(self,actor,requirement,key): scope=self.get(actor,key) if scope['card'].get('resource_budget')!=self.limits(actor): raise SkillError('SCOPE_BUDGET_CHANGED','预算配置已变化,请更新范围卡并重新确认,尚未启动调用。',409) if scope['status']!='confirmed' or scope['requirement']!=requirement: raise SkillError('BUSINESS_SCOPE_CONFIRMATION_REQUIRED','请先确认当前版本的首版范围,确认前不调用模型。',409) return {k:scope[k] for k in ['id','digest','version','original_requirement','supplements','requirement','card','confirmation','base_run','new_acceptance_baseline','affected_tests']}